From b2f82598d8ecdc86bd9a6d50af173c0de4f4705c Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Mon, 13 Nov 2023 20:51:08 +0000 Subject: [PATCH 1/2] feat: add data store and engine services docs: keep the API doc up-to-date with recent changes PiperOrigin-RevId: 582014920 Source-Link: https://github.com/googleapis/googleapis/commit/10f46e91a68fbfb4a0325e96ba6702347a6b2ed3 Source-Link: https://github.com/googleapis/googleapis-gen/commit/5f8c4c25960faa8f285f6108f441a7a85349b6c7 Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLWNsb3VkLWRpc2NvdmVyeWVuZ2luZS8uT3dsQm90LnlhbWwiLCJoIjoiNWY4YzRjMjU5NjBmYWE4ZjI4NWY2MTA4ZjQ0MWE3YTg1MzQ5YjZjNyJ9 --- .../v1/.coveragerc | 13 + .../google-cloud-discoveryengine/v1/.flake8 | 33 + .../v1/MANIFEST.in | 2 + .../v1/README.rst | 49 + .../v1/docs/_static/custom.css | 3 + .../v1/docs/conf.py | 376 + .../discoveryengine_v1/completion_service.rst | 6 + .../conversational_search_service.rst | 10 + .../discoveryengine_v1/document_service.rst | 10 + .../discoveryengine_v1/schema_service.rst | 10 + .../discoveryengine_v1/search_service.rst | 10 + .../v1/docs/discoveryengine_v1/services_.rst | 11 + .../v1/docs/discoveryengine_v1/types_.rst | 6 + .../discoveryengine_v1/user_event_service.rst | 6 + .../v1/docs/index.rst | 7 + .../google/cloud/discoveryengine/__init__.py | 165 + .../cloud/discoveryengine/gapic_version.py | 16 + .../v1/google/cloud/discoveryengine/py.typed | 2 + .../cloud/discoveryengine_v1/__init__.py | 166 + .../discoveryengine_v1/gapic_metadata.json | 468 ++ .../cloud/discoveryengine_v1/gapic_version.py | 16 + .../google/cloud/discoveryengine_v1/py.typed | 2 + .../discoveryengine_v1/services/__init__.py | 15 + .../services/completion_service/__init__.py | 22 + .../completion_service/async_client.py | 386 + .../services/completion_service/client.py | 594 ++ .../completion_service/transports/__init__.py | 38 + .../completion_service/transports/base.py | 168 + .../completion_service/transports/grpc.py | 303 + .../transports/grpc_asyncio.py | 302 + .../completion_service/transports/rest.py | 574 ++ .../conversational_search_service/__init__.py | 22 + .../async_client.py | 971 +++ .../conversational_search_service/client.py | 1205 ++++ .../conversational_search_service/pagers.py | 140 + .../transports/__init__.py | 38 + .../transports/base.py | 241 + .../transports/grpc.py | 449 ++ .../transports/grpc_asyncio.py | 448 ++ .../transports/rest.py | 1164 +++ .../services/document_service/__init__.py | 22 + .../services/document_service/async_client.py | 1109 +++ .../services/document_service/client.py | 1322 ++++ .../services/document_service/pagers.py | 140 + .../document_service/transports/__init__.py | 38 + .../document_service/transports/base.py | 269 + .../document_service/transports/grpc.py | 509 ++ .../transports/grpc_asyncio.py | 508 ++ .../document_service/transports/rest.py | 1445 ++++ .../services/schema_service/__init__.py | 22 + .../services/schema_service/async_client.py | 902 +++ .../services/schema_service/client.py | 1119 +++ .../services/schema_service/pagers.py | 140 + .../schema_service/transports/__init__.py | 38 + .../schema_service/transports/base.py | 231 + .../schema_service/transports/grpc.py | 427 ++ .../schema_service/transports/grpc_asyncio.py | 426 ++ .../schema_service/transports/rest.py | 1208 ++++ .../services/search_service/__init__.py | 22 + .../services/search_service/async_client.py | 402 ++ .../services/search_service/client.py | 628 ++ .../services/search_service/pagers.py | 139 + .../search_service/transports/__init__.py | 38 + .../search_service/transports/base.py | 168 + .../search_service/transports/grpc.py | 302 + .../search_service/transports/grpc_asyncio.py | 301 + .../search_service/transports/rest.py | 584 ++ .../services/user_event_service/__init__.py | 22 + .../user_event_service/async_client.py | 644 ++ .../services/user_event_service/client.py | 857 +++ .../user_event_service/transports/__init__.py | 38 + .../user_event_service/transports/base.py | 211 + .../user_event_service/transports/grpc.py | 389 + .../transports/grpc_asyncio.py | 388 + .../user_event_service/transports/rest.py | 1021 +++ .../discoveryengine_v1/types/__init__.py | 162 + .../cloud/discoveryengine_v1/types/common.py | 167 + .../types/completion_service.py | 158 + .../discoveryengine_v1/types/conversation.py | 204 + .../types/conversational_search_service.py | 322 + .../discoveryengine_v1/types/document.py | 189 + .../types/document_service.py | 262 + .../discoveryengine_v1/types/import_config.py | 604 ++ .../discoveryengine_v1/types/purge_config.py | 133 + .../cloud/discoveryengine_v1/types/schema.py | 78 + .../types/schema_service.py | 289 + .../types/search_service.py | 1089 +++ .../discoveryengine_v1/types/user_event.py | 754 ++ .../types/user_event_service.py | 110 + .../google-cloud-discoveryengine/v1/mypy.ini | 3 + .../v1/noxfile.py | 184 + ...completion_service_complete_query_async.py | 53 + ..._completion_service_complete_query_sync.py | 53 + ...rch_service_converse_conversation_async.py | 52 + ...arch_service_converse_conversation_sync.py | 52 + ...earch_service_create_conversation_async.py | 52 + ...search_service_create_conversation_sync.py | 52 + ...earch_service_delete_conversation_async.py | 50 + ...search_service_delete_conversation_sync.py | 50 + ...l_search_service_get_conversation_async.py | 52 + ...al_search_service_get_conversation_sync.py | 52 + ...search_service_list_conversations_async.py | 53 + ..._search_service_list_conversations_sync.py | 53 + ...earch_service_update_conversation_async.py | 51 + ...search_service_update_conversation_sync.py | 51 + ..._document_service_create_document_async.py | 53 + ...d_document_service_create_document_sync.py | 53 + ..._document_service_delete_document_async.py | 50 + ...d_document_service_delete_document_sync.py | 50 + ...ted_document_service_get_document_async.py | 52 + ...ated_document_service_get_document_sync.py | 52 + ...document_service_import_documents_async.py | 56 + ..._document_service_import_documents_sync.py | 56 + ...d_document_service_list_documents_async.py | 53 + ...ed_document_service_list_documents_sync.py | 53 + ..._document_service_purge_documents_async.py | 57 + ...d_document_service_purge_documents_sync.py | 57 + ..._document_service_update_document_async.py | 51 + ...d_document_service_update_document_sync.py | 51 + ...ated_schema_service_create_schema_async.py | 57 + ...rated_schema_service_create_schema_sync.py | 57 + ...ated_schema_service_delete_schema_async.py | 56 + ...rated_schema_service_delete_schema_sync.py | 56 + ...nerated_schema_service_get_schema_async.py | 52 + ...enerated_schema_service_get_schema_sync.py | 52 + ...rated_schema_service_list_schemas_async.py | 53 + ...erated_schema_service_list_schemas_sync.py | 53 + ...ated_schema_service_update_schema_async.py | 55 + ...rated_schema_service_update_schema_sync.py | 55 + ...1_generated_search_service_search_async.py | 53 + ...v1_generated_search_service_search_sync.py | 53 + ..._event_service_collect_user_event_async.py | 53 + ...r_event_service_collect_user_event_sync.py | 53 + ..._event_service_import_user_events_async.py | 61 + ...r_event_service_import_user_events_sync.py | 61 + ...er_event_service_write_user_event_async.py | 52 + ...ser_event_service_write_user_event_sync.py | 52 + ...adata_google.cloud.discoveryengine.v1.json | 3690 ++++++++++ .../fixup_discoveryengine_v1_keywords.py | 198 + .../google-cloud-discoveryengine/v1/setup.py | 90 + .../v1/testing/constraints-3.10.txt | 6 + .../v1/testing/constraints-3.11.txt | 6 + .../v1/testing/constraints-3.12.txt | 6 + .../v1/testing/constraints-3.7.txt | 9 + .../v1/testing/constraints-3.8.txt | 6 + .../v1/testing/constraints-3.9.txt | 6 + .../v1/tests/__init__.py | 16 + .../v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../unit/gapic/discoveryengine_v1/__init__.py | 16 + .../test_completion_service.py | 1920 +++++ .../test_conversational_search_service.py | 4902 +++++++++++++ .../test_document_service.py | 4999 +++++++++++++ .../discoveryengine_v1/test_schema_service.py | 4265 +++++++++++ .../discoveryengine_v1/test_search_service.py | 2233 ++++++ .../test_user_event_service.py | 2786 ++++++++ .../v1alpha/.coveragerc | 13 + .../v1alpha/.flake8 | 33 + .../v1alpha/MANIFEST.in | 2 + .../v1alpha/README.rst | 49 + .../v1alpha/docs/_static/custom.css | 3 + .../v1alpha/docs/conf.py | 376 + .../completion_service.rst | 6 + .../conversational_search_service.rst | 10 + .../data_store_service.rst | 10 + .../document_service.rst | 10 + .../engine_service.rst | 10 + .../recommendation_service.rst | 6 + .../schema_service.rst | 10 + .../search_service.rst | 10 + .../discoveryengine_v1alpha/services_.rst | 15 + .../site_search_engine_service.rst | 6 + .../docs/discoveryengine_v1alpha/types_.rst | 6 + .../user_event_service.rst | 6 + .../v1alpha/docs/index.rst | 7 + .../google/cloud/discoveryengine/__init__.py | 255 + .../cloud/discoveryengine/gapic_version.py | 16 + .../google/cloud/discoveryengine/py.typed | 2 + .../cloud/discoveryengine_v1alpha/__init__.py | 256 + .../gapic_metadata.json | 784 ++ .../discoveryengine_v1alpha/gapic_version.py | 16 + .../cloud/discoveryengine_v1alpha/py.typed | 2 + .../services/__init__.py | 15 + .../services/completion_service/__init__.py | 22 + .../completion_service/async_client.py | 386 + .../services/completion_service/client.py | 594 ++ .../completion_service/transports/__init__.py | 38 + .../completion_service/transports/base.py | 168 + .../completion_service/transports/grpc.py | 303 + .../transports/grpc_asyncio.py | 302 + .../completion_service/transports/rest.py | 566 ++ .../conversational_search_service/__init__.py | 22 + .../async_client.py | 971 +++ .../conversational_search_service/client.py | 1205 ++++ .../conversational_search_service/pagers.py | 140 + .../transports/__init__.py | 38 + .../transports/base.py | 241 + .../transports/grpc.py | 449 ++ .../transports/grpc_asyncio.py | 448 ++ .../transports/rest.py | 1156 +++ .../services/data_store_service/__init__.py | 22 + .../data_store_service/async_client.py | 977 +++ .../services/data_store_service/client.py | 1193 ++++ .../services/data_store_service/pagers.py | 140 + .../data_store_service/transports/__init__.py | 38 + .../data_store_service/transports/base.py | 232 + .../data_store_service/transports/grpc.py | 440 ++ .../transports/grpc_asyncio.py | 439 ++ .../data_store_service/transports/rest.py | 1195 ++++ .../services/document_service/__init__.py | 22 + .../services/document_service/async_client.py | 1113 +++ .../services/document_service/client.py | 1326 ++++ .../services/document_service/pagers.py | 140 + .../document_service/transports/__init__.py | 38 + .../document_service/transports/base.py | 269 + .../document_service/transports/grpc.py | 513 ++ .../transports/grpc_asyncio.py | 512 ++ .../document_service/transports/rest.py | 1429 ++++ .../services/engine_service/__init__.py | 22 + .../services/engine_service/async_client.py | 1279 ++++ .../services/engine_service/client.py | 1495 ++++ .../services/engine_service/pagers.py | 140 + .../engine_service/transports/__init__.py | 38 + .../engine_service/transports/base.py | 274 + .../engine_service/transports/grpc.py | 513 ++ .../engine_service/transports/grpc_asyncio.py | 512 ++ .../engine_service/transports/rest.py | 1543 ++++ .../recommendation_service/__init__.py | 22 + .../recommendation_service/async_client.py | 389 + .../services/recommendation_service/client.py | 606 ++ .../transports/__init__.py | 38 + .../recommendation_service/transports/base.py | 168 + .../recommendation_service/transports/grpc.py | 303 + .../transports/grpc_asyncio.py | 302 + .../recommendation_service/transports/rest.py | 578 ++ .../services/schema_service/__init__.py | 22 + .../services/schema_service/async_client.py | 902 +++ .../services/schema_service/client.py | 1119 +++ .../services/schema_service/pagers.py | 140 + .../schema_service/transports/__init__.py | 38 + .../schema_service/transports/base.py | 231 + .../schema_service/transports/grpc.py | 427 ++ .../schema_service/transports/grpc_asyncio.py | 426 ++ .../schema_service/transports/rest.py | 1192 ++++ .../services/search_service/__init__.py | 22 + .../services/search_service/async_client.py | 402 ++ .../services/search_service/client.py | 628 ++ .../services/search_service/pagers.py | 139 + .../search_service/transports/__init__.py | 38 + .../search_service/transports/base.py | 168 + .../search_service/transports/grpc.py | 302 + .../search_service/transports/grpc_asyncio.py | 301 + .../search_service/transports/rest.py | 581 ++ .../site_search_engine_service/__init__.py | 22 + .../async_client.py | 401 ++ .../site_search_engine_service/client.py | 609 ++ .../transports/__init__.py | 38 + .../transports/base.py | 174 + .../transports/grpc.py | 320 + .../transports/grpc_asyncio.py | 319 + .../transports/rest.py | 709 ++ .../services/user_event_service/__init__.py | 22 + .../user_event_service/async_client.py | 746 ++ .../services/user_event_service/client.py | 960 +++ .../user_event_service/transports/__init__.py | 38 + .../user_event_service/transports/base.py | 226 + .../user_event_service/transports/grpc.py | 420 ++ .../transports/grpc_asyncio.py | 419 ++ .../user_event_service/transports/rest.py | 1132 +++ .../discoveryengine_v1alpha/types/__init__.py | 248 + .../discoveryengine_v1alpha/types/common.py | 257 + .../types/completion_service.py | 169 + .../types/conversation.py | 248 + .../types/conversational_search_service.py | 328 + .../types/data_store.py | 132 + .../types/data_store_service.py | 326 + .../discoveryengine_v1alpha/types/document.py | 189 + .../types/document_service.py | 266 + .../discoveryengine_v1alpha/types/engine.py | 570 ++ .../types/engine_service.py | 356 + .../types/import_config.py | 607 ++ .../types/purge_config.py | 247 + .../types/recommendation_service.py | 287 + .../discoveryengine_v1alpha/types/schema.py | 413 ++ .../types/schema_service.py | 291 + .../types/search_service.py | 1365 ++++ .../types/site_search_engine_service.py | 211 + .../types/user_event.py | 761 ++ .../types/user_event_service.py | 110 + .../v1alpha/mypy.ini | 3 + .../v1alpha/noxfile.py | 184 + ...completion_service_complete_query_async.py | 53 + ..._completion_service_complete_query_sync.py | 53 + ...rch_service_converse_conversation_async.py | 52 + ...arch_service_converse_conversation_sync.py | 52 + ...earch_service_create_conversation_async.py | 52 + ...search_service_create_conversation_sync.py | 52 + ...earch_service_delete_conversation_async.py | 50 + ...search_service_delete_conversation_sync.py | 50 + ...l_search_service_get_conversation_async.py | 52 + ...al_search_service_get_conversation_sync.py | 52 + ...search_service_list_conversations_async.py | 53 + ..._search_service_list_conversations_sync.py | 53 + ...earch_service_update_conversation_async.py | 51 + ...search_service_update_conversation_sync.py | 51 + ...a_store_service_create_data_store_async.py | 61 + ...ta_store_service_create_data_store_sync.py | 61 + ...a_store_service_delete_data_store_async.py | 56 + ...ta_store_service_delete_data_store_sync.py | 56 + ...data_store_service_get_data_store_async.py | 52 + ..._data_store_service_get_data_store_sync.py | 52 + ...ta_store_service_list_data_stores_async.py | 53 + ...ata_store_service_list_data_stores_sync.py | 53 + ...a_store_service_update_data_store_async.py | 55 + ...ta_store_service_update_data_store_sync.py | 55 + ..._document_service_create_document_async.py | 53 + ...d_document_service_create_document_sync.py | 53 + ..._document_service_delete_document_async.py | 50 + ...d_document_service_delete_document_sync.py | 50 + ...ted_document_service_get_document_async.py | 52 + ...ated_document_service_get_document_sync.py | 52 + ...document_service_import_documents_async.py | 56 + ..._document_service_import_documents_sync.py | 56 + ...d_document_service_list_documents_async.py | 53 + ...ed_document_service_list_documents_sync.py | 53 + ..._document_service_purge_documents_async.py | 57 + ...d_document_service_purge_documents_sync.py | 57 + ..._document_service_update_document_async.py | 51 + ...d_document_service_update_document_sync.py | 51 + ...ated_engine_service_create_engine_async.py | 62 + ...rated_engine_service_create_engine_sync.py | 62 + ...ated_engine_service_delete_engine_async.py | 56 + ...rated_engine_service_delete_engine_sync.py | 56 + ...nerated_engine_service_get_engine_async.py | 52 + ...enerated_engine_service_get_engine_sync.py | 52 + ...rated_engine_service_list_engines_async.py | 53 + ...erated_engine_service_list_engines_sync.py | 53 + ...rated_engine_service_pause_engine_async.py | 52 + ...erated_engine_service_pause_engine_sync.py | 52 + ...ated_engine_service_resume_engine_async.py | 52 + ...rated_engine_service_resume_engine_sync.py | 52 + ...erated_engine_service_tune_engine_async.py | 56 + ...nerated_engine_service_tune_engine_sync.py | 56 + ...ated_engine_service_update_engine_async.py | 56 + ...rated_engine_service_update_engine_sync.py | 56 + ..._recommendation_service_recommend_async.py | 57 + ...d_recommendation_service_recommend_sync.py | 57 + ...ated_schema_service_create_schema_async.py | 57 + ...rated_schema_service_create_schema_sync.py | 57 + ...ated_schema_service_delete_schema_async.py | 56 + ...rated_schema_service_delete_schema_sync.py | 56 + ...nerated_schema_service_get_schema_async.py | 52 + ...enerated_schema_service_get_schema_sync.py | 52 + ...rated_schema_service_list_schemas_async.py | 53 + ...erated_schema_service_list_schemas_sync.py | 53 + ...ated_schema_service_update_schema_async.py | 55 + ...rated_schema_service_update_schema_sync.py | 55 + ...a_generated_search_service_search_async.py | 53 + ...ha_generated_search_service_search_sync.py | 53 + ...earch_engine_service_recrawl_uris_async.py | 57 + ...search_engine_service_recrawl_uris_sync.py | 57 + ..._event_service_collect_user_event_async.py | 53 + ...r_event_service_collect_user_event_sync.py | 53 + ..._event_service_import_user_events_async.py | 61 + ...r_event_service_import_user_events_sync.py | 61 + ...r_event_service_purge_user_events_async.py | 57 + ...er_event_service_purge_user_events_sync.py | 57 + ...er_event_service_write_user_event_async.py | 52 + ...ser_event_service_write_user_event_sync.py | 52 + ..._google.cloud.discoveryengine.v1alpha.json | 6290 +++++++++++++++++ .../fixup_discoveryengine_v1alpha_keywords.py | 214 + .../v1alpha/setup.py | 90 + .../v1alpha/testing/constraints-3.10.txt | 6 + .../v1alpha/testing/constraints-3.11.txt | 6 + .../v1alpha/testing/constraints-3.12.txt | 6 + .../v1alpha/testing/constraints-3.7.txt | 9 + .../v1alpha/testing/constraints-3.8.txt | 6 + .../v1alpha/testing/constraints-3.9.txt | 6 + .../v1alpha/tests/__init__.py | 16 + .../v1alpha/tests/unit/__init__.py | 16 + .../v1alpha/tests/unit/gapic/__init__.py | 16 + .../gapic/discoveryengine_v1alpha/__init__.py | 16 + .../test_completion_service.py | 1920 +++++ .../test_conversational_search_service.py | 4908 +++++++++++++ .../test_data_store_service.py | 4481 ++++++++++++ .../test_document_service.py | 4999 +++++++++++++ .../test_engine_service.py | 5927 ++++++++++++++++ .../test_recommendation_service.py | 1952 +++++ .../test_schema_service.py | 4265 +++++++++++ .../test_search_service.py | 2239 ++++++ .../test_site_search_engine_service.py | 1961 +++++ .../test_user_event_service.py | 3118 ++++++++ .../v1beta/.coveragerc | 13 + .../v1beta/.flake8 | 33 + .../v1beta/MANIFEST.in | 2 + .../v1beta/README.rst | 49 + .../v1beta/docs/_static/custom.css | 3 + .../v1beta/docs/conf.py | 376 + .../completion_service.rst | 6 + .../conversational_search_service.rst | 10 + .../document_service.rst | 10 + .../recommendation_service.rst | 6 + .../discoveryengine_v1beta/schema_service.rst | 10 + .../discoveryengine_v1beta/search_service.rst | 10 + .../docs/discoveryengine_v1beta/services_.rst | 12 + .../docs/discoveryengine_v1beta/types_.rst | 6 + .../user_event_service.rst | 6 + .../v1beta/docs/index.rst | 7 + .../google/cloud/discoveryengine/__init__.py | 175 + .../cloud/discoveryengine/gapic_version.py | 16 + .../google/cloud/discoveryengine/py.typed | 2 + .../cloud/discoveryengine_v1beta/__init__.py | 176 + .../gapic_metadata.json | 502 ++ .../discoveryengine_v1beta/gapic_version.py | 16 + .../cloud/discoveryengine_v1beta/py.typed | 2 + .../services/__init__.py | 15 + .../services/completion_service/__init__.py | 22 + .../completion_service/async_client.py | 386 + .../services/completion_service/client.py | 594 ++ .../completion_service/transports/__init__.py | 38 + .../completion_service/transports/base.py | 168 + .../completion_service/transports/grpc.py | 303 + .../transports/grpc_asyncio.py | 302 + .../completion_service/transports/rest.py | 566 ++ .../conversational_search_service/__init__.py | 22 + .../async_client.py | 971 +++ .../conversational_search_service/client.py | 1205 ++++ .../conversational_search_service/pagers.py | 140 + .../transports/__init__.py | 38 + .../transports/base.py | 241 + .../transports/grpc.py | 449 ++ .../transports/grpc_asyncio.py | 448 ++ .../transports/rest.py | 1156 +++ .../services/document_service/__init__.py | 22 + .../services/document_service/async_client.py | 1112 +++ .../services/document_service/client.py | 1325 ++++ .../services/document_service/pagers.py | 140 + .../document_service/transports/__init__.py | 38 + .../document_service/transports/base.py | 269 + .../document_service/transports/grpc.py | 512 ++ .../transports/grpc_asyncio.py | 511 ++ .../document_service/transports/rest.py | 1429 ++++ .../recommendation_service/__init__.py | 22 + .../recommendation_service/async_client.py | 389 + .../services/recommendation_service/client.py | 606 ++ .../transports/__init__.py | 38 + .../recommendation_service/transports/base.py | 168 + .../recommendation_service/transports/grpc.py | 303 + .../transports/grpc_asyncio.py | 302 + .../recommendation_service/transports/rest.py | 573 ++ .../services/schema_service/__init__.py | 22 + .../services/schema_service/async_client.py | 902 +++ .../services/schema_service/client.py | 1119 +++ .../services/schema_service/pagers.py | 140 + .../schema_service/transports/__init__.py | 38 + .../schema_service/transports/base.py | 231 + .../schema_service/transports/grpc.py | 427 ++ .../schema_service/transports/grpc_asyncio.py | 426 ++ .../schema_service/transports/rest.py | 1192 ++++ .../services/search_service/__init__.py | 22 + .../services/search_service/async_client.py | 402 ++ .../services/search_service/client.py | 628 ++ .../services/search_service/pagers.py | 139 + .../search_service/transports/__init__.py | 38 + .../search_service/transports/base.py | 168 + .../search_service/transports/grpc.py | 302 + .../search_service/transports/grpc_asyncio.py | 301 + .../search_service/transports/rest.py | 576 ++ .../services/user_event_service/__init__.py | 22 + .../user_event_service/async_client.py | 644 ++ .../services/user_event_service/client.py | 857 +++ .../user_event_service/transports/__init__.py | 38 + .../user_event_service/transports/base.py | 211 + .../user_event_service/transports/grpc.py | 389 + .../transports/grpc_asyncio.py | 388 + .../user_event_service/transports/rest.py | 1005 +++ .../discoveryengine_v1beta/types/__init__.py | 170 + .../discoveryengine_v1beta/types/common.py | 182 + .../types/completion_service.py | 158 + .../types/conversation.py | 248 + .../types/conversational_search_service.py | 328 + .../discoveryengine_v1beta/types/document.py | 189 + .../types/document_service.py | 265 + .../types/import_config.py | 607 ++ .../types/purge_config.py | 133 + .../types/recommendation_service.py | 264 + .../discoveryengine_v1beta/types/schema.py | 78 + .../types/schema_service.py | 291 + .../types/search_service.py | 1312 ++++ .../types/user_event.py | 758 ++ .../types/user_event_service.py | 110 + .../v1beta/mypy.ini | 3 + .../v1beta/noxfile.py | 184 + ...completion_service_complete_query_async.py | 53 + ..._completion_service_complete_query_sync.py | 53 + ...rch_service_converse_conversation_async.py | 52 + ...arch_service_converse_conversation_sync.py | 52 + ...earch_service_create_conversation_async.py | 52 + ...search_service_create_conversation_sync.py | 52 + ...earch_service_delete_conversation_async.py | 50 + ...search_service_delete_conversation_sync.py | 50 + ...l_search_service_get_conversation_async.py | 52 + ...al_search_service_get_conversation_sync.py | 52 + ...search_service_list_conversations_async.py | 53 + ..._search_service_list_conversations_sync.py | 53 + ...earch_service_update_conversation_async.py | 51 + ...search_service_update_conversation_sync.py | 51 + ..._document_service_create_document_async.py | 53 + ...d_document_service_create_document_sync.py | 53 + ..._document_service_delete_document_async.py | 50 + ...d_document_service_delete_document_sync.py | 50 + ...ted_document_service_get_document_async.py | 52 + ...ated_document_service_get_document_sync.py | 52 + ...document_service_import_documents_async.py | 56 + ..._document_service_import_documents_sync.py | 56 + ...d_document_service_list_documents_async.py | 53 + ...ed_document_service_list_documents_sync.py | 53 + ..._document_service_purge_documents_async.py | 57 + ...d_document_service_purge_documents_sync.py | 57 + ..._document_service_update_document_async.py | 51 + ...d_document_service_update_document_sync.py | 51 + ..._recommendation_service_recommend_async.py | 57 + ...d_recommendation_service_recommend_sync.py | 57 + ...ated_schema_service_create_schema_async.py | 57 + ...rated_schema_service_create_schema_sync.py | 57 + ...ated_schema_service_delete_schema_async.py | 56 + ...rated_schema_service_delete_schema_sync.py | 56 + ...nerated_schema_service_get_schema_async.py | 52 + ...enerated_schema_service_get_schema_sync.py | 52 + ...rated_schema_service_list_schemas_async.py | 53 + ...erated_schema_service_list_schemas_sync.py | 53 + ...ated_schema_service_update_schema_async.py | 55 + ...rated_schema_service_update_schema_sync.py | 55 + ...a_generated_search_service_search_async.py | 53 + ...ta_generated_search_service_search_sync.py | 53 + ..._event_service_collect_user_event_async.py | 53 + ...r_event_service_collect_user_event_sync.py | 53 + ..._event_service_import_user_events_async.py | 61 + ...r_event_service_import_user_events_sync.py | 61 + ...er_event_service_write_user_event_async.py | 52 + ...ser_event_service_write_user_event_sync.py | 52 + ...a_google.cloud.discoveryengine.v1beta.json | 3843 ++++++++++ .../fixup_discoveryengine_v1beta_keywords.py | 199 + .../v1beta/setup.py | 90 + .../v1beta/testing/constraints-3.10.txt | 6 + .../v1beta/testing/constraints-3.11.txt | 6 + .../v1beta/testing/constraints-3.12.txt | 6 + .../v1beta/testing/constraints-3.7.txt | 9 + .../v1beta/testing/constraints-3.8.txt | 6 + .../v1beta/testing/constraints-3.9.txt | 6 + .../v1beta/tests/__init__.py | 16 + .../v1beta/tests/unit/__init__.py | 16 + .../v1beta/tests/unit/gapic/__init__.py | 16 + .../gapic/discoveryengine_v1beta/__init__.py | 16 + .../test_completion_service.py | 1920 +++++ .../test_conversational_search_service.py | 4908 +++++++++++++ .../test_document_service.py | 4999 +++++++++++++ .../test_recommendation_service.py | 1952 +++++ .../test_schema_service.py | 4265 +++++++++++ .../test_search_service.py | 2239 ++++++ .../test_user_event_service.py | 2786 ++++++++ 561 files changed, 214033 insertions(+) create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/.coveragerc create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/.flake8 create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/MANIFEST.in create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/README.rst create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/docs/_static/custom.css create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/docs/conf.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/completion_service.rst create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/conversational_search_service.rst create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/document_service.rst create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/schema_service.rst create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/search_service.rst create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/services_.rst create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/types_.rst create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/user_event_service.rst create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/docs/index.rst create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine/py.typed create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/gapic_metadata.json create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/py.typed create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/async_client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/base.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/async_client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/pagers.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/base.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/async_client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/pagers.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/base.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/async_client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/pagers.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/base.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/async_client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/pagers.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/base.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/async_client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/base.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/common.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/completion_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/conversation.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/conversational_search_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/document.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/document_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/import_config.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/purge_config.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/schema.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/schema_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/search_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/user_event.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/user_event_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/mypy.ini create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/noxfile.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_completion_service_complete_query_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_completion_service_complete_query_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_converse_conversation_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_converse_conversation_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_create_conversation_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_create_conversation_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_delete_conversation_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_delete_conversation_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_get_conversation_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_get_conversation_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_list_conversations_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_list_conversations_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_update_conversation_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_update_conversation_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_create_document_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_create_document_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_delete_document_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_delete_document_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_get_document_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_get_document_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_import_documents_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_import_documents_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_list_documents_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_list_documents_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_purge_documents_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_purge_documents_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_update_document_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_update_document_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_create_schema_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_create_schema_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_delete_schema_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_delete_schema_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_get_schema_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_get_schema_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_list_schemas_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_list_schemas_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_update_schema_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_update_schema_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_search_service_search_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_search_service_search_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_collect_user_event_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_collect_user_event_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_import_user_events_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_import_user_events_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_write_user_event_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_write_user_event_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1.json create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/scripts/fixup_discoveryengine_v1_keywords.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/setup.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/tests/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_completion_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_conversational_search_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_document_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_schema_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_search_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_user_event_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/.coveragerc create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/.flake8 create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/MANIFEST.in create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/README.rst create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/_static/custom.css create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/conf.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/completion_service.rst create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/conversational_search_service.rst create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/data_store_service.rst create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/document_service.rst create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/engine_service.rst create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/recommendation_service.rst create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/schema_service.rst create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/search_service.rst create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/services_.rst create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/site_search_engine_service.rst create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/types_.rst create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/user_event_service.rst create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/index.rst create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine/py.typed create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/gapic_metadata.json create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/py.typed create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/async_client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/base.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/async_client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/pagers.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/base.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/async_client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/pagers.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/base.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/async_client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/pagers.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/base.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/async_client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/pagers.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/base.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/async_client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/base.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/async_client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/pagers.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/base.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/async_client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/pagers.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/base.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/async_client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/base.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/async_client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/base.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/common.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/completion_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/conversation.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/conversational_search_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/data_store.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/data_store_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/document.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/document_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/engine.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/engine_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/import_config.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/purge_config.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/recommendation_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/schema.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/schema_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/search_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/site_search_engine_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/user_event.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/user_event_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/mypy.ini create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/noxfile.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_completion_service_complete_query_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_completion_service_complete_query_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_converse_conversation_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_converse_conversation_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_create_conversation_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_create_conversation_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_delete_conversation_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_delete_conversation_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_get_conversation_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_get_conversation_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_list_conversations_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_list_conversations_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_update_conversation_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_update_conversation_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_create_data_store_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_create_data_store_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_delete_data_store_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_delete_data_store_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_get_data_store_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_get_data_store_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_list_data_stores_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_list_data_stores_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_update_data_store_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_update_data_store_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_create_document_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_create_document_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_delete_document_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_delete_document_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_get_document_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_get_document_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_import_documents_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_import_documents_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_list_documents_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_list_documents_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_purge_documents_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_purge_documents_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_update_document_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_update_document_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_create_engine_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_create_engine_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_delete_engine_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_delete_engine_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_get_engine_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_get_engine_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_list_engines_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_list_engines_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_pause_engine_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_pause_engine_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_resume_engine_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_resume_engine_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_tune_engine_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_tune_engine_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_update_engine_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_update_engine_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_recommendation_service_recommend_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_recommendation_service_recommend_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_create_schema_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_create_schema_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_delete_schema_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_delete_schema_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_get_schema_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_get_schema_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_list_schemas_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_list_schemas_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_update_schema_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_update_schema_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_search_service_search_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_search_service_search_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_site_search_engine_service_recrawl_uris_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_site_search_engine_service_recrawl_uris_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_collect_user_event_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_collect_user_event_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_import_user_events_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_import_user_events_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_purge_user_events_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_purge_user_events_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_write_user_event_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_write_user_event_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1alpha.json create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/scripts/fixup_discoveryengine_v1alpha_keywords.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/setup.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_completion_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_conversational_search_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_data_store_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_document_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_engine_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_recommendation_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_schema_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_search_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_site_search_engine_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_user_event_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/.coveragerc create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/.flake8 create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/MANIFEST.in create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/README.rst create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/_static/custom.css create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/conf.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/completion_service.rst create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/conversational_search_service.rst create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/document_service.rst create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/recommendation_service.rst create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/schema_service.rst create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/search_service.rst create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/services_.rst create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/types_.rst create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/user_event_service.rst create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/index.rst create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine/py.typed create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/gapic_metadata.json create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/py.typed create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/async_client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/base.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/async_client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/pagers.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/base.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/async_client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/pagers.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/base.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/async_client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/base.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/async_client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/pagers.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/base.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/async_client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/pagers.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/base.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/async_client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/client.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/base.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/common.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/completion_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/conversation.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/conversational_search_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/document.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/document_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/import_config.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/purge_config.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/recommendation_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/schema.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/schema_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/search_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/user_event.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/user_event_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/mypy.ini create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/noxfile.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_completion_service_complete_query_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_completion_service_complete_query_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_converse_conversation_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_converse_conversation_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_create_conversation_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_create_conversation_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_delete_conversation_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_delete_conversation_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_get_conversation_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_get_conversation_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_list_conversations_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_list_conversations_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_update_conversation_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_update_conversation_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_create_document_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_create_document_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_delete_document_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_delete_document_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_get_document_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_get_document_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_import_documents_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_import_documents_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_list_documents_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_list_documents_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_purge_documents_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_purge_documents_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_update_document_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_update_document_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_recommendation_service_recommend_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_recommendation_service_recommend_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_create_schema_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_create_schema_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_delete_schema_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_delete_schema_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_get_schema_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_get_schema_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_list_schemas_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_list_schemas_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_update_schema_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_update_schema_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_search_service_search_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_search_service_search_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_collect_user_event_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_collect_user_event_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_import_user_events_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_import_user_events_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_write_user_event_async.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_write_user_event_sync.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1beta.json create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/scripts/fixup_discoveryengine_v1beta_keywords.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/setup.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/__init__.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_completion_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_conversational_search_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_document_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_recommendation_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_schema_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_search_service.py create mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_user_event_service.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/.coveragerc b/owl-bot-staging/google-cloud-discoveryengine/v1/.coveragerc new file mode 100644 index 000000000000..f2c9bc595be9 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/discoveryengine/__init__.py + google/cloud/discoveryengine/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/.flake8 b/owl-bot-staging/google-cloud-discoveryengine/v1/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/MANIFEST.in b/owl-bot-staging/google-cloud-discoveryengine/v1/MANIFEST.in new file mode 100644 index 000000000000..9d84ac93f6c8 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/discoveryengine *.py +recursive-include google/cloud/discoveryengine_v1 *.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/README.rst b/owl-bot-staging/google-cloud-discoveryengine/v1/README.rst new file mode 100644 index 000000000000..25f579284266 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Discoveryengine API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Cloud Discoveryengine API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/docs/_static/custom.css b/owl-bot-staging/google-cloud-discoveryengine/v1/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/docs/conf.py b/owl-bot-staging/google-cloud-discoveryengine/v1/docs/conf.py new file mode 100644 index 000000000000..9852ef988546 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-discoveryengine documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-cloud-discoveryengine" +copyright = u"2023, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = 'en' + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-discoveryengine-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-cloud-discoveryengine.tex", + u"google-cloud-discoveryengine Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + root_doc, + "google-cloud-discoveryengine", + u"Google Cloud Discoveryengine Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-cloud-discoveryengine", + u"google-cloud-discoveryengine Documentation", + author, + "google-cloud-discoveryengine", + "GAPIC library for Google Cloud Discoveryengine API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/completion_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/completion_service.rst new file mode 100644 index 000000000000..f18a0cfa68f6 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/completion_service.rst @@ -0,0 +1,6 @@ +CompletionService +----------------------------------- + +.. automodule:: google.cloud.discoveryengine_v1.services.completion_service + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/conversational_search_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/conversational_search_service.rst new file mode 100644 index 000000000000..1b538eb65974 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/conversational_search_service.rst @@ -0,0 +1,10 @@ +ConversationalSearchService +--------------------------------------------- + +.. automodule:: google.cloud.discoveryengine_v1.services.conversational_search_service + :members: + :inherited-members: + +.. automodule:: google.cloud.discoveryengine_v1.services.conversational_search_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/document_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/document_service.rst new file mode 100644 index 000000000000..a0513d278416 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/document_service.rst @@ -0,0 +1,10 @@ +DocumentService +--------------------------------- + +.. automodule:: google.cloud.discoveryengine_v1.services.document_service + :members: + :inherited-members: + +.. automodule:: google.cloud.discoveryengine_v1.services.document_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/schema_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/schema_service.rst new file mode 100644 index 000000000000..725b280ca3bf --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/schema_service.rst @@ -0,0 +1,10 @@ +SchemaService +------------------------------- + +.. automodule:: google.cloud.discoveryengine_v1.services.schema_service + :members: + :inherited-members: + +.. automodule:: google.cloud.discoveryengine_v1.services.schema_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/search_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/search_service.rst new file mode 100644 index 000000000000..54969826c038 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/search_service.rst @@ -0,0 +1,10 @@ +SearchService +------------------------------- + +.. automodule:: google.cloud.discoveryengine_v1.services.search_service + :members: + :inherited-members: + +.. automodule:: google.cloud.discoveryengine_v1.services.search_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/services_.rst b/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/services_.rst new file mode 100644 index 000000000000..f93a1c0cd465 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/services_.rst @@ -0,0 +1,11 @@ +Services for Google Cloud Discoveryengine v1 API +================================================ +.. toctree:: + :maxdepth: 2 + + completion_service + conversational_search_service + document_service + schema_service + search_service + user_event_service diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/types_.rst b/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/types_.rst new file mode 100644 index 000000000000..07127eae56ef --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Discoveryengine v1 API +============================================= + +.. automodule:: google.cloud.discoveryengine_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/user_event_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/user_event_service.rst new file mode 100644 index 000000000000..74a5dca6bc44 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/user_event_service.rst @@ -0,0 +1,6 @@ +UserEventService +---------------------------------- + +.. automodule:: google.cloud.discoveryengine_v1.services.user_event_service + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/docs/index.rst b/owl-bot-staging/google-cloud-discoveryengine/v1/docs/index.rst new file mode 100644 index 000000000000..b3ce373dfe99 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + discoveryengine_v1/services + discoveryengine_v1/types diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine/__init__.py new file mode 100644 index 000000000000..1910fb7ef9bb --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine/__init__.py @@ -0,0 +1,165 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.discoveryengine import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.discoveryengine_v1.services.completion_service.client import CompletionServiceClient +from google.cloud.discoveryengine_v1.services.completion_service.async_client import CompletionServiceAsyncClient +from google.cloud.discoveryengine_v1.services.conversational_search_service.client import ConversationalSearchServiceClient +from google.cloud.discoveryengine_v1.services.conversational_search_service.async_client import ConversationalSearchServiceAsyncClient +from google.cloud.discoveryengine_v1.services.document_service.client import DocumentServiceClient +from google.cloud.discoveryengine_v1.services.document_service.async_client import DocumentServiceAsyncClient +from google.cloud.discoveryengine_v1.services.schema_service.client import SchemaServiceClient +from google.cloud.discoveryengine_v1.services.schema_service.async_client import SchemaServiceAsyncClient +from google.cloud.discoveryengine_v1.services.search_service.client import SearchServiceClient +from google.cloud.discoveryengine_v1.services.search_service.async_client import SearchServiceAsyncClient +from google.cloud.discoveryengine_v1.services.user_event_service.client import UserEventServiceClient +from google.cloud.discoveryengine_v1.services.user_event_service.async_client import UserEventServiceAsyncClient + +from google.cloud.discoveryengine_v1.types.common import CustomAttribute +from google.cloud.discoveryengine_v1.types.common import Interval +from google.cloud.discoveryengine_v1.types.common import UserInfo +from google.cloud.discoveryengine_v1.types.completion_service import CompleteQueryRequest +from google.cloud.discoveryengine_v1.types.completion_service import CompleteQueryResponse +from google.cloud.discoveryengine_v1.types.conversation import Conversation +from google.cloud.discoveryengine_v1.types.conversation import ConversationContext +from google.cloud.discoveryengine_v1.types.conversation import ConversationMessage +from google.cloud.discoveryengine_v1.types.conversation import Reply +from google.cloud.discoveryengine_v1.types.conversation import TextInput +from google.cloud.discoveryengine_v1.types.conversational_search_service import ConverseConversationRequest +from google.cloud.discoveryengine_v1.types.conversational_search_service import ConverseConversationResponse +from google.cloud.discoveryengine_v1.types.conversational_search_service import CreateConversationRequest +from google.cloud.discoveryengine_v1.types.conversational_search_service import DeleteConversationRequest +from google.cloud.discoveryengine_v1.types.conversational_search_service import GetConversationRequest +from google.cloud.discoveryengine_v1.types.conversational_search_service import ListConversationsRequest +from google.cloud.discoveryengine_v1.types.conversational_search_service import ListConversationsResponse +from google.cloud.discoveryengine_v1.types.conversational_search_service import UpdateConversationRequest +from google.cloud.discoveryengine_v1.types.document import Document +from google.cloud.discoveryengine_v1.types.document_service import CreateDocumentRequest +from google.cloud.discoveryengine_v1.types.document_service import DeleteDocumentRequest +from google.cloud.discoveryengine_v1.types.document_service import GetDocumentRequest +from google.cloud.discoveryengine_v1.types.document_service import ListDocumentsRequest +from google.cloud.discoveryengine_v1.types.document_service import ListDocumentsResponse +from google.cloud.discoveryengine_v1.types.document_service import UpdateDocumentRequest +from google.cloud.discoveryengine_v1.types.import_config import BigQuerySource +from google.cloud.discoveryengine_v1.types.import_config import GcsSource +from google.cloud.discoveryengine_v1.types.import_config import ImportDocumentsMetadata +from google.cloud.discoveryengine_v1.types.import_config import ImportDocumentsRequest +from google.cloud.discoveryengine_v1.types.import_config import ImportDocumentsResponse +from google.cloud.discoveryengine_v1.types.import_config import ImportErrorConfig +from google.cloud.discoveryengine_v1.types.import_config import ImportUserEventsMetadata +from google.cloud.discoveryengine_v1.types.import_config import ImportUserEventsRequest +from google.cloud.discoveryengine_v1.types.import_config import ImportUserEventsResponse +from google.cloud.discoveryengine_v1.types.purge_config import PurgeDocumentsMetadata +from google.cloud.discoveryengine_v1.types.purge_config import PurgeDocumentsRequest +from google.cloud.discoveryengine_v1.types.purge_config import PurgeDocumentsResponse +from google.cloud.discoveryengine_v1.types.schema import Schema +from google.cloud.discoveryengine_v1.types.schema_service import CreateSchemaMetadata +from google.cloud.discoveryengine_v1.types.schema_service import CreateSchemaRequest +from google.cloud.discoveryengine_v1.types.schema_service import DeleteSchemaMetadata +from google.cloud.discoveryengine_v1.types.schema_service import DeleteSchemaRequest +from google.cloud.discoveryengine_v1.types.schema_service import GetSchemaRequest +from google.cloud.discoveryengine_v1.types.schema_service import ListSchemasRequest +from google.cloud.discoveryengine_v1.types.schema_service import ListSchemasResponse +from google.cloud.discoveryengine_v1.types.schema_service import UpdateSchemaMetadata +from google.cloud.discoveryengine_v1.types.schema_service import UpdateSchemaRequest +from google.cloud.discoveryengine_v1.types.search_service import SearchRequest +from google.cloud.discoveryengine_v1.types.search_service import SearchResponse +from google.cloud.discoveryengine_v1.types.user_event import CompletionInfo +from google.cloud.discoveryengine_v1.types.user_event import DocumentInfo +from google.cloud.discoveryengine_v1.types.user_event import MediaInfo +from google.cloud.discoveryengine_v1.types.user_event import PageInfo +from google.cloud.discoveryengine_v1.types.user_event import PanelInfo +from google.cloud.discoveryengine_v1.types.user_event import SearchInfo +from google.cloud.discoveryengine_v1.types.user_event import TransactionInfo +from google.cloud.discoveryengine_v1.types.user_event import UserEvent +from google.cloud.discoveryengine_v1.types.user_event_service import CollectUserEventRequest +from google.cloud.discoveryengine_v1.types.user_event_service import WriteUserEventRequest + +__all__ = ('CompletionServiceClient', + 'CompletionServiceAsyncClient', + 'ConversationalSearchServiceClient', + 'ConversationalSearchServiceAsyncClient', + 'DocumentServiceClient', + 'DocumentServiceAsyncClient', + 'SchemaServiceClient', + 'SchemaServiceAsyncClient', + 'SearchServiceClient', + 'SearchServiceAsyncClient', + 'UserEventServiceClient', + 'UserEventServiceAsyncClient', + 'CustomAttribute', + 'Interval', + 'UserInfo', + 'CompleteQueryRequest', + 'CompleteQueryResponse', + 'Conversation', + 'ConversationContext', + 'ConversationMessage', + 'Reply', + 'TextInput', + 'ConverseConversationRequest', + 'ConverseConversationResponse', + 'CreateConversationRequest', + 'DeleteConversationRequest', + 'GetConversationRequest', + 'ListConversationsRequest', + 'ListConversationsResponse', + 'UpdateConversationRequest', + 'Document', + 'CreateDocumentRequest', + 'DeleteDocumentRequest', + 'GetDocumentRequest', + 'ListDocumentsRequest', + 'ListDocumentsResponse', + 'UpdateDocumentRequest', + 'BigQuerySource', + 'GcsSource', + 'ImportDocumentsMetadata', + 'ImportDocumentsRequest', + 'ImportDocumentsResponse', + 'ImportErrorConfig', + 'ImportUserEventsMetadata', + 'ImportUserEventsRequest', + 'ImportUserEventsResponse', + 'PurgeDocumentsMetadata', + 'PurgeDocumentsRequest', + 'PurgeDocumentsResponse', + 'Schema', + 'CreateSchemaMetadata', + 'CreateSchemaRequest', + 'DeleteSchemaMetadata', + 'DeleteSchemaRequest', + 'GetSchemaRequest', + 'ListSchemasRequest', + 'ListSchemasResponse', + 'UpdateSchemaMetadata', + 'UpdateSchemaRequest', + 'SearchRequest', + 'SearchResponse', + 'CompletionInfo', + 'DocumentInfo', + 'MediaInfo', + 'PageInfo', + 'PanelInfo', + 'SearchInfo', + 'TransactionInfo', + 'UserEvent', + 'CollectUserEventRequest', + 'WriteUserEventRequest', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine/gapic_version.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine/gapic_version.py new file mode 100644 index 000000000000..360a0d13ebdd --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine/py.typed b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine/py.typed new file mode 100644 index 000000000000..2ff6437cf473 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-discoveryengine package uses inline types. diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/__init__.py new file mode 100644 index 000000000000..c55b70e7ad19 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/__init__.py @@ -0,0 +1,166 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.discoveryengine_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.completion_service import CompletionServiceClient +from .services.completion_service import CompletionServiceAsyncClient +from .services.conversational_search_service import ConversationalSearchServiceClient +from .services.conversational_search_service import ConversationalSearchServiceAsyncClient +from .services.document_service import DocumentServiceClient +from .services.document_service import DocumentServiceAsyncClient +from .services.schema_service import SchemaServiceClient +from .services.schema_service import SchemaServiceAsyncClient +from .services.search_service import SearchServiceClient +from .services.search_service import SearchServiceAsyncClient +from .services.user_event_service import UserEventServiceClient +from .services.user_event_service import UserEventServiceAsyncClient + +from .types.common import CustomAttribute +from .types.common import Interval +from .types.common import UserInfo +from .types.completion_service import CompleteQueryRequest +from .types.completion_service import CompleteQueryResponse +from .types.conversation import Conversation +from .types.conversation import ConversationContext +from .types.conversation import ConversationMessage +from .types.conversation import Reply +from .types.conversation import TextInput +from .types.conversational_search_service import ConverseConversationRequest +from .types.conversational_search_service import ConverseConversationResponse +from .types.conversational_search_service import CreateConversationRequest +from .types.conversational_search_service import DeleteConversationRequest +from .types.conversational_search_service import GetConversationRequest +from .types.conversational_search_service import ListConversationsRequest +from .types.conversational_search_service import ListConversationsResponse +from .types.conversational_search_service import UpdateConversationRequest +from .types.document import Document +from .types.document_service import CreateDocumentRequest +from .types.document_service import DeleteDocumentRequest +from .types.document_service import GetDocumentRequest +from .types.document_service import ListDocumentsRequest +from .types.document_service import ListDocumentsResponse +from .types.document_service import UpdateDocumentRequest +from .types.import_config import BigQuerySource +from .types.import_config import GcsSource +from .types.import_config import ImportDocumentsMetadata +from .types.import_config import ImportDocumentsRequest +from .types.import_config import ImportDocumentsResponse +from .types.import_config import ImportErrorConfig +from .types.import_config import ImportUserEventsMetadata +from .types.import_config import ImportUserEventsRequest +from .types.import_config import ImportUserEventsResponse +from .types.purge_config import PurgeDocumentsMetadata +from .types.purge_config import PurgeDocumentsRequest +from .types.purge_config import PurgeDocumentsResponse +from .types.schema import Schema +from .types.schema_service import CreateSchemaMetadata +from .types.schema_service import CreateSchemaRequest +from .types.schema_service import DeleteSchemaMetadata +from .types.schema_service import DeleteSchemaRequest +from .types.schema_service import GetSchemaRequest +from .types.schema_service import ListSchemasRequest +from .types.schema_service import ListSchemasResponse +from .types.schema_service import UpdateSchemaMetadata +from .types.schema_service import UpdateSchemaRequest +from .types.search_service import SearchRequest +from .types.search_service import SearchResponse +from .types.user_event import CompletionInfo +from .types.user_event import DocumentInfo +from .types.user_event import MediaInfo +from .types.user_event import PageInfo +from .types.user_event import PanelInfo +from .types.user_event import SearchInfo +from .types.user_event import TransactionInfo +from .types.user_event import UserEvent +from .types.user_event_service import CollectUserEventRequest +from .types.user_event_service import WriteUserEventRequest + +__all__ = ( + 'CompletionServiceAsyncClient', + 'ConversationalSearchServiceAsyncClient', + 'DocumentServiceAsyncClient', + 'SchemaServiceAsyncClient', + 'SearchServiceAsyncClient', + 'UserEventServiceAsyncClient', +'BigQuerySource', +'CollectUserEventRequest', +'CompleteQueryRequest', +'CompleteQueryResponse', +'CompletionInfo', +'CompletionServiceClient', +'Conversation', +'ConversationContext', +'ConversationMessage', +'ConversationalSearchServiceClient', +'ConverseConversationRequest', +'ConverseConversationResponse', +'CreateConversationRequest', +'CreateDocumentRequest', +'CreateSchemaMetadata', +'CreateSchemaRequest', +'CustomAttribute', +'DeleteConversationRequest', +'DeleteDocumentRequest', +'DeleteSchemaMetadata', +'DeleteSchemaRequest', +'Document', +'DocumentInfo', +'DocumentServiceClient', +'GcsSource', +'GetConversationRequest', +'GetDocumentRequest', +'GetSchemaRequest', +'ImportDocumentsMetadata', +'ImportDocumentsRequest', +'ImportDocumentsResponse', +'ImportErrorConfig', +'ImportUserEventsMetadata', +'ImportUserEventsRequest', +'ImportUserEventsResponse', +'Interval', +'ListConversationsRequest', +'ListConversationsResponse', +'ListDocumentsRequest', +'ListDocumentsResponse', +'ListSchemasRequest', +'ListSchemasResponse', +'MediaInfo', +'PageInfo', +'PanelInfo', +'PurgeDocumentsMetadata', +'PurgeDocumentsRequest', +'PurgeDocumentsResponse', +'Reply', +'Schema', +'SchemaServiceClient', +'SearchInfo', +'SearchRequest', +'SearchResponse', +'SearchServiceClient', +'TextInput', +'TransactionInfo', +'UpdateConversationRequest', +'UpdateDocumentRequest', +'UpdateSchemaMetadata', +'UpdateSchemaRequest', +'UserEvent', +'UserEventServiceClient', +'UserInfo', +'WriteUserEventRequest', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/gapic_metadata.json new file mode 100644 index 000000000000..40ef7a0de6c2 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/gapic_metadata.json @@ -0,0 +1,468 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.discoveryengine_v1", + "protoPackage": "google.cloud.discoveryengine.v1", + "schema": "1.0", + "services": { + "CompletionService": { + "clients": { + "grpc": { + "libraryClient": "CompletionServiceClient", + "rpcs": { + "CompleteQuery": { + "methods": [ + "complete_query" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CompletionServiceAsyncClient", + "rpcs": { + "CompleteQuery": { + "methods": [ + "complete_query" + ] + } + } + }, + "rest": { + "libraryClient": "CompletionServiceClient", + "rpcs": { + "CompleteQuery": { + "methods": [ + "complete_query" + ] + } + } + } + } + }, + "ConversationalSearchService": { + "clients": { + "grpc": { + "libraryClient": "ConversationalSearchServiceClient", + "rpcs": { + "ConverseConversation": { + "methods": [ + "converse_conversation" + ] + }, + "CreateConversation": { + "methods": [ + "create_conversation" + ] + }, + "DeleteConversation": { + "methods": [ + "delete_conversation" + ] + }, + "GetConversation": { + "methods": [ + "get_conversation" + ] + }, + "ListConversations": { + "methods": [ + "list_conversations" + ] + }, + "UpdateConversation": { + "methods": [ + "update_conversation" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ConversationalSearchServiceAsyncClient", + "rpcs": { + "ConverseConversation": { + "methods": [ + "converse_conversation" + ] + }, + "CreateConversation": { + "methods": [ + "create_conversation" + ] + }, + "DeleteConversation": { + "methods": [ + "delete_conversation" + ] + }, + "GetConversation": { + "methods": [ + "get_conversation" + ] + }, + "ListConversations": { + "methods": [ + "list_conversations" + ] + }, + "UpdateConversation": { + "methods": [ + "update_conversation" + ] + } + } + }, + "rest": { + "libraryClient": "ConversationalSearchServiceClient", + "rpcs": { + "ConverseConversation": { + "methods": [ + "converse_conversation" + ] + }, + "CreateConversation": { + "methods": [ + "create_conversation" + ] + }, + "DeleteConversation": { + "methods": [ + "delete_conversation" + ] + }, + "GetConversation": { + "methods": [ + "get_conversation" + ] + }, + "ListConversations": { + "methods": [ + "list_conversations" + ] + }, + "UpdateConversation": { + "methods": [ + "update_conversation" + ] + } + } + } + } + }, + "DocumentService": { + "clients": { + "grpc": { + "libraryClient": "DocumentServiceClient", + "rpcs": { + "CreateDocument": { + "methods": [ + "create_document" + ] + }, + "DeleteDocument": { + "methods": [ + "delete_document" + ] + }, + "GetDocument": { + "methods": [ + "get_document" + ] + }, + "ImportDocuments": { + "methods": [ + "import_documents" + ] + }, + "ListDocuments": { + "methods": [ + "list_documents" + ] + }, + "PurgeDocuments": { + "methods": [ + "purge_documents" + ] + }, + "UpdateDocument": { + "methods": [ + "update_document" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DocumentServiceAsyncClient", + "rpcs": { + "CreateDocument": { + "methods": [ + "create_document" + ] + }, + "DeleteDocument": { + "methods": [ + "delete_document" + ] + }, + "GetDocument": { + "methods": [ + "get_document" + ] + }, + "ImportDocuments": { + "methods": [ + "import_documents" + ] + }, + "ListDocuments": { + "methods": [ + "list_documents" + ] + }, + "PurgeDocuments": { + "methods": [ + "purge_documents" + ] + }, + "UpdateDocument": { + "methods": [ + "update_document" + ] + } + } + }, + "rest": { + "libraryClient": "DocumentServiceClient", + "rpcs": { + "CreateDocument": { + "methods": [ + "create_document" + ] + }, + "DeleteDocument": { + "methods": [ + "delete_document" + ] + }, + "GetDocument": { + "methods": [ + "get_document" + ] + }, + "ImportDocuments": { + "methods": [ + "import_documents" + ] + }, + "ListDocuments": { + "methods": [ + "list_documents" + ] + }, + "PurgeDocuments": { + "methods": [ + "purge_documents" + ] + }, + "UpdateDocument": { + "methods": [ + "update_document" + ] + } + } + } + } + }, + "SchemaService": { + "clients": { + "grpc": { + "libraryClient": "SchemaServiceClient", + "rpcs": { + "CreateSchema": { + "methods": [ + "create_schema" + ] + }, + "DeleteSchema": { + "methods": [ + "delete_schema" + ] + }, + "GetSchema": { + "methods": [ + "get_schema" + ] + }, + "ListSchemas": { + "methods": [ + "list_schemas" + ] + }, + "UpdateSchema": { + "methods": [ + "update_schema" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SchemaServiceAsyncClient", + "rpcs": { + "CreateSchema": { + "methods": [ + "create_schema" + ] + }, + "DeleteSchema": { + "methods": [ + "delete_schema" + ] + }, + "GetSchema": { + "methods": [ + "get_schema" + ] + }, + "ListSchemas": { + "methods": [ + "list_schemas" + ] + }, + "UpdateSchema": { + "methods": [ + "update_schema" + ] + } + } + }, + "rest": { + "libraryClient": "SchemaServiceClient", + "rpcs": { + "CreateSchema": { + "methods": [ + "create_schema" + ] + }, + "DeleteSchema": { + "methods": [ + "delete_schema" + ] + }, + "GetSchema": { + "methods": [ + "get_schema" + ] + }, + "ListSchemas": { + "methods": [ + "list_schemas" + ] + }, + "UpdateSchema": { + "methods": [ + "update_schema" + ] + } + } + } + } + }, + "SearchService": { + "clients": { + "grpc": { + "libraryClient": "SearchServiceClient", + "rpcs": { + "Search": { + "methods": [ + "search" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SearchServiceAsyncClient", + "rpcs": { + "Search": { + "methods": [ + "search" + ] + } + } + }, + "rest": { + "libraryClient": "SearchServiceClient", + "rpcs": { + "Search": { + "methods": [ + "search" + ] + } + } + } + } + }, + "UserEventService": { + "clients": { + "grpc": { + "libraryClient": "UserEventServiceClient", + "rpcs": { + "CollectUserEvent": { + "methods": [ + "collect_user_event" + ] + }, + "ImportUserEvents": { + "methods": [ + "import_user_events" + ] + }, + "WriteUserEvent": { + "methods": [ + "write_user_event" + ] + } + } + }, + "grpc-async": { + "libraryClient": "UserEventServiceAsyncClient", + "rpcs": { + "CollectUserEvent": { + "methods": [ + "collect_user_event" + ] + }, + "ImportUserEvents": { + "methods": [ + "import_user_events" + ] + }, + "WriteUserEvent": { + "methods": [ + "write_user_event" + ] + } + } + }, + "rest": { + "libraryClient": "UserEventServiceClient", + "rpcs": { + "CollectUserEvent": { + "methods": [ + "collect_user_event" + ] + }, + "ImportUserEvents": { + "methods": [ + "import_user_events" + ] + }, + "WriteUserEvent": { + "methods": [ + "write_user_event" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/gapic_version.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/gapic_version.py new file mode 100644 index 000000000000..360a0d13ebdd --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/py.typed b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/py.typed new file mode 100644 index 000000000000..2ff6437cf473 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-discoveryengine package uses inline types. diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/__init__.py new file mode 100644 index 000000000000..89a37dc92c5a --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/__init__.py new file mode 100644 index 000000000000..440cbfb40963 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import CompletionServiceClient +from .async_client import CompletionServiceAsyncClient + +__all__ = ( + 'CompletionServiceClient', + 'CompletionServiceAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/async_client.py new file mode 100644 index 000000000000..5ddbf499bf7b --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/async_client.py @@ -0,0 +1,386 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.discoveryengine_v1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.discoveryengine_v1.types import completion_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport +from .client import CompletionServiceClient + + +class CompletionServiceAsyncClient: + """Service for Auto-Completion.""" + + _client: CompletionServiceClient + + DEFAULT_ENDPOINT = CompletionServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = CompletionServiceClient.DEFAULT_MTLS_ENDPOINT + + data_store_path = staticmethod(CompletionServiceClient.data_store_path) + parse_data_store_path = staticmethod(CompletionServiceClient.parse_data_store_path) + common_billing_account_path = staticmethod(CompletionServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(CompletionServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(CompletionServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(CompletionServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(CompletionServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(CompletionServiceClient.parse_common_organization_path) + common_project_path = staticmethod(CompletionServiceClient.common_project_path) + parse_common_project_path = staticmethod(CompletionServiceClient.parse_common_project_path) + common_location_path = staticmethod(CompletionServiceClient.common_location_path) + parse_common_location_path = staticmethod(CompletionServiceClient.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: + CompletionServiceAsyncClient: The constructed client. + """ + return CompletionServiceClient.from_service_account_info.__func__(CompletionServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceAsyncClient: The constructed client. + """ + return CompletionServiceClient.from_service_account_file.__func__(CompletionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return CompletionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> CompletionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CompletionServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(CompletionServiceClient).get_transport_class, type(CompletionServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, CompletionServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the completion 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 (Union[str, ~.CompletionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = CompletionServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def complete_query(self, + request: Optional[Union[completion_service.CompleteQueryRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> completion_service.CompleteQueryResponse: + r"""Completes the specified user input with keyword + suggestions. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + async def sample_complete_query(): + # Create a client + client = discoveryengine_v1.CompletionServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.CompleteQueryRequest( + data_store="data_store_value", + query="query_value", + ) + + # Make the request + response = await client.complete_query(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1.types.CompleteQueryRequest, dict]]): + The request object. Request message for + [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1.CompletionService.CompleteQuery] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1.types.CompleteQueryResponse: + Response message for + [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1.CompletionService.CompleteQuery] + method. + + """ + # Create or coerce a protobuf request object. + request = completion_service.CompleteQueryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.complete_query, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("data_store", request.data_store), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "CompletionServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "CompletionServiceAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/client.py new file mode 100644 index 000000000000..2d3a30a2c1f7 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/client.py @@ -0,0 +1,594 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.discoveryengine_v1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.discoveryengine_v1.types import completion_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import CompletionServiceGrpcTransport +from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport +from .transports.rest import CompletionServiceRestTransport + + +class CompletionServiceClientMeta(type): + """Metaclass for the CompletionService 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[CompletionServiceTransport]] + _transport_registry["grpc"] = CompletionServiceGrpcTransport + _transport_registry["grpc_asyncio"] = CompletionServiceGrpcAsyncIOTransport + _transport_registry["rest"] = CompletionServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[CompletionServiceTransport]: + """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 CompletionServiceClient(metaclass=CompletionServiceClientMeta): + """Service for Auto-Completion.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceClient: 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: + CompletionServiceClient: 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) -> CompletionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CompletionServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def data_store_path(project: str,location: str,data_store: str,) -> str: + """Returns a fully-qualified data_store string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) + + @staticmethod + def parse_data_store_path(path: str) -> Dict[str,str]: + """Parses a data_store path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, CompletionServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the completion 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 (Union[str, CompletionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, CompletionServiceTransport): + # transport is a CompletionServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def complete_query(self, + request: Optional[Union[completion_service.CompleteQueryRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> completion_service.CompleteQueryResponse: + r"""Completes the specified user input with keyword + suggestions. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + def sample_complete_query(): + # Create a client + client = discoveryengine_v1.CompletionServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.CompleteQueryRequest( + data_store="data_store_value", + query="query_value", + ) + + # Make the request + response = client.complete_query(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1.types.CompleteQueryRequest, dict]): + The request object. Request message for + [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1.CompletionService.CompleteQuery] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1.types.CompleteQueryResponse: + Response message for + [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1.CompletionService.CompleteQuery] + method. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a completion_service.CompleteQueryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, completion_service.CompleteQueryRequest): + request = completion_service.CompleteQueryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.complete_query] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("data_store", request.data_store), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "CompletionServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "CompletionServiceClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/__init__.py new file mode 100644 index 000000000000..f32ad4419b13 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import CompletionServiceTransport +from .grpc import CompletionServiceGrpcTransport +from .grpc_asyncio import CompletionServiceGrpcAsyncIOTransport +from .rest import CompletionServiceRestTransport +from .rest import CompletionServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] +_transport_registry['grpc'] = CompletionServiceGrpcTransport +_transport_registry['grpc_asyncio'] = CompletionServiceGrpcAsyncIOTransport +_transport_registry['rest'] = CompletionServiceRestTransport + +__all__ = ( + 'CompletionServiceTransport', + 'CompletionServiceGrpcTransport', + 'CompletionServiceGrpcAsyncIOTransport', + 'CompletionServiceRestTransport', + 'CompletionServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/base.py new file mode 100644 index 000000000000..ab8350b556c9 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/base.py @@ -0,0 +1,168 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.discoveryengine_v1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.discoveryengine_v1.types import completion_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class CompletionServiceTransport(abc.ABC): + """Abstract transport class for CompletionService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'discoveryengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.complete_query: gapic_v1.method.wrap_method( + self.complete_query, + 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 complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + Union[ + completion_service.CompleteQueryResponse, + Awaitable[completion_service.CompleteQueryResponse] + ]]: + 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 kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'CompletionServiceTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/grpc.py new file mode 100644 index 000000000000..5ce36ba7ca47 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/grpc.py @@ -0,0 +1,303 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.discoveryengine_v1.types import completion_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO + + +class CompletionServiceGrpcTransport(CompletionServiceTransport): + """gRPC backend transport for CompletionService. + + Service for Auto-Completion. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + completion_service.CompleteQueryResponse]: + r"""Return a callable for the complete query method over gRPC. + + Completes the specified user input with keyword + suggestions. + + Returns: + Callable[[~.CompleteQueryRequest], + ~.CompleteQueryResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'complete_query' not in self._stubs: + self._stubs['complete_query'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.CompletionService/CompleteQuery', + request_serializer=completion_service.CompleteQueryRequest.serialize, + response_deserializer=completion_service.CompleteQueryResponse.deserialize, + ) + return self._stubs['complete_query'] + + def close(self): + self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'CompletionServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..9578fc7444f4 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/grpc_asyncio.py @@ -0,0 +1,302 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.discoveryengine_v1.types import completion_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import CompletionServiceGrpcTransport + + +class CompletionServiceGrpcAsyncIOTransport(CompletionServiceTransport): + """gRPC AsyncIO backend transport for CompletionService. + + Service for Auto-Completion. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + Awaitable[completion_service.CompleteQueryResponse]]: + r"""Return a callable for the complete query method over gRPC. + + Completes the specified user input with keyword + suggestions. + + Returns: + Callable[[~.CompleteQueryRequest], + Awaitable[~.CompleteQueryResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'complete_query' not in self._stubs: + self._stubs['complete_query'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.CompletionService/CompleteQuery', + request_serializer=completion_service.CompleteQueryRequest.serialize, + response_deserializer=completion_service.CompleteQueryResponse.deserialize, + ) + return self._stubs['complete_query'] + + def close(self): + return self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ( + 'CompletionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/rest.py new file mode 100644 index 000000000000..11075f2905e8 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/rest.py @@ -0,0 +1,574 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.cloud.location import locations_pb2 # type: ignore +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.discoveryengine_v1.types import completion_service +from google.longrunning import operations_pb2 # type: ignore + +from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class CompletionServiceRestInterceptor: + """Interceptor for CompletionService. + + 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 CompletionServiceRestTransport. + + .. code-block:: python + class MyCustomCompletionServiceInterceptor(CompletionServiceRestInterceptor): + def pre_complete_query(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_complete_query(self, response): + logging.log(f"Received response: {response}") + return response + + transport = CompletionServiceRestTransport(interceptor=MyCustomCompletionServiceInterceptor()) + client = CompletionServiceClient(transport=transport) + + + """ + def pre_complete_query(self, request: completion_service.CompleteQueryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[completion_service.CompleteQueryRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for complete_query + + Override in a subclass to manipulate the request or metadata + before they are sent to the CompletionService server. + """ + return request, metadata + + def post_complete_query(self, response: completion_service.CompleteQueryResponse) -> completion_service.CompleteQueryResponse: + """Post-rpc interceptor for complete_query + + Override in a subclass to manipulate the response + after it is returned by the CompletionService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the CompletionService 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 CompletionService server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the CompletionService 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 CompletionService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class CompletionServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: CompletionServiceRestInterceptor + + +class CompletionServiceRestTransport(CompletionServiceTransport): + """REST backend transport for CompletionService. + + Service for Auto-Completion. + + 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 = 'discoveryengine.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[CompletionServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or CompletionServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CompleteQuery(CompletionServiceRestStub): + def __hash__(self): + return hash("CompleteQuery") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "query" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: completion_service.CompleteQueryRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> completion_service.CompleteQueryResponse: + r"""Call the complete query method over HTTP. + + Args: + request (~.completion_service.CompleteQueryRequest): + The request object. Request message for + [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1.CompletionService.CompleteQuery] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.completion_service.CompleteQueryResponse: + Response message for + [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1.CompletionService.CompleteQuery] + method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{data_store=projects/*/locations/*/dataStores/*}:completeQuery', + }, +{ + 'method': 'get', + 'uri': '/v1/{data_store=projects/*/locations/*/collections/*/dataStores/*}:completeQuery', + }, + ] + request, metadata = self._interceptor.pre_complete_query(request, metadata) + pb_request = completion_service.CompleteQueryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = completion_service.CompleteQueryResponse() + pb_resp = completion_service.CompleteQueryResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_complete_query(resp) + return resp + + @property + def complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + completion_service.CompleteQueryResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CompleteQuery(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(CompletionServiceRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(CompletionServiceRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/engines/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'CompletionServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/__init__.py new file mode 100644 index 000000000000..4bf42b241a8b --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import ConversationalSearchServiceClient +from .async_client import ConversationalSearchServiceAsyncClient + +__all__ = ( + 'ConversationalSearchServiceClient', + 'ConversationalSearchServiceAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/async_client.py new file mode 100644 index 000000000000..82846c2f6824 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/async_client.py @@ -0,0 +1,971 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.discoveryengine_v1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.discoveryengine_v1.services.conversational_search_service import pagers +from google.cloud.discoveryengine_v1.types import conversation +from google.cloud.discoveryengine_v1.types import conversation as gcd_conversation +from google.cloud.discoveryengine_v1.types import conversational_search_service +from google.cloud.discoveryengine_v1.types import search_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ConversationalSearchServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ConversationalSearchServiceGrpcAsyncIOTransport +from .client import ConversationalSearchServiceClient + + +class ConversationalSearchServiceAsyncClient: + """Service for conversational search.""" + + _client: ConversationalSearchServiceClient + + DEFAULT_ENDPOINT = ConversationalSearchServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ConversationalSearchServiceClient.DEFAULT_MTLS_ENDPOINT + + conversation_path = staticmethod(ConversationalSearchServiceClient.conversation_path) + parse_conversation_path = staticmethod(ConversationalSearchServiceClient.parse_conversation_path) + data_store_path = staticmethod(ConversationalSearchServiceClient.data_store_path) + parse_data_store_path = staticmethod(ConversationalSearchServiceClient.parse_data_store_path) + document_path = staticmethod(ConversationalSearchServiceClient.document_path) + parse_document_path = staticmethod(ConversationalSearchServiceClient.parse_document_path) + serving_config_path = staticmethod(ConversationalSearchServiceClient.serving_config_path) + parse_serving_config_path = staticmethod(ConversationalSearchServiceClient.parse_serving_config_path) + common_billing_account_path = staticmethod(ConversationalSearchServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ConversationalSearchServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ConversationalSearchServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(ConversationalSearchServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(ConversationalSearchServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(ConversationalSearchServiceClient.parse_common_organization_path) + common_project_path = staticmethod(ConversationalSearchServiceClient.common_project_path) + parse_common_project_path = staticmethod(ConversationalSearchServiceClient.parse_common_project_path) + common_location_path = staticmethod(ConversationalSearchServiceClient.common_location_path) + parse_common_location_path = staticmethod(ConversationalSearchServiceClient.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: + ConversationalSearchServiceAsyncClient: The constructed client. + """ + return ConversationalSearchServiceClient.from_service_account_info.__func__(ConversationalSearchServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ConversationalSearchServiceAsyncClient: The constructed client. + """ + return ConversationalSearchServiceClient.from_service_account_file.__func__(ConversationalSearchServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return ConversationalSearchServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ConversationalSearchServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ConversationalSearchServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ConversationalSearchServiceClient).get_transport_class, type(ConversationalSearchServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ConversationalSearchServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the conversational search 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 (Union[str, ~.ConversationalSearchServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ConversationalSearchServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def converse_conversation(self, + request: Optional[Union[conversational_search_service.ConverseConversationRequest, dict]] = None, + *, + name: Optional[str] = None, + query: Optional[conversation.TextInput] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversational_search_service.ConverseConversationResponse: + r"""Converses 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 discoveryengine_v1 + + async def sample_converse_conversation(): + # Create a client + client = discoveryengine_v1.ConversationalSearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.ConverseConversationRequest( + name="name_value", + ) + + # Make the request + response = await client.converse_conversation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1.types.ConverseConversationRequest, dict]]): + The request object. Request message for + [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1.ConversationalSearchService.ConverseConversation] + method. + name (:class:`str`): + Required. The resource name of the Conversation to get. + Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}``. + Use + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/-`` + to activate auto session mode, which automatically + creates a new conversation inside a ConverseConversation + session. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + query (:class:`google.cloud.discoveryengine_v1.types.TextInput`): + Required. Current user input. + This corresponds to the ``query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1.types.ConverseConversationResponse: + Response message for + [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1.ConversationalSearchService.ConverseConversation] + method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, query]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = conversational_search_service.ConverseConversationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if query is not None: + request.query = query + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.converse_conversation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_conversation(self, + request: Optional[Union[conversational_search_service.CreateConversationRequest, dict]] = None, + *, + parent: Optional[str] = None, + conversation: Optional[gcd_conversation.Conversation] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_conversation.Conversation: + r"""Creates a Conversation. + + If the + [Conversation][google.cloud.discoveryengine.v1.Conversation] to + create already exists, an ALREADY_EXISTS error is returned. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + async def sample_create_conversation(): + # Create a client + client = discoveryengine_v1.ConversationalSearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.CreateConversationRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_conversation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1.types.CreateConversationRequest, dict]]): + The request object. Request for CreateConversation + method. + parent (:class:`str`): + Required. Full resource name of parent data store. + Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + conversation (:class:`google.cloud.discoveryengine_v1.types.Conversation`): + Required. The conversation to create. + This corresponds to the ``conversation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1.types.Conversation: + External conversation proto + definition. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, conversation]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = conversational_search_service.CreateConversationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if conversation is not None: + request.conversation = conversation + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_conversation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_conversation(self, + request: Optional[Union[conversational_search_service.DeleteConversationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a Conversation. + + If the + [Conversation][google.cloud.discoveryengine.v1.Conversation] to + delete does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + async def sample_delete_conversation(): + # Create a client + client = discoveryengine_v1.ConversationalSearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.DeleteConversationRequest( + name="name_value", + ) + + # Make the request + await client.delete_conversation(request=request) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1.types.DeleteConversationRequest, dict]]): + The request object. Request for DeleteConversation + method. + name (:class:`str`): + Required. The resource name of the Conversation to + delete. Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = conversational_search_service.DeleteConversationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_conversation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def update_conversation(self, + request: Optional[Union[conversational_search_service.UpdateConversationRequest, dict]] = None, + *, + conversation: Optional[gcd_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, str]] = (), + ) -> gcd_conversation.Conversation: + r"""Updates a Conversation. + + [Conversation][google.cloud.discoveryengine.v1.Conversation] + action type cannot be changed. If the + [Conversation][google.cloud.discoveryengine.v1.Conversation] to + update does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + async def sample_update_conversation(): + # Create a client + client = discoveryengine_v1.ConversationalSearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.UpdateConversationRequest( + ) + + # Make the request + response = await client.update_conversation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1.types.UpdateConversationRequest, dict]]): + The request object. Request for UpdateConversation + method. + conversation (:class:`google.cloud.discoveryengine_v1.types.Conversation`): + Required. The Conversation to update. + 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`): + Indicates which fields in the provided + [Conversation][google.cloud.discoveryengine.v1.Conversation] + to update. The following are NOT supported: + + - [conversation.name][] + + If not set or empty, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1.types.Conversation: + External conversation proto + definition. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([conversation, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = conversational_search_service.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 = gapic_v1.method_async.wrap_method( + self._client._transport.update_conversation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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), + )), + ) + + # 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[conversational_search_service.GetConversationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversation.Conversation: + r"""Gets 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 discoveryengine_v1 + + async def sample_get_conversation(): + # Create a client + client = discoveryengine_v1.ConversationalSearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.GetConversationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_conversation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1.types.GetConversationRequest, dict]]): + The request object. Request for GetConversation method. + name (:class:`str`): + Required. The resource name of the Conversation to get. + Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1.types.Conversation: + External conversation proto + definition. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = conversational_search_service.GetConversationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_conversation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_conversations(self, + request: Optional[Union[conversational_search_service.ListConversationsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListConversationsAsyncPager: + r"""Lists all Conversations by their parent + [DataStore][google.cloud.discoveryengine.v1.DataStore]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + async def sample_list_conversations(): + # Create a client + client = discoveryengine_v1.ConversationalSearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.ListConversationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_conversations(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1.types.ListConversationsRequest, dict]]): + The request object. Request for ListConversations method. + parent (:class:`str`): + Required. The data store resource name. Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1.services.conversational_search_service.pagers.ListConversationsAsyncPager: + Response for ListConversations + method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = conversational_search_service.ListConversationsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_conversations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListConversationsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "ConversationalSearchServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "ConversationalSearchServiceAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/client.py new file mode 100644 index 000000000000..4f48e82d6e56 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/client.py @@ -0,0 +1,1205 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.discoveryengine_v1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.discoveryengine_v1.services.conversational_search_service import pagers +from google.cloud.discoveryengine_v1.types import conversation +from google.cloud.discoveryengine_v1.types import conversation as gcd_conversation +from google.cloud.discoveryengine_v1.types import conversational_search_service +from google.cloud.discoveryengine_v1.types import search_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ConversationalSearchServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ConversationalSearchServiceGrpcTransport +from .transports.grpc_asyncio import ConversationalSearchServiceGrpcAsyncIOTransport +from .transports.rest import ConversationalSearchServiceRestTransport + + +class ConversationalSearchServiceClientMeta(type): + """Metaclass for the ConversationalSearchService 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[ConversationalSearchServiceTransport]] + _transport_registry["grpc"] = ConversationalSearchServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ConversationalSearchServiceGrpcAsyncIOTransport + _transport_registry["rest"] = ConversationalSearchServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[ConversationalSearchServiceTransport]: + """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 ConversationalSearchServiceClient(metaclass=ConversationalSearchServiceClientMeta): + """Service for conversational search.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ConversationalSearchServiceClient: 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: + ConversationalSearchServiceClient: 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) -> ConversationalSearchServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ConversationalSearchServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def conversation_path(project: str,location: str,data_store: str,conversation: str,) -> str: + """Returns a fully-qualified conversation string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/conversations/{conversation}".format(project=project, location=location, data_store=data_store, conversation=conversation, ) + + @staticmethod + def parse_conversation_path(path: str) -> Dict[str,str]: + """Parses a conversation path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/conversations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def data_store_path(project: str,location: str,data_store: str,) -> str: + """Returns a fully-qualified data_store string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) + + @staticmethod + def parse_data_store_path(path: str) -> Dict[str,str]: + """Parses a data_store path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def document_path(project: str,location: str,data_store: str,branch: str,document: str,) -> str: + """Returns a fully-qualified document string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) + + @staticmethod + def parse_document_path(path: str) -> Dict[str,str]: + """Parses a document path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)/documents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def serving_config_path(project: str,location: str,data_store: str,serving_config: str,) -> str: + """Returns a fully-qualified serving_config string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/servingConfigs/{serving_config}".format(project=project, location=location, data_store=data_store, serving_config=serving_config, ) + + @staticmethod + def parse_serving_config_path(path: str) -> Dict[str,str]: + """Parses a serving_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/servingConfigs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ConversationalSearchServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the conversational search 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 (Union[str, ConversationalSearchServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ConversationalSearchServiceTransport): + # transport is a ConversationalSearchServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def converse_conversation(self, + request: Optional[Union[conversational_search_service.ConverseConversationRequest, dict]] = None, + *, + name: Optional[str] = None, + query: Optional[conversation.TextInput] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversational_search_service.ConverseConversationResponse: + r"""Converses 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 discoveryengine_v1 + + def sample_converse_conversation(): + # Create a client + client = discoveryengine_v1.ConversationalSearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.ConverseConversationRequest( + name="name_value", + ) + + # Make the request + response = client.converse_conversation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1.types.ConverseConversationRequest, dict]): + The request object. Request message for + [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1.ConversationalSearchService.ConverseConversation] + method. + name (str): + Required. The resource name of the Conversation to get. + Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}``. + Use + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/-`` + to activate auto session mode, which automatically + creates a new conversation inside a ConverseConversation + session. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + query (google.cloud.discoveryengine_v1.types.TextInput): + Required. Current user input. + This corresponds to the ``query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1.types.ConverseConversationResponse: + Response message for + [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1.ConversationalSearchService.ConverseConversation] + method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, query]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a conversational_search_service.ConverseConversationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, conversational_search_service.ConverseConversationRequest): + request = conversational_search_service.ConverseConversationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if query is not None: + request.query = query + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.converse_conversation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_conversation(self, + request: Optional[Union[conversational_search_service.CreateConversationRequest, dict]] = None, + *, + parent: Optional[str] = None, + conversation: Optional[gcd_conversation.Conversation] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_conversation.Conversation: + r"""Creates a Conversation. + + If the + [Conversation][google.cloud.discoveryengine.v1.Conversation] to + create already exists, an ALREADY_EXISTS error is returned. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + def sample_create_conversation(): + # Create a client + client = discoveryengine_v1.ConversationalSearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.CreateConversationRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_conversation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1.types.CreateConversationRequest, dict]): + The request object. Request for CreateConversation + method. + parent (str): + Required. Full resource name of parent data store. + Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + conversation (google.cloud.discoveryengine_v1.types.Conversation): + Required. The conversation to create. + This corresponds to the ``conversation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1.types.Conversation: + External conversation proto + definition. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, conversation]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a conversational_search_service.CreateConversationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, conversational_search_service.CreateConversationRequest): + request = conversational_search_service.CreateConversationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if conversation is not None: + request.conversation = conversation + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_conversation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_conversation(self, + request: Optional[Union[conversational_search_service.DeleteConversationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a Conversation. + + If the + [Conversation][google.cloud.discoveryengine.v1.Conversation] to + delete does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + def sample_delete_conversation(): + # Create a client + client = discoveryengine_v1.ConversationalSearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.DeleteConversationRequest( + name="name_value", + ) + + # Make the request + client.delete_conversation(request=request) + + Args: + request (Union[google.cloud.discoveryengine_v1.types.DeleteConversationRequest, dict]): + The request object. Request for DeleteConversation + method. + name (str): + Required. The resource name of the Conversation to + delete. Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a conversational_search_service.DeleteConversationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, conversational_search_service.DeleteConversationRequest): + request = conversational_search_service.DeleteConversationRequest(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_conversation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def update_conversation(self, + request: Optional[Union[conversational_search_service.UpdateConversationRequest, dict]] = None, + *, + conversation: Optional[gcd_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, str]] = (), + ) -> gcd_conversation.Conversation: + r"""Updates a Conversation. + + [Conversation][google.cloud.discoveryengine.v1.Conversation] + action type cannot be changed. If the + [Conversation][google.cloud.discoveryengine.v1.Conversation] to + update does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + def sample_update_conversation(): + # Create a client + client = discoveryengine_v1.ConversationalSearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.UpdateConversationRequest( + ) + + # Make the request + response = client.update_conversation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1.types.UpdateConversationRequest, dict]): + The request object. Request for UpdateConversation + method. + conversation (google.cloud.discoveryengine_v1.types.Conversation): + Required. The Conversation to update. + 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): + Indicates which fields in the provided + [Conversation][google.cloud.discoveryengine.v1.Conversation] + to update. The following are NOT supported: + + - [conversation.name][] + + If not set or empty, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1.types.Conversation: + External conversation proto + definition. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([conversation, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a conversational_search_service.UpdateConversationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, conversational_search_service.UpdateConversationRequest): + request = conversational_search_service.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), + )), + ) + + # 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[conversational_search_service.GetConversationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversation.Conversation: + r"""Gets 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 discoveryengine_v1 + + def sample_get_conversation(): + # Create a client + client = discoveryengine_v1.ConversationalSearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.GetConversationRequest( + name="name_value", + ) + + # Make the request + response = client.get_conversation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1.types.GetConversationRequest, dict]): + The request object. Request for GetConversation method. + name (str): + Required. The resource name of the Conversation to get. + Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1.types.Conversation: + External conversation proto + definition. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a conversational_search_service.GetConversationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, conversational_search_service.GetConversationRequest): + request = conversational_search_service.GetConversationRequest(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_conversation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_conversations(self, + request: Optional[Union[conversational_search_service.ListConversationsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListConversationsPager: + r"""Lists all Conversations by their parent + [DataStore][google.cloud.discoveryengine.v1.DataStore]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + def sample_list_conversations(): + # Create a client + client = discoveryengine_v1.ConversationalSearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.ListConversationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_conversations(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1.types.ListConversationsRequest, dict]): + The request object. Request for ListConversations method. + parent (str): + Required. The data store resource name. Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1.services.conversational_search_service.pagers.ListConversationsPager: + Response for ListConversations + method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a conversational_search_service.ListConversationsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, conversational_search_service.ListConversationsRequest): + request = conversational_search_service.ListConversationsRequest(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_conversations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListConversationsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "ConversationalSearchServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "ConversationalSearchServiceClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/pagers.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/pagers.py new file mode 100644 index 000000000000..c2b6b52ec303 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.discoveryengine_v1.types import conversation +from google.cloud.discoveryengine_v1.types import conversational_search_service + + +class ListConversationsPager: + """A pager for iterating through ``list_conversations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1.types.ListConversationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``conversations`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListConversations`` requests and continue to iterate + through the ``conversations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1.types.ListConversationsResponse` + 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[..., conversational_search_service.ListConversationsResponse], + request: conversational_search_service.ListConversationsRequest, + response: conversational_search_service.ListConversationsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.discoveryengine_v1.types.ListConversationsRequest): + The initial request object. + response (google.cloud.discoveryengine_v1.types.ListConversationsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = conversational_search_service.ListConversationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[conversational_search_service.ListConversationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[conversation.Conversation]: + for page in self.pages: + yield from page.conversations + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListConversationsAsyncPager: + """A pager for iterating through ``list_conversations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1.types.ListConversationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``conversations`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListConversations`` requests and continue to iterate + through the ``conversations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1.types.ListConversationsResponse` + 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[conversational_search_service.ListConversationsResponse]], + request: conversational_search_service.ListConversationsRequest, + response: conversational_search_service.ListConversationsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.discoveryengine_v1.types.ListConversationsRequest): + The initial request object. + response (google.cloud.discoveryengine_v1.types.ListConversationsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = conversational_search_service.ListConversationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[conversational_search_service.ListConversationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[conversation.Conversation]: + async def async_generator(): + async for page in self.pages: + for response in page.conversations: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/__init__.py new file mode 100644 index 000000000000..f49b63e4b6cd --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import ConversationalSearchServiceTransport +from .grpc import ConversationalSearchServiceGrpcTransport +from .grpc_asyncio import ConversationalSearchServiceGrpcAsyncIOTransport +from .rest import ConversationalSearchServiceRestTransport +from .rest import ConversationalSearchServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ConversationalSearchServiceTransport]] +_transport_registry['grpc'] = ConversationalSearchServiceGrpcTransport +_transport_registry['grpc_asyncio'] = ConversationalSearchServiceGrpcAsyncIOTransport +_transport_registry['rest'] = ConversationalSearchServiceRestTransport + +__all__ = ( + 'ConversationalSearchServiceTransport', + 'ConversationalSearchServiceGrpcTransport', + 'ConversationalSearchServiceGrpcAsyncIOTransport', + 'ConversationalSearchServiceRestTransport', + 'ConversationalSearchServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/base.py new file mode 100644 index 000000000000..a37715bd3bad --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/base.py @@ -0,0 +1,241 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.discoveryengine_v1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.discoveryengine_v1.types import conversation +from google.cloud.discoveryengine_v1.types import conversation as gcd_conversation +from google.cloud.discoveryengine_v1.types import conversational_search_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class ConversationalSearchServiceTransport(abc.ABC): + """Abstract transport class for ConversationalSearchService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'discoveryengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.converse_conversation: gapic_v1.method.wrap_method( + self.converse_conversation, + default_timeout=None, + client_info=client_info, + ), + self.create_conversation: gapic_v1.method.wrap_method( + self.create_conversation, + default_timeout=None, + client_info=client_info, + ), + self.delete_conversation: gapic_v1.method.wrap_method( + self.delete_conversation, + 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, + client_info=client_info, + ), + self.list_conversations: gapic_v1.method.wrap_method( + self.list_conversations, + 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 converse_conversation(self) -> Callable[ + [conversational_search_service.ConverseConversationRequest], + Union[ + conversational_search_service.ConverseConversationResponse, + Awaitable[conversational_search_service.ConverseConversationResponse] + ]]: + raise NotImplementedError() + + @property + def create_conversation(self) -> Callable[ + [conversational_search_service.CreateConversationRequest], + Union[ + gcd_conversation.Conversation, + Awaitable[gcd_conversation.Conversation] + ]]: + raise NotImplementedError() + + @property + def delete_conversation(self) -> Callable[ + [conversational_search_service.DeleteConversationRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_conversation(self) -> Callable[ + [conversational_search_service.UpdateConversationRequest], + Union[ + gcd_conversation.Conversation, + Awaitable[gcd_conversation.Conversation] + ]]: + raise NotImplementedError() + + @property + def get_conversation(self) -> Callable[ + [conversational_search_service.GetConversationRequest], + Union[ + conversation.Conversation, + Awaitable[conversation.Conversation] + ]]: + raise NotImplementedError() + + @property + def list_conversations(self) -> Callable[ + [conversational_search_service.ListConversationsRequest], + Union[ + conversational_search_service.ListConversationsResponse, + Awaitable[conversational_search_service.ListConversationsResponse] + ]]: + 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 kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ConversationalSearchServiceTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/grpc.py new file mode 100644 index 000000000000..d3ab8f9f152f --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/grpc.py @@ -0,0 +1,449 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.discoveryengine_v1.types import conversation +from google.cloud.discoveryengine_v1.types import conversation as gcd_conversation +from google.cloud.discoveryengine_v1.types import conversational_search_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import ConversationalSearchServiceTransport, DEFAULT_CLIENT_INFO + + +class ConversationalSearchServiceGrpcTransport(ConversationalSearchServiceTransport): + """gRPC backend transport for ConversationalSearchService. + + Service for conversational search. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def converse_conversation(self) -> Callable[ + [conversational_search_service.ConverseConversationRequest], + conversational_search_service.ConverseConversationResponse]: + r"""Return a callable for the converse conversation method over gRPC. + + Converses a conversation. + + Returns: + Callable[[~.ConverseConversationRequest], + ~.ConverseConversationResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'converse_conversation' not in self._stubs: + self._stubs['converse_conversation'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.ConversationalSearchService/ConverseConversation', + request_serializer=conversational_search_service.ConverseConversationRequest.serialize, + response_deserializer=conversational_search_service.ConverseConversationResponse.deserialize, + ) + return self._stubs['converse_conversation'] + + @property + def create_conversation(self) -> Callable[ + [conversational_search_service.CreateConversationRequest], + gcd_conversation.Conversation]: + r"""Return a callable for the create conversation method over gRPC. + + Creates a Conversation. + + If the + [Conversation][google.cloud.discoveryengine.v1.Conversation] to + create already exists, an ALREADY_EXISTS error is returned. + + Returns: + Callable[[~.CreateConversationRequest], + ~.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 'create_conversation' not in self._stubs: + self._stubs['create_conversation'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.ConversationalSearchService/CreateConversation', + request_serializer=conversational_search_service.CreateConversationRequest.serialize, + response_deserializer=gcd_conversation.Conversation.deserialize, + ) + return self._stubs['create_conversation'] + + @property + def delete_conversation(self) -> Callable[ + [conversational_search_service.DeleteConversationRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete conversation method over gRPC. + + Deletes a Conversation. + + If the + [Conversation][google.cloud.discoveryengine.v1.Conversation] to + delete does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.DeleteConversationRequest], + ~.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_conversation' not in self._stubs: + self._stubs['delete_conversation'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.ConversationalSearchService/DeleteConversation', + request_serializer=conversational_search_service.DeleteConversationRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_conversation'] + + @property + def update_conversation(self) -> Callable[ + [conversational_search_service.UpdateConversationRequest], + gcd_conversation.Conversation]: + r"""Return a callable for the update conversation method over gRPC. + + Updates a Conversation. + + [Conversation][google.cloud.discoveryengine.v1.Conversation] + action type cannot be changed. If the + [Conversation][google.cloud.discoveryengine.v1.Conversation] to + update does not exist, a NOT_FOUND error is returned. + + 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.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.ConversationalSearchService/UpdateConversation', + request_serializer=conversational_search_service.UpdateConversationRequest.serialize, + response_deserializer=gcd_conversation.Conversation.deserialize, + ) + return self._stubs['update_conversation'] + + @property + def get_conversation(self) -> Callable[ + [conversational_search_service.GetConversationRequest], + conversation.Conversation]: + r"""Return a callable for the get conversation method over gRPC. + + Gets a Conversation. + + Returns: + Callable[[~.GetConversationRequest], + ~.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 'get_conversation' not in self._stubs: + self._stubs['get_conversation'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.ConversationalSearchService/GetConversation', + request_serializer=conversational_search_service.GetConversationRequest.serialize, + response_deserializer=conversation.Conversation.deserialize, + ) + return self._stubs['get_conversation'] + + @property + def list_conversations(self) -> Callable[ + [conversational_search_service.ListConversationsRequest], + conversational_search_service.ListConversationsResponse]: + r"""Return a callable for the list conversations method over gRPC. + + Lists all Conversations by their parent + [DataStore][google.cloud.discoveryengine.v1.DataStore]. + + Returns: + Callable[[~.ListConversationsRequest], + ~.ListConversationsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversations' not in self._stubs: + self._stubs['list_conversations'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.ConversationalSearchService/ListConversations', + request_serializer=conversational_search_service.ListConversationsRequest.serialize, + response_deserializer=conversational_search_service.ListConversationsResponse.deserialize, + ) + return self._stubs['list_conversations'] + + def close(self): + self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ConversationalSearchServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..c7ca32705683 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/grpc_asyncio.py @@ -0,0 +1,448 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.discoveryengine_v1.types import conversation +from google.cloud.discoveryengine_v1.types import conversation as gcd_conversation +from google.cloud.discoveryengine_v1.types import conversational_search_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import ConversationalSearchServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import ConversationalSearchServiceGrpcTransport + + +class ConversationalSearchServiceGrpcAsyncIOTransport(ConversationalSearchServiceTransport): + """gRPC AsyncIO backend transport for ConversationalSearchService. + + Service for conversational search. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def converse_conversation(self) -> Callable[ + [conversational_search_service.ConverseConversationRequest], + Awaitable[conversational_search_service.ConverseConversationResponse]]: + r"""Return a callable for the converse conversation method over gRPC. + + Converses a conversation. + + Returns: + Callable[[~.ConverseConversationRequest], + Awaitable[~.ConverseConversationResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'converse_conversation' not in self._stubs: + self._stubs['converse_conversation'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.ConversationalSearchService/ConverseConversation', + request_serializer=conversational_search_service.ConverseConversationRequest.serialize, + response_deserializer=conversational_search_service.ConverseConversationResponse.deserialize, + ) + return self._stubs['converse_conversation'] + + @property + def create_conversation(self) -> Callable[ + [conversational_search_service.CreateConversationRequest], + Awaitable[gcd_conversation.Conversation]]: + r"""Return a callable for the create conversation method over gRPC. + + Creates a Conversation. + + If the + [Conversation][google.cloud.discoveryengine.v1.Conversation] to + create already exists, an ALREADY_EXISTS error is returned. + + Returns: + Callable[[~.CreateConversationRequest], + 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 'create_conversation' not in self._stubs: + self._stubs['create_conversation'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.ConversationalSearchService/CreateConversation', + request_serializer=conversational_search_service.CreateConversationRequest.serialize, + response_deserializer=gcd_conversation.Conversation.deserialize, + ) + return self._stubs['create_conversation'] + + @property + def delete_conversation(self) -> Callable[ + [conversational_search_service.DeleteConversationRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete conversation method over gRPC. + + Deletes a Conversation. + + If the + [Conversation][google.cloud.discoveryengine.v1.Conversation] to + delete does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.DeleteConversationRequest], + 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_conversation' not in self._stubs: + self._stubs['delete_conversation'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.ConversationalSearchService/DeleteConversation', + request_serializer=conversational_search_service.DeleteConversationRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_conversation'] + + @property + def update_conversation(self) -> Callable[ + [conversational_search_service.UpdateConversationRequest], + Awaitable[gcd_conversation.Conversation]]: + r"""Return a callable for the update conversation method over gRPC. + + Updates a Conversation. + + [Conversation][google.cloud.discoveryengine.v1.Conversation] + action type cannot be changed. If the + [Conversation][google.cloud.discoveryengine.v1.Conversation] to + update does not exist, a NOT_FOUND error is returned. + + 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.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.ConversationalSearchService/UpdateConversation', + request_serializer=conversational_search_service.UpdateConversationRequest.serialize, + response_deserializer=gcd_conversation.Conversation.deserialize, + ) + return self._stubs['update_conversation'] + + @property + def get_conversation(self) -> Callable[ + [conversational_search_service.GetConversationRequest], + Awaitable[conversation.Conversation]]: + r"""Return a callable for the get conversation method over gRPC. + + Gets a Conversation. + + Returns: + Callable[[~.GetConversationRequest], + 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 'get_conversation' not in self._stubs: + self._stubs['get_conversation'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.ConversationalSearchService/GetConversation', + request_serializer=conversational_search_service.GetConversationRequest.serialize, + response_deserializer=conversation.Conversation.deserialize, + ) + return self._stubs['get_conversation'] + + @property + def list_conversations(self) -> Callable[ + [conversational_search_service.ListConversationsRequest], + Awaitable[conversational_search_service.ListConversationsResponse]]: + r"""Return a callable for the list conversations method over gRPC. + + Lists all Conversations by their parent + [DataStore][google.cloud.discoveryengine.v1.DataStore]. + + Returns: + Callable[[~.ListConversationsRequest], + Awaitable[~.ListConversationsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversations' not in self._stubs: + self._stubs['list_conversations'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.ConversationalSearchService/ListConversations', + request_serializer=conversational_search_service.ListConversationsRequest.serialize, + response_deserializer=conversational_search_service.ListConversationsResponse.deserialize, + ) + return self._stubs['list_conversations'] + + def close(self): + return self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ( + 'ConversationalSearchServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/rest.py new file mode 100644 index 000000000000..ba997c667314 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/rest.py @@ -0,0 +1,1164 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.cloud.location import locations_pb2 # type: ignore +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.discoveryengine_v1.types import conversation +from google.cloud.discoveryengine_v1.types import conversation as gcd_conversation +from google.cloud.discoveryengine_v1.types import conversational_search_service +from google.protobuf import empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from .base import ConversationalSearchServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class ConversationalSearchServiceRestInterceptor: + """Interceptor for ConversationalSearchService. + + 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 ConversationalSearchServiceRestTransport. + + .. code-block:: python + class MyCustomConversationalSearchServiceInterceptor(ConversationalSearchServiceRestInterceptor): + def pre_converse_conversation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_converse_conversation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_conversation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_conversation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_conversation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_conversation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_conversation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_conversations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_conversations(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 = ConversationalSearchServiceRestTransport(interceptor=MyCustomConversationalSearchServiceInterceptor()) + client = ConversationalSearchServiceClient(transport=transport) + + + """ + def pre_converse_conversation(self, request: conversational_search_service.ConverseConversationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversational_search_service.ConverseConversationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for converse_conversation + + Override in a subclass to manipulate the request or metadata + before they are sent to the ConversationalSearchService server. + """ + return request, metadata + + def post_converse_conversation(self, response: conversational_search_service.ConverseConversationResponse) -> conversational_search_service.ConverseConversationResponse: + """Post-rpc interceptor for converse_conversation + + Override in a subclass to manipulate the response + after it is returned by the ConversationalSearchService server but before + it is returned to user code. + """ + return response + def pre_create_conversation(self, request: conversational_search_service.CreateConversationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversational_search_service.CreateConversationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_conversation + + Override in a subclass to manipulate the request or metadata + before they are sent to the ConversationalSearchService server. + """ + return request, metadata + + def post_create_conversation(self, response: gcd_conversation.Conversation) -> gcd_conversation.Conversation: + """Post-rpc interceptor for create_conversation + + Override in a subclass to manipulate the response + after it is returned by the ConversationalSearchService server but before + it is returned to user code. + """ + return response + def pre_delete_conversation(self, request: conversational_search_service.DeleteConversationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversational_search_service.DeleteConversationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_conversation + + Override in a subclass to manipulate the request or metadata + before they are sent to the ConversationalSearchService server. + """ + return request, metadata + + def pre_get_conversation(self, request: conversational_search_service.GetConversationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversational_search_service.GetConversationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_conversation + + Override in a subclass to manipulate the request or metadata + before they are sent to the ConversationalSearchService server. + """ + return request, metadata + + def post_get_conversation(self, response: conversation.Conversation) -> conversation.Conversation: + """Post-rpc interceptor for get_conversation + + Override in a subclass to manipulate the response + after it is returned by the ConversationalSearchService server but before + it is returned to user code. + """ + return response + def pre_list_conversations(self, request: conversational_search_service.ListConversationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversational_search_service.ListConversationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_conversations + + Override in a subclass to manipulate the request or metadata + before they are sent to the ConversationalSearchService server. + """ + return request, metadata + + def post_list_conversations(self, response: conversational_search_service.ListConversationsResponse) -> conversational_search_service.ListConversationsResponse: + """Post-rpc interceptor for list_conversations + + Override in a subclass to manipulate the response + after it is returned by the ConversationalSearchService server but before + it is returned to user code. + """ + return response + def pre_update_conversation(self, request: conversational_search_service.UpdateConversationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversational_search_service.UpdateConversationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_conversation + + Override in a subclass to manipulate the request or metadata + before they are sent to the ConversationalSearchService server. + """ + return request, metadata + + def post_update_conversation(self, response: gcd_conversation.Conversation) -> gcd_conversation.Conversation: + """Post-rpc interceptor for update_conversation + + Override in a subclass to manipulate the response + after it is returned by the ConversationalSearchService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the ConversationalSearchService 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 ConversationalSearchService server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the ConversationalSearchService 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 ConversationalSearchService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class ConversationalSearchServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ConversationalSearchServiceRestInterceptor + + +class ConversationalSearchServiceRestTransport(ConversationalSearchServiceTransport): + """REST backend transport for ConversationalSearchService. + + Service for conversational search. + + 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 = 'discoveryengine.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[ConversationalSearchServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or ConversationalSearchServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _ConverseConversation(ConversationalSearchServiceRestStub): + def __hash__(self): + return hash("ConverseConversation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: conversational_search_service.ConverseConversationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> conversational_search_service.ConverseConversationResponse: + r"""Call the converse conversation method over HTTP. + + Args: + request (~.conversational_search_service.ConverseConversationRequest): + The request object. Request message for + [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1.ConversationalSearchService.ConverseConversation] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.conversational_search_service.ConverseConversationResponse: + Response message for + [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1.ConversationalSearchService.ConverseConversation] + method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/conversations/*}:converse', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/conversations/*}:converse', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_converse_conversation(request, metadata) + pb_request = conversational_search_service.ConverseConversationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = conversational_search_service.ConverseConversationResponse() + pb_resp = conversational_search_service.ConverseConversationResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_converse_conversation(resp) + return resp + + class _CreateConversation(ConversationalSearchServiceRestStub): + def __hash__(self): + return hash("CreateConversation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: conversational_search_service.CreateConversationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcd_conversation.Conversation: + r"""Call the create conversation method over HTTP. + + Args: + request (~.conversational_search_service.CreateConversationRequest): + The request object. Request for CreateConversation + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcd_conversation.Conversation: + External conversation proto + definition. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/dataStores/*}/conversations', + 'body': 'conversation', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/collections/*/dataStores/*}/conversations', + 'body': 'conversation', + }, + ] + request, metadata = self._interceptor.pre_create_conversation(request, metadata) + pb_request = conversational_search_service.CreateConversationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcd_conversation.Conversation() + pb_resp = gcd_conversation.Conversation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_conversation(resp) + return resp + + class _DeleteConversation(ConversationalSearchServiceRestStub): + def __hash__(self): + return hash("DeleteConversation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: conversational_search_service.DeleteConversationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete conversation method over HTTP. + + Args: + request (~.conversational_search_service.DeleteConversationRequest): + The request object. Request for DeleteConversation + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/conversations/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/conversations/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_conversation(request, metadata) + pb_request = conversational_search_service.DeleteConversationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _GetConversation(ConversationalSearchServiceRestStub): + def __hash__(self): + return hash("GetConversation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: conversational_search_service.GetConversationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> conversation.Conversation: + r"""Call the get conversation method over HTTP. + + Args: + request (~.conversational_search_service.GetConversationRequest): + The request object. Request for GetConversation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.conversation.Conversation: + External conversation proto + definition. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/conversations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/conversations/*}', + }, + ] + request, metadata = self._interceptor.pre_get_conversation(request, metadata) + pb_request = conversational_search_service.GetConversationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = conversation.Conversation() + pb_resp = conversation.Conversation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_conversation(resp) + return resp + + class _ListConversations(ConversationalSearchServiceRestStub): + def __hash__(self): + return hash("ListConversations") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: conversational_search_service.ListConversationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> conversational_search_service.ListConversationsResponse: + r"""Call the list conversations method over HTTP. + + Args: + request (~.conversational_search_service.ListConversationsRequest): + The request object. Request for ListConversations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.conversational_search_service.ListConversationsResponse: + Response for ListConversations + method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/dataStores/*}/conversations', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/collections/*/dataStores/*}/conversations', + }, + ] + request, metadata = self._interceptor.pre_list_conversations(request, metadata) + pb_request = conversational_search_service.ListConversationsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = conversational_search_service.ListConversationsResponse() + pb_resp = conversational_search_service.ListConversationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_conversations(resp) + return resp + + class _UpdateConversation(ConversationalSearchServiceRestStub): + def __hash__(self): + return hash("UpdateConversation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: conversational_search_service.UpdateConversationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcd_conversation.Conversation: + r"""Call the update conversation method over HTTP. + + Args: + request (~.conversational_search_service.UpdateConversationRequest): + The request object. Request for UpdateConversation + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcd_conversation.Conversation: + External conversation proto + definition. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{conversation.name=projects/*/locations/*/dataStores/*/conversations/*}', + 'body': 'conversation', + }, +{ + 'method': 'patch', + 'uri': '/v1/{conversation.name=projects/*/locations/*/collections/*/dataStores/*/conversations/*}', + 'body': 'conversation', + }, + ] + request, metadata = self._interceptor.pre_update_conversation(request, metadata) + pb_request = conversational_search_service.UpdateConversationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcd_conversation.Conversation() + pb_resp = gcd_conversation.Conversation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_conversation(resp) + return resp + + @property + def converse_conversation(self) -> Callable[ + [conversational_search_service.ConverseConversationRequest], + conversational_search_service.ConverseConversationResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ConverseConversation(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_conversation(self) -> Callable[ + [conversational_search_service.CreateConversationRequest], + gcd_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._CreateConversation(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_conversation(self) -> Callable[ + [conversational_search_service.DeleteConversationRequest], + 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._DeleteConversation(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_conversation(self) -> Callable[ + [conversational_search_service.GetConversationRequest], + 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._GetConversation(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_conversations(self) -> Callable[ + [conversational_search_service.ListConversationsRequest], + conversational_search_service.ListConversationsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListConversations(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_conversation(self) -> Callable[ + [conversational_search_service.UpdateConversationRequest], + gcd_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_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(ConversationalSearchServiceRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(ConversationalSearchServiceRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/engines/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'ConversationalSearchServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/__init__.py new file mode 100644 index 000000000000..e4f0b808a498 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import DocumentServiceClient +from .async_client import DocumentServiceAsyncClient + +__all__ = ( + 'DocumentServiceClient', + 'DocumentServiceAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/async_client.py new file mode 100644 index 000000000000..729c1e2e58bb --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/async_client.py @@ -0,0 +1,1109 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.discoveryengine_v1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.discoveryengine_v1.services.document_service import pagers +from google.cloud.discoveryengine_v1.types import document +from google.cloud.discoveryengine_v1.types import document as gcd_document +from google.cloud.discoveryengine_v1.types import document_service +from google.cloud.discoveryengine_v1.types import import_config +from google.cloud.discoveryengine_v1.types import purge_config +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from .transports.base import DocumentServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import DocumentServiceGrpcAsyncIOTransport +from .client import DocumentServiceClient + + +class DocumentServiceAsyncClient: + """Service for ingesting + [Document][google.cloud.discoveryengine.v1.Document] information of + the customer's website. + """ + + _client: DocumentServiceClient + + DEFAULT_ENDPOINT = DocumentServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = DocumentServiceClient.DEFAULT_MTLS_ENDPOINT + + branch_path = staticmethod(DocumentServiceClient.branch_path) + parse_branch_path = staticmethod(DocumentServiceClient.parse_branch_path) + document_path = staticmethod(DocumentServiceClient.document_path) + parse_document_path = staticmethod(DocumentServiceClient.parse_document_path) + common_billing_account_path = staticmethod(DocumentServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(DocumentServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(DocumentServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(DocumentServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(DocumentServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(DocumentServiceClient.parse_common_organization_path) + common_project_path = staticmethod(DocumentServiceClient.common_project_path) + parse_common_project_path = staticmethod(DocumentServiceClient.parse_common_project_path) + common_location_path = staticmethod(DocumentServiceClient.common_location_path) + parse_common_location_path = staticmethod(DocumentServiceClient.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: + DocumentServiceAsyncClient: The constructed client. + """ + return DocumentServiceClient.from_service_account_info.__func__(DocumentServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DocumentServiceAsyncClient: The constructed client. + """ + return DocumentServiceClient.from_service_account_file.__func__(DocumentServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return DocumentServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> DocumentServiceTransport: + """Returns the transport used by the client instance. + + Returns: + DocumentServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(DocumentServiceClient).get_transport_class, type(DocumentServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, DocumentServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the document 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 (Union[str, ~.DocumentServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = DocumentServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def get_document(self, + request: Optional[Union[document_service.GetDocumentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> document.Document: + r"""Gets a [Document][google.cloud.discoveryengine.v1.Document]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + async def sample_get_document(): + # Create a client + client = discoveryengine_v1.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.GetDocumentRequest( + name="name_value", + ) + + # Make the request + response = await client.get_document(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1.types.GetDocumentRequest, dict]]): + The request object. Request message for + [DocumentService.GetDocument][google.cloud.discoveryengine.v1.DocumentService.GetDocument] + method. + name (:class:`str`): + Required. Full resource name of + [Document][google.cloud.discoveryengine.v1.Document], + such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. + + If the caller does not have permission to access the + [Document][google.cloud.discoveryengine.v1.Document], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the requested + [Document][google.cloud.discoveryengine.v1.Document] + does not exist, a ``NOT_FOUND`` error is returned. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1.types.Document: + Document captures all raw metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = document_service.GetDocumentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_document, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_documents(self, + request: Optional[Union[document_service.ListDocumentsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDocumentsAsyncPager: + r"""Gets a list of + [Document][google.cloud.discoveryengine.v1.Document]s. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + async def sample_list_documents(): + # Create a client + client = discoveryengine_v1.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.ListDocumentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_documents(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1.types.ListDocumentsRequest, dict]]): + The request object. Request message for + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1.DocumentService.ListDocuments] + method. + parent (:class:`str`): + Required. The parent branch resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. + Use ``default_branch`` as the branch ID, to list + documents under the default branch. + + If the caller does not have permission to list + [Document][google.cloud.discoveryengine.v1.Document]s + under this branch, regardless of whether or not this + branch exists, a ``PERMISSION_DENIED`` error is + returned. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1.services.document_service.pagers.ListDocumentsAsyncPager: + Response message for + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1.DocumentService.ListDocuments] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = document_service.ListDocumentsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_documents, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListDocumentsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_document(self, + request: Optional[Union[document_service.CreateDocumentRequest, dict]] = None, + *, + parent: Optional[str] = None, + document: Optional[gcd_document.Document] = None, + document_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_document.Document: + r"""Creates a [Document][google.cloud.discoveryengine.v1.Document]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + async def sample_create_document(): + # Create a client + client = discoveryengine_v1.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.CreateDocumentRequest( + parent="parent_value", + document_id="document_id_value", + ) + + # Make the request + response = await client.create_document(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1.types.CreateDocumentRequest, dict]]): + The request object. Request message for + [DocumentService.CreateDocument][google.cloud.discoveryengine.v1.DocumentService.CreateDocument] + method. + parent (:class:`str`): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + document (:class:`google.cloud.discoveryengine_v1.types.Document`): + Required. The + [Document][google.cloud.discoveryengine.v1.Document] to + create. + + This corresponds to the ``document`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + document_id (:class:`str`): + Required. The ID to use for the + [Document][google.cloud.discoveryengine.v1.Document], + which will become the final component of the + [Document.name][google.cloud.discoveryengine.v1.Document.name]. + + If the caller does not have permission to create the + [Document][google.cloud.discoveryengine.v1.Document], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + This field must be unique among all + [Document][google.cloud.discoveryengine.v1.Document]s + with the same + [parent][google.cloud.discoveryengine.v1.CreateDocumentRequest.parent]. + Otherwise, an ``ALREADY_EXISTS`` error is returned. + + This field must conform to + `RFC-1034 `__ + standard with a length limit of 63 characters. + Otherwise, an ``INVALID_ARGUMENT`` error is returned. + + This corresponds to the ``document_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1.types.Document: + Document captures all raw metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, document, document_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = document_service.CreateDocumentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if document is not None: + request.document = document + if document_id is not None: + request.document_id = document_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_document, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_document(self, + request: Optional[Union[document_service.UpdateDocumentRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> document.Document: + r"""Updates a [Document][google.cloud.discoveryengine.v1.Document]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + async def sample_update_document(): + # Create a client + client = discoveryengine_v1.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.UpdateDocumentRequest( + ) + + # Make the request + response = await client.update_document(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1.types.UpdateDocumentRequest, dict]]): + The request object. Request message for + [DocumentService.UpdateDocument][google.cloud.discoveryengine.v1.DocumentService.UpdateDocument] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1.types.Document: + Document captures all raw metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + request = document_service.UpdateDocumentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_document, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("document.name", request.document.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_document(self, + request: Optional[Union[document_service.DeleteDocumentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a [Document][google.cloud.discoveryengine.v1.Document]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + async def sample_delete_document(): + # Create a client + client = discoveryengine_v1.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.DeleteDocumentRequest( + name="name_value", + ) + + # Make the request + await client.delete_document(request=request) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1.types.DeleteDocumentRequest, dict]]): + The request object. Request message for + [DocumentService.DeleteDocument][google.cloud.discoveryengine.v1.DocumentService.DeleteDocument] + method. + name (:class:`str`): + Required. Full resource name of + [Document][google.cloud.discoveryengine.v1.Document], + such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. + + If the caller does not have permission to delete the + [Document][google.cloud.discoveryengine.v1.Document], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [Document][google.cloud.discoveryengine.v1.Document] to + delete does not exist, a ``NOT_FOUND`` error is + returned. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = document_service.DeleteDocumentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_document, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def import_documents(self, + request: Optional[Union[import_config.ImportDocumentsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of multiple + [Document][google.cloud.discoveryengine.v1.Document]s. Request + processing may be synchronous. Non-existing items will be + created. + + Note: It is possible for a subset of the + [Document][google.cloud.discoveryengine.v1.Document]s to be + successfully updated. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + async def sample_import_documents(): + # Create a client + client = discoveryengine_v1.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.ImportDocumentsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.import_documents(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1.types.ImportDocumentsRequest, dict]]): + The request object. Request message for Import methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1.types.ImportDocumentsResponse` Response of the + [ImportDocumentsRequest][google.cloud.discoveryengine.v1.ImportDocumentsRequest]. + If the long running operation is done, then this + message is returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + request = import_config.ImportDocumentsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_documents, + default_retry=retries.Retry( +initial=1.0,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_config.ImportDocumentsResponse, + metadata_type=import_config.ImportDocumentsMetadata, + ) + + # Done; return the response. + return response + + async def purge_documents(self, + request: Optional[Union[purge_config.PurgeDocumentsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Permanently deletes all selected + [Document][google.cloud.discoveryengine.v1.Document]s in a + branch. + + This process is asynchronous. Depending on the number of + [Document][google.cloud.discoveryengine.v1.Document]s to be + deleted, this operation can take hours to complete. Before the + delete operation completes, some + [Document][google.cloud.discoveryengine.v1.Document]s might + still be returned by + [DocumentService.GetDocument][google.cloud.discoveryengine.v1.DocumentService.GetDocument] + or + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1.DocumentService.ListDocuments]. + + To get a list of the + [Document][google.cloud.discoveryengine.v1.Document]s to be + deleted, set + [PurgeDocumentsRequest.force][google.cloud.discoveryengine.v1.PurgeDocumentsRequest.force] + to false. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + async def sample_purge_documents(): + # Create a client + client = discoveryengine_v1.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.PurgeDocumentsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_documents(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1.types.PurgeDocumentsRequest, dict]]): + The request object. Request message for + [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1.DocumentService.PurgeDocuments] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1.types.PurgeDocumentsResponse` Response message for + [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1.DocumentService.PurgeDocuments] + method. If the long running operation is successfully + done, then this message is returned by the + google.longrunning.Operations.response field. + + """ + # Create or coerce a protobuf request object. + request = purge_config.PurgeDocumentsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.purge_documents, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + purge_config.PurgeDocumentsResponse, + metadata_type=purge_config.PurgeDocumentsMetadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "DocumentServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "DocumentServiceAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/client.py new file mode 100644 index 000000000000..7cd733b747e9 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/client.py @@ -0,0 +1,1322 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.discoveryengine_v1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.discoveryengine_v1.services.document_service import pagers +from google.cloud.discoveryengine_v1.types import document +from google.cloud.discoveryengine_v1.types import document as gcd_document +from google.cloud.discoveryengine_v1.types import document_service +from google.cloud.discoveryengine_v1.types import import_config +from google.cloud.discoveryengine_v1.types import purge_config +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from .transports.base import DocumentServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import DocumentServiceGrpcTransport +from .transports.grpc_asyncio import DocumentServiceGrpcAsyncIOTransport +from .transports.rest import DocumentServiceRestTransport + + +class DocumentServiceClientMeta(type): + """Metaclass for the DocumentService 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[DocumentServiceTransport]] + _transport_registry["grpc"] = DocumentServiceGrpcTransport + _transport_registry["grpc_asyncio"] = DocumentServiceGrpcAsyncIOTransport + _transport_registry["rest"] = DocumentServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[DocumentServiceTransport]: + """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 DocumentServiceClient(metaclass=DocumentServiceClientMeta): + """Service for ingesting + [Document][google.cloud.discoveryengine.v1.Document] information of + the customer's website. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DocumentServiceClient: 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: + DocumentServiceClient: 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) -> DocumentServiceTransport: + """Returns the transport used by the client instance. + + Returns: + DocumentServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def branch_path(project: str,location: str,data_store: str,branch: str,) -> str: + """Returns a fully-qualified branch string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}".format(project=project, location=location, data_store=data_store, branch=branch, ) + + @staticmethod + def parse_branch_path(path: str) -> Dict[str,str]: + """Parses a branch path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def document_path(project: str,location: str,data_store: str,branch: str,document: str,) -> str: + """Returns a fully-qualified document string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) + + @staticmethod + def parse_document_path(path: str) -> Dict[str,str]: + """Parses a document path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)/documents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, DocumentServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the document 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 (Union[str, DocumentServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, DocumentServiceTransport): + # transport is a DocumentServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def get_document(self, + request: Optional[Union[document_service.GetDocumentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> document.Document: + r"""Gets a [Document][google.cloud.discoveryengine.v1.Document]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + def sample_get_document(): + # Create a client + client = discoveryengine_v1.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.GetDocumentRequest( + name="name_value", + ) + + # Make the request + response = client.get_document(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1.types.GetDocumentRequest, dict]): + The request object. Request message for + [DocumentService.GetDocument][google.cloud.discoveryengine.v1.DocumentService.GetDocument] + method. + name (str): + Required. Full resource name of + [Document][google.cloud.discoveryengine.v1.Document], + such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. + + If the caller does not have permission to access the + [Document][google.cloud.discoveryengine.v1.Document], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the requested + [Document][google.cloud.discoveryengine.v1.Document] + does not exist, a ``NOT_FOUND`` error is returned. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1.types.Document: + Document captures all raw metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a document_service.GetDocumentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, document_service.GetDocumentRequest): + request = document_service.GetDocumentRequest(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_document] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_documents(self, + request: Optional[Union[document_service.ListDocumentsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDocumentsPager: + r"""Gets a list of + [Document][google.cloud.discoveryengine.v1.Document]s. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + def sample_list_documents(): + # Create a client + client = discoveryengine_v1.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.ListDocumentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_documents(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1.types.ListDocumentsRequest, dict]): + The request object. Request message for + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1.DocumentService.ListDocuments] + method. + parent (str): + Required. The parent branch resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. + Use ``default_branch`` as the branch ID, to list + documents under the default branch. + + If the caller does not have permission to list + [Document][google.cloud.discoveryengine.v1.Document]s + under this branch, regardless of whether or not this + branch exists, a ``PERMISSION_DENIED`` error is + returned. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1.services.document_service.pagers.ListDocumentsPager: + Response message for + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1.DocumentService.ListDocuments] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a document_service.ListDocumentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, document_service.ListDocumentsRequest): + request = document_service.ListDocumentsRequest(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_documents] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListDocumentsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_document(self, + request: Optional[Union[document_service.CreateDocumentRequest, dict]] = None, + *, + parent: Optional[str] = None, + document: Optional[gcd_document.Document] = None, + document_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_document.Document: + r"""Creates a [Document][google.cloud.discoveryengine.v1.Document]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + def sample_create_document(): + # Create a client + client = discoveryengine_v1.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.CreateDocumentRequest( + parent="parent_value", + document_id="document_id_value", + ) + + # Make the request + response = client.create_document(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1.types.CreateDocumentRequest, dict]): + The request object. Request message for + [DocumentService.CreateDocument][google.cloud.discoveryengine.v1.DocumentService.CreateDocument] + method. + parent (str): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + document (google.cloud.discoveryengine_v1.types.Document): + Required. The + [Document][google.cloud.discoveryengine.v1.Document] to + create. + + This corresponds to the ``document`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + document_id (str): + Required. The ID to use for the + [Document][google.cloud.discoveryengine.v1.Document], + which will become the final component of the + [Document.name][google.cloud.discoveryengine.v1.Document.name]. + + If the caller does not have permission to create the + [Document][google.cloud.discoveryengine.v1.Document], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + This field must be unique among all + [Document][google.cloud.discoveryengine.v1.Document]s + with the same + [parent][google.cloud.discoveryengine.v1.CreateDocumentRequest.parent]. + Otherwise, an ``ALREADY_EXISTS`` error is returned. + + This field must conform to + `RFC-1034 `__ + standard with a length limit of 63 characters. + Otherwise, an ``INVALID_ARGUMENT`` error is returned. + + This corresponds to the ``document_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1.types.Document: + Document captures all raw metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, document, document_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a document_service.CreateDocumentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, document_service.CreateDocumentRequest): + request = document_service.CreateDocumentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if document is not None: + request.document = document + if document_id is not None: + request.document_id = document_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_document] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_document(self, + request: Optional[Union[document_service.UpdateDocumentRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> document.Document: + r"""Updates a [Document][google.cloud.discoveryengine.v1.Document]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + def sample_update_document(): + # Create a client + client = discoveryengine_v1.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.UpdateDocumentRequest( + ) + + # Make the request + response = client.update_document(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1.types.UpdateDocumentRequest, dict]): + The request object. Request message for + [DocumentService.UpdateDocument][google.cloud.discoveryengine.v1.DocumentService.UpdateDocument] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1.types.Document: + Document captures all raw metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a document_service.UpdateDocumentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, document_service.UpdateDocumentRequest): + request = document_service.UpdateDocumentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_document] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("document.name", request.document.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_document(self, + request: Optional[Union[document_service.DeleteDocumentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a [Document][google.cloud.discoveryengine.v1.Document]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + def sample_delete_document(): + # Create a client + client = discoveryengine_v1.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.DeleteDocumentRequest( + name="name_value", + ) + + # Make the request + client.delete_document(request=request) + + Args: + request (Union[google.cloud.discoveryengine_v1.types.DeleteDocumentRequest, dict]): + The request object. Request message for + [DocumentService.DeleteDocument][google.cloud.discoveryengine.v1.DocumentService.DeleteDocument] + method. + name (str): + Required. Full resource name of + [Document][google.cloud.discoveryengine.v1.Document], + such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. + + If the caller does not have permission to delete the + [Document][google.cloud.discoveryengine.v1.Document], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [Document][google.cloud.discoveryengine.v1.Document] to + delete does not exist, a ``NOT_FOUND`` error is + returned. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a document_service.DeleteDocumentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, document_service.DeleteDocumentRequest): + request = document_service.DeleteDocumentRequest(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_document] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def import_documents(self, + request: Optional[Union[import_config.ImportDocumentsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Bulk import of multiple + [Document][google.cloud.discoveryengine.v1.Document]s. Request + processing may be synchronous. Non-existing items will be + created. + + Note: It is possible for a subset of the + [Document][google.cloud.discoveryengine.v1.Document]s to be + successfully updated. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + def sample_import_documents(): + # Create a client + client = discoveryengine_v1.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.ImportDocumentsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.import_documents(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1.types.ImportDocumentsRequest, dict]): + The request object. Request message for Import methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1.types.ImportDocumentsResponse` Response of the + [ImportDocumentsRequest][google.cloud.discoveryengine.v1.ImportDocumentsRequest]. + If the long running operation is done, then this + message is returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a import_config.ImportDocumentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, import_config.ImportDocumentsRequest): + request = import_config.ImportDocumentsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_documents] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_config.ImportDocumentsResponse, + metadata_type=import_config.ImportDocumentsMetadata, + ) + + # Done; return the response. + return response + + def purge_documents(self, + request: Optional[Union[purge_config.PurgeDocumentsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Permanently deletes all selected + [Document][google.cloud.discoveryengine.v1.Document]s in a + branch. + + This process is asynchronous. Depending on the number of + [Document][google.cloud.discoveryengine.v1.Document]s to be + deleted, this operation can take hours to complete. Before the + delete operation completes, some + [Document][google.cloud.discoveryengine.v1.Document]s might + still be returned by + [DocumentService.GetDocument][google.cloud.discoveryengine.v1.DocumentService.GetDocument] + or + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1.DocumentService.ListDocuments]. + + To get a list of the + [Document][google.cloud.discoveryengine.v1.Document]s to be + deleted, set + [PurgeDocumentsRequest.force][google.cloud.discoveryengine.v1.PurgeDocumentsRequest.force] + to false. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + def sample_purge_documents(): + # Create a client + client = discoveryengine_v1.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.PurgeDocumentsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_documents(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1.types.PurgeDocumentsRequest, dict]): + The request object. Request message for + [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1.DocumentService.PurgeDocuments] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1.types.PurgeDocumentsResponse` Response message for + [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1.DocumentService.PurgeDocuments] + method. If the long running operation is successfully + done, then this message is returned by the + google.longrunning.Operations.response field. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a purge_config.PurgeDocumentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, purge_config.PurgeDocumentsRequest): + request = purge_config.PurgeDocumentsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.purge_documents] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + purge_config.PurgeDocumentsResponse, + metadata_type=purge_config.PurgeDocumentsMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "DocumentServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "DocumentServiceClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/pagers.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/pagers.py new file mode 100644 index 000000000000..30cfb52563dc --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.discoveryengine_v1.types import document +from google.cloud.discoveryengine_v1.types import document_service + + +class ListDocumentsPager: + """A pager for iterating through ``list_documents`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1.types.ListDocumentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``documents`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDocuments`` requests and continue to iterate + through the ``documents`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1.types.ListDocumentsResponse` + 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[..., document_service.ListDocumentsResponse], + request: document_service.ListDocumentsRequest, + response: document_service.ListDocumentsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.discoveryengine_v1.types.ListDocumentsRequest): + The initial request object. + response (google.cloud.discoveryengine_v1.types.ListDocumentsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = document_service.ListDocumentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[document_service.ListDocumentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[document.Document]: + for page in self.pages: + yield from page.documents + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDocumentsAsyncPager: + """A pager for iterating through ``list_documents`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1.types.ListDocumentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``documents`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDocuments`` requests and continue to iterate + through the ``documents`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1.types.ListDocumentsResponse` + 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[document_service.ListDocumentsResponse]], + request: document_service.ListDocumentsRequest, + response: document_service.ListDocumentsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.discoveryengine_v1.types.ListDocumentsRequest): + The initial request object. + response (google.cloud.discoveryengine_v1.types.ListDocumentsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = document_service.ListDocumentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[document_service.ListDocumentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[document.Document]: + async def async_generator(): + async for page in self.pages: + for response in page.documents: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/__init__.py new file mode 100644 index 000000000000..fb08db02f32c --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import DocumentServiceTransport +from .grpc import DocumentServiceGrpcTransport +from .grpc_asyncio import DocumentServiceGrpcAsyncIOTransport +from .rest import DocumentServiceRestTransport +from .rest import DocumentServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[DocumentServiceTransport]] +_transport_registry['grpc'] = DocumentServiceGrpcTransport +_transport_registry['grpc_asyncio'] = DocumentServiceGrpcAsyncIOTransport +_transport_registry['rest'] = DocumentServiceRestTransport + +__all__ = ( + 'DocumentServiceTransport', + 'DocumentServiceGrpcTransport', + 'DocumentServiceGrpcAsyncIOTransport', + 'DocumentServiceRestTransport', + 'DocumentServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/base.py new file mode 100644 index 000000000000..b76cf87be59b --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/base.py @@ -0,0 +1,269 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.discoveryengine_v1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.discoveryengine_v1.types import document +from google.cloud.discoveryengine_v1.types import document as gcd_document +from google.cloud.discoveryengine_v1.types import document_service +from google.cloud.discoveryengine_v1.types import import_config +from google.cloud.discoveryengine_v1.types import purge_config +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class DocumentServiceTransport(abc.ABC): + """Abstract transport class for DocumentService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'discoveryengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_document: gapic_v1.method.wrap_method( + self.get_document, + default_timeout=None, + client_info=client_info, + ), + self.list_documents: gapic_v1.method.wrap_method( + self.list_documents, + default_timeout=None, + client_info=client_info, + ), + self.create_document: gapic_v1.method.wrap_method( + self.create_document, + default_timeout=None, + client_info=client_info, + ), + self.update_document: gapic_v1.method.wrap_method( + self.update_document, + default_timeout=None, + client_info=client_info, + ), + self.delete_document: gapic_v1.method.wrap_method( + self.delete_document, + default_timeout=None, + client_info=client_info, + ), + self.import_documents: gapic_v1.method.wrap_method( + self.import_documents, + default_retry=retries.Retry( +initial=1.0,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.0, + client_info=client_info, + ), + self.purge_documents: gapic_v1.method.wrap_method( + self.purge_documents, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def get_document(self) -> Callable[ + [document_service.GetDocumentRequest], + Union[ + document.Document, + Awaitable[document.Document] + ]]: + raise NotImplementedError() + + @property + def list_documents(self) -> Callable[ + [document_service.ListDocumentsRequest], + Union[ + document_service.ListDocumentsResponse, + Awaitable[document_service.ListDocumentsResponse] + ]]: + raise NotImplementedError() + + @property + def create_document(self) -> Callable[ + [document_service.CreateDocumentRequest], + Union[ + gcd_document.Document, + Awaitable[gcd_document.Document] + ]]: + raise NotImplementedError() + + @property + def update_document(self) -> Callable[ + [document_service.UpdateDocumentRequest], + Union[ + document.Document, + Awaitable[document.Document] + ]]: + raise NotImplementedError() + + @property + def delete_document(self) -> Callable[ + [document_service.DeleteDocumentRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def import_documents(self) -> Callable[ + [import_config.ImportDocumentsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def purge_documents(self) -> Callable[ + [purge_config.PurgeDocumentsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'DocumentServiceTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/grpc.py new file mode 100644 index 000000000000..663a4cea7b26 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/grpc.py @@ -0,0 +1,509 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.discoveryengine_v1.types import document +from google.cloud.discoveryengine_v1.types import document as gcd_document +from google.cloud.discoveryengine_v1.types import document_service +from google.cloud.discoveryengine_v1.types import import_config +from google.cloud.discoveryengine_v1.types import purge_config +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import DocumentServiceTransport, DEFAULT_CLIENT_INFO + + +class DocumentServiceGrpcTransport(DocumentServiceTransport): + """gRPC backend transport for DocumentService. + + Service for ingesting + [Document][google.cloud.discoveryengine.v1.Document] information of + the customer's website. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def get_document(self) -> Callable[ + [document_service.GetDocumentRequest], + document.Document]: + r"""Return a callable for the get document method over gRPC. + + Gets a [Document][google.cloud.discoveryengine.v1.Document]. + + Returns: + Callable[[~.GetDocumentRequest], + ~.Document]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_document' not in self._stubs: + self._stubs['get_document'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.DocumentService/GetDocument', + request_serializer=document_service.GetDocumentRequest.serialize, + response_deserializer=document.Document.deserialize, + ) + return self._stubs['get_document'] + + @property + def list_documents(self) -> Callable[ + [document_service.ListDocumentsRequest], + document_service.ListDocumentsResponse]: + r"""Return a callable for the list documents method over gRPC. + + Gets a list of + [Document][google.cloud.discoveryengine.v1.Document]s. + + Returns: + Callable[[~.ListDocumentsRequest], + ~.ListDocumentsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_documents' not in self._stubs: + self._stubs['list_documents'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.DocumentService/ListDocuments', + request_serializer=document_service.ListDocumentsRequest.serialize, + response_deserializer=document_service.ListDocumentsResponse.deserialize, + ) + return self._stubs['list_documents'] + + @property + def create_document(self) -> Callable[ + [document_service.CreateDocumentRequest], + gcd_document.Document]: + r"""Return a callable for the create document method over gRPC. + + Creates a [Document][google.cloud.discoveryengine.v1.Document]. + + Returns: + Callable[[~.CreateDocumentRequest], + ~.Document]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_document' not in self._stubs: + self._stubs['create_document'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.DocumentService/CreateDocument', + request_serializer=document_service.CreateDocumentRequest.serialize, + response_deserializer=gcd_document.Document.deserialize, + ) + return self._stubs['create_document'] + + @property + def update_document(self) -> Callable[ + [document_service.UpdateDocumentRequest], + document.Document]: + r"""Return a callable for the update document method over gRPC. + + Updates a [Document][google.cloud.discoveryengine.v1.Document]. + + Returns: + Callable[[~.UpdateDocumentRequest], + ~.Document]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_document' not in self._stubs: + self._stubs['update_document'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.DocumentService/UpdateDocument', + request_serializer=document_service.UpdateDocumentRequest.serialize, + response_deserializer=document.Document.deserialize, + ) + return self._stubs['update_document'] + + @property + def delete_document(self) -> Callable[ + [document_service.DeleteDocumentRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete document method over gRPC. + + Deletes a [Document][google.cloud.discoveryengine.v1.Document]. + + Returns: + Callable[[~.DeleteDocumentRequest], + ~.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_document' not in self._stubs: + self._stubs['delete_document'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.DocumentService/DeleteDocument', + request_serializer=document_service.DeleteDocumentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_document'] + + @property + def import_documents(self) -> Callable[ + [import_config.ImportDocumentsRequest], + operations_pb2.Operation]: + r"""Return a callable for the import documents method over gRPC. + + Bulk import of multiple + [Document][google.cloud.discoveryengine.v1.Document]s. Request + processing may be synchronous. Non-existing items will be + created. + + Note: It is possible for a subset of the + [Document][google.cloud.discoveryengine.v1.Document]s to be + successfully updated. + + Returns: + Callable[[~.ImportDocumentsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_documents' not in self._stubs: + self._stubs['import_documents'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.DocumentService/ImportDocuments', + request_serializer=import_config.ImportDocumentsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_documents'] + + @property + def purge_documents(self) -> Callable[ + [purge_config.PurgeDocumentsRequest], + operations_pb2.Operation]: + r"""Return a callable for the purge documents method over gRPC. + + Permanently deletes all selected + [Document][google.cloud.discoveryengine.v1.Document]s in a + branch. + + This process is asynchronous. Depending on the number of + [Document][google.cloud.discoveryengine.v1.Document]s to be + deleted, this operation can take hours to complete. Before the + delete operation completes, some + [Document][google.cloud.discoveryengine.v1.Document]s might + still be returned by + [DocumentService.GetDocument][google.cloud.discoveryengine.v1.DocumentService.GetDocument] + or + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1.DocumentService.ListDocuments]. + + To get a list of the + [Document][google.cloud.discoveryengine.v1.Document]s to be + deleted, set + [PurgeDocumentsRequest.force][google.cloud.discoveryengine.v1.PurgeDocumentsRequest.force] + to false. + + Returns: + Callable[[~.PurgeDocumentsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'purge_documents' not in self._stubs: + self._stubs['purge_documents'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.DocumentService/PurgeDocuments', + request_serializer=purge_config.PurgeDocumentsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['purge_documents'] + + def close(self): + self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'DocumentServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..1b2e3e1c587d --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/grpc_asyncio.py @@ -0,0 +1,508 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.discoveryengine_v1.types import document +from google.cloud.discoveryengine_v1.types import document as gcd_document +from google.cloud.discoveryengine_v1.types import document_service +from google.cloud.discoveryengine_v1.types import import_config +from google.cloud.discoveryengine_v1.types import purge_config +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import DocumentServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import DocumentServiceGrpcTransport + + +class DocumentServiceGrpcAsyncIOTransport(DocumentServiceTransport): + """gRPC AsyncIO backend transport for DocumentService. + + Service for ingesting + [Document][google.cloud.discoveryengine.v1.Document] information of + the customer's website. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def get_document(self) -> Callable[ + [document_service.GetDocumentRequest], + Awaitable[document.Document]]: + r"""Return a callable for the get document method over gRPC. + + Gets a [Document][google.cloud.discoveryengine.v1.Document]. + + Returns: + Callable[[~.GetDocumentRequest], + Awaitable[~.Document]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_document' not in self._stubs: + self._stubs['get_document'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.DocumentService/GetDocument', + request_serializer=document_service.GetDocumentRequest.serialize, + response_deserializer=document.Document.deserialize, + ) + return self._stubs['get_document'] + + @property + def list_documents(self) -> Callable[ + [document_service.ListDocumentsRequest], + Awaitable[document_service.ListDocumentsResponse]]: + r"""Return a callable for the list documents method over gRPC. + + Gets a list of + [Document][google.cloud.discoveryengine.v1.Document]s. + + Returns: + Callable[[~.ListDocumentsRequest], + Awaitable[~.ListDocumentsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_documents' not in self._stubs: + self._stubs['list_documents'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.DocumentService/ListDocuments', + request_serializer=document_service.ListDocumentsRequest.serialize, + response_deserializer=document_service.ListDocumentsResponse.deserialize, + ) + return self._stubs['list_documents'] + + @property + def create_document(self) -> Callable[ + [document_service.CreateDocumentRequest], + Awaitable[gcd_document.Document]]: + r"""Return a callable for the create document method over gRPC. + + Creates a [Document][google.cloud.discoveryengine.v1.Document]. + + Returns: + Callable[[~.CreateDocumentRequest], + Awaitable[~.Document]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_document' not in self._stubs: + self._stubs['create_document'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.DocumentService/CreateDocument', + request_serializer=document_service.CreateDocumentRequest.serialize, + response_deserializer=gcd_document.Document.deserialize, + ) + return self._stubs['create_document'] + + @property + def update_document(self) -> Callable[ + [document_service.UpdateDocumentRequest], + Awaitable[document.Document]]: + r"""Return a callable for the update document method over gRPC. + + Updates a [Document][google.cloud.discoveryengine.v1.Document]. + + Returns: + Callable[[~.UpdateDocumentRequest], + Awaitable[~.Document]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_document' not in self._stubs: + self._stubs['update_document'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.DocumentService/UpdateDocument', + request_serializer=document_service.UpdateDocumentRequest.serialize, + response_deserializer=document.Document.deserialize, + ) + return self._stubs['update_document'] + + @property + def delete_document(self) -> Callable[ + [document_service.DeleteDocumentRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete document method over gRPC. + + Deletes a [Document][google.cloud.discoveryengine.v1.Document]. + + Returns: + Callable[[~.DeleteDocumentRequest], + 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_document' not in self._stubs: + self._stubs['delete_document'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.DocumentService/DeleteDocument', + request_serializer=document_service.DeleteDocumentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_document'] + + @property + def import_documents(self) -> Callable[ + [import_config.ImportDocumentsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import documents method over gRPC. + + Bulk import of multiple + [Document][google.cloud.discoveryengine.v1.Document]s. Request + processing may be synchronous. Non-existing items will be + created. + + Note: It is possible for a subset of the + [Document][google.cloud.discoveryengine.v1.Document]s to be + successfully updated. + + Returns: + Callable[[~.ImportDocumentsRequest], + 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 'import_documents' not in self._stubs: + self._stubs['import_documents'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.DocumentService/ImportDocuments', + request_serializer=import_config.ImportDocumentsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_documents'] + + @property + def purge_documents(self) -> Callable[ + [purge_config.PurgeDocumentsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the purge documents method over gRPC. + + Permanently deletes all selected + [Document][google.cloud.discoveryengine.v1.Document]s in a + branch. + + This process is asynchronous. Depending on the number of + [Document][google.cloud.discoveryengine.v1.Document]s to be + deleted, this operation can take hours to complete. Before the + delete operation completes, some + [Document][google.cloud.discoveryengine.v1.Document]s might + still be returned by + [DocumentService.GetDocument][google.cloud.discoveryengine.v1.DocumentService.GetDocument] + or + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1.DocumentService.ListDocuments]. + + To get a list of the + [Document][google.cloud.discoveryengine.v1.Document]s to be + deleted, set + [PurgeDocumentsRequest.force][google.cloud.discoveryengine.v1.PurgeDocumentsRequest.force] + to false. + + Returns: + Callable[[~.PurgeDocumentsRequest], + 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 'purge_documents' not in self._stubs: + self._stubs['purge_documents'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.DocumentService/PurgeDocuments', + request_serializer=purge_config.PurgeDocumentsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['purge_documents'] + + def close(self): + return self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ( + 'DocumentServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/rest.py new file mode 100644 index 000000000000..737f83b24002 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/rest.py @@ -0,0 +1,1445 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.cloud.location import locations_pb2 # type: ignore +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.discoveryengine_v1.types import document +from google.cloud.discoveryengine_v1.types import document as gcd_document +from google.cloud.discoveryengine_v1.types import document_service +from google.cloud.discoveryengine_v1.types import import_config +from google.cloud.discoveryengine_v1.types import purge_config +from google.protobuf import empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from .base import DocumentServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class DocumentServiceRestInterceptor: + """Interceptor for DocumentService. + + 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 DocumentServiceRestTransport. + + .. code-block:: python + class MyCustomDocumentServiceInterceptor(DocumentServiceRestInterceptor): + def pre_create_document(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_document(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_document(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_document(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_document(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_import_documents(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_import_documents(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_documents(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_documents(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_purge_documents(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_purge_documents(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_document(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_document(self, response): + logging.log(f"Received response: {response}") + return response + + transport = DocumentServiceRestTransport(interceptor=MyCustomDocumentServiceInterceptor()) + client = DocumentServiceClient(transport=transport) + + + """ + def pre_create_document(self, request: document_service.CreateDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_service.CreateDocumentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_document + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentService server. + """ + return request, metadata + + def post_create_document(self, response: gcd_document.Document) -> gcd_document.Document: + """Post-rpc interceptor for create_document + + Override in a subclass to manipulate the response + after it is returned by the DocumentService server but before + it is returned to user code. + """ + return response + def pre_delete_document(self, request: document_service.DeleteDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_service.DeleteDocumentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_document + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentService server. + """ + return request, metadata + + def pre_get_document(self, request: document_service.GetDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_service.GetDocumentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_document + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentService server. + """ + return request, metadata + + def post_get_document(self, response: document.Document) -> document.Document: + """Post-rpc interceptor for get_document + + Override in a subclass to manipulate the response + after it is returned by the DocumentService server but before + it is returned to user code. + """ + return response + def pre_import_documents(self, request: import_config.ImportDocumentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[import_config.ImportDocumentsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for import_documents + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentService server. + """ + return request, metadata + + def post_import_documents(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for import_documents + + Override in a subclass to manipulate the response + after it is returned by the DocumentService server but before + it is returned to user code. + """ + return response + def pre_list_documents(self, request: document_service.ListDocumentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_service.ListDocumentsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_documents + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentService server. + """ + return request, metadata + + def post_list_documents(self, response: document_service.ListDocumentsResponse) -> document_service.ListDocumentsResponse: + """Post-rpc interceptor for list_documents + + Override in a subclass to manipulate the response + after it is returned by the DocumentService server but before + it is returned to user code. + """ + return response + def pre_purge_documents(self, request: purge_config.PurgeDocumentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[purge_config.PurgeDocumentsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for purge_documents + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentService server. + """ + return request, metadata + + def post_purge_documents(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for purge_documents + + Override in a subclass to manipulate the response + after it is returned by the DocumentService server but before + it is returned to user code. + """ + return response + def pre_update_document(self, request: document_service.UpdateDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_service.UpdateDocumentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_document + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentService server. + """ + return request, metadata + + def post_update_document(self, response: document.Document) -> document.Document: + """Post-rpc interceptor for update_document + + Override in a subclass to manipulate the response + after it is returned by the DocumentService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentService 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 DocumentService server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentService 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 DocumentService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class DocumentServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: DocumentServiceRestInterceptor + + +class DocumentServiceRestTransport(DocumentServiceTransport): + """REST backend transport for DocumentService. + + Service for ingesting + [Document][google.cloud.discoveryengine.v1.Document] information of + the customer's website. + + 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 = 'discoveryengine.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[DocumentServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or DocumentServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/engines/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/models/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CreateDocument(DocumentServiceRestStub): + def __hash__(self): + return hash("CreateDocument") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "documentId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_service.CreateDocumentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcd_document.Document: + r"""Call the create document method over HTTP. + + Args: + request (~.document_service.CreateDocumentRequest): + The request object. Request message for + [DocumentService.CreateDocument][google.cloud.discoveryengine.v1.DocumentService.CreateDocument] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcd_document.Document: + Document captures all raw metadata + information of items to be recommended + or searched. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/dataStores/*/branches/*}/documents', + 'body': 'document', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/collections/*/dataStores/*/branches/*}/documents', + 'body': 'document', + }, + ] + request, metadata = self._interceptor.pre_create_document(request, metadata) + pb_request = document_service.CreateDocumentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcd_document.Document() + pb_resp = gcd_document.Document.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_document(resp) + return resp + + class _DeleteDocument(DocumentServiceRestStub): + def __hash__(self): + return hash("DeleteDocument") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_service.DeleteDocumentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete document method over HTTP. + + Args: + request (~.document_service.DeleteDocumentRequest): + The request object. Request message for + [DocumentService.DeleteDocument][google.cloud.discoveryengine.v1.DocumentService.DeleteDocument] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*/documents/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/documents/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_document(request, metadata) + pb_request = document_service.DeleteDocumentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _GetDocument(DocumentServiceRestStub): + def __hash__(self): + return hash("GetDocument") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_service.GetDocumentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> document.Document: + r"""Call the get document method over HTTP. + + Args: + request (~.document_service.GetDocumentRequest): + The request object. Request message for + [DocumentService.GetDocument][google.cloud.discoveryengine.v1.DocumentService.GetDocument] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.document.Document: + Document captures all raw metadata + information of items to be recommended + or searched. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*/documents/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/documents/*}', + }, + ] + request, metadata = self._interceptor.pre_get_document(request, metadata) + pb_request = document_service.GetDocumentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = document.Document() + pb_resp = document.Document.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_document(resp) + return resp + + class _ImportDocuments(DocumentServiceRestStub): + def __hash__(self): + return hash("ImportDocuments") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: import_config.ImportDocumentsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the import documents method over HTTP. + + Args: + request (~.import_config.ImportDocumentsRequest): + The request object. Request message for Import methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/dataStores/*/branches/*}/documents:import', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/collections/*/dataStores/*/branches/*}/documents:import', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_import_documents(request, metadata) + pb_request = import_config.ImportDocumentsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_import_documents(resp) + return resp + + class _ListDocuments(DocumentServiceRestStub): + def __hash__(self): + return hash("ListDocuments") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_service.ListDocumentsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> document_service.ListDocumentsResponse: + r"""Call the list documents method over HTTP. + + Args: + request (~.document_service.ListDocumentsRequest): + The request object. Request message for + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1.DocumentService.ListDocuments] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.document_service.ListDocumentsResponse: + Response message for + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1.DocumentService.ListDocuments] + method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/dataStores/*/branches/*}/documents', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/collections/*/dataStores/*/branches/*}/documents', + }, + ] + request, metadata = self._interceptor.pre_list_documents(request, metadata) + pb_request = document_service.ListDocumentsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = document_service.ListDocumentsResponse() + pb_resp = document_service.ListDocumentsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_documents(resp) + return resp + + class _PurgeDocuments(DocumentServiceRestStub): + def __hash__(self): + return hash("PurgeDocuments") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: purge_config.PurgeDocumentsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the purge documents method over HTTP. + + Args: + request (~.purge_config.PurgeDocumentsRequest): + The request object. Request message for + [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1.DocumentService.PurgeDocuments] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/dataStores/*/branches/*}/documents:purge', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/collections/*/dataStores/*/branches/*}/documents:purge', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_purge_documents(request, metadata) + pb_request = purge_config.PurgeDocumentsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_purge_documents(resp) + return resp + + class _UpdateDocument(DocumentServiceRestStub): + def __hash__(self): + return hash("UpdateDocument") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_service.UpdateDocumentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> document.Document: + r"""Call the update document method over HTTP. + + Args: + request (~.document_service.UpdateDocumentRequest): + The request object. Request message for + [DocumentService.UpdateDocument][google.cloud.discoveryengine.v1.DocumentService.UpdateDocument] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.document.Document: + Document captures all raw metadata + information of items to be recommended + or searched. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{document.name=projects/*/locations/*/dataStores/*/branches/*/documents/*}', + 'body': 'document', + }, +{ + 'method': 'patch', + 'uri': '/v1/{document.name=projects/*/locations/*/collections/*/dataStores/*/branches/*/documents/*}', + 'body': 'document', + }, + ] + request, metadata = self._interceptor.pre_update_document(request, metadata) + pb_request = document_service.UpdateDocumentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = document.Document() + pb_resp = document.Document.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_document(resp) + return resp + + @property + def create_document(self) -> Callable[ + [document_service.CreateDocumentRequest], + gcd_document.Document]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateDocument(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_document(self) -> Callable[ + [document_service.DeleteDocumentRequest], + 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._DeleteDocument(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_document(self) -> Callable[ + [document_service.GetDocumentRequest], + document.Document]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetDocument(self._session, self._host, self._interceptor) # type: ignore + + @property + def import_documents(self) -> Callable[ + [import_config.ImportDocumentsRequest], + 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._ImportDocuments(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_documents(self) -> Callable[ + [document_service.ListDocumentsRequest], + document_service.ListDocumentsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListDocuments(self._session, self._host, self._interceptor) # type: ignore + + @property + def purge_documents(self) -> Callable[ + [purge_config.PurgeDocumentsRequest], + 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._PurgeDocuments(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_document(self) -> Callable[ + [document_service.UpdateDocumentRequest], + document.Document]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateDocument(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(DocumentServiceRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(DocumentServiceRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/engines/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'DocumentServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/__init__.py new file mode 100644 index 000000000000..4e9455a921b6 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import SchemaServiceClient +from .async_client import SchemaServiceAsyncClient + +__all__ = ( + 'SchemaServiceClient', + 'SchemaServiceAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/async_client.py new file mode 100644 index 000000000000..f26e342d36dc --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/async_client.py @@ -0,0 +1,902 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.discoveryengine_v1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.discoveryengine_v1.services.schema_service import pagers +from google.cloud.discoveryengine_v1.types import schema +from google.cloud.discoveryengine_v1.types import schema as gcd_schema +from google.cloud.discoveryengine_v1.types import schema_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from .transports.base import SchemaServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SchemaServiceGrpcAsyncIOTransport +from .client import SchemaServiceClient + + +class SchemaServiceAsyncClient: + """Service for managing + [Schema][google.cloud.discoveryengine.v1.Schema]s. + """ + + _client: SchemaServiceClient + + DEFAULT_ENDPOINT = SchemaServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SchemaServiceClient.DEFAULT_MTLS_ENDPOINT + + data_store_path = staticmethod(SchemaServiceClient.data_store_path) + parse_data_store_path = staticmethod(SchemaServiceClient.parse_data_store_path) + schema_path = staticmethod(SchemaServiceClient.schema_path) + parse_schema_path = staticmethod(SchemaServiceClient.parse_schema_path) + common_billing_account_path = staticmethod(SchemaServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SchemaServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SchemaServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(SchemaServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(SchemaServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(SchemaServiceClient.parse_common_organization_path) + common_project_path = staticmethod(SchemaServiceClient.common_project_path) + parse_common_project_path = staticmethod(SchemaServiceClient.parse_common_project_path) + common_location_path = staticmethod(SchemaServiceClient.common_location_path) + parse_common_location_path = staticmethod(SchemaServiceClient.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: + SchemaServiceAsyncClient: The constructed client. + """ + return SchemaServiceClient.from_service_account_info.__func__(SchemaServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SchemaServiceAsyncClient: The constructed client. + """ + return SchemaServiceClient.from_service_account_file.__func__(SchemaServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return SchemaServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SchemaServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SchemaServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(SchemaServiceClient).get_transport_class, type(SchemaServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, SchemaServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the schema 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 (Union[str, ~.SchemaServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = SchemaServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def get_schema(self, + request: Optional[Union[schema_service.GetSchemaRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> schema.Schema: + r"""Gets a [Schema][google.cloud.discoveryengine.v1.Schema]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + async def sample_get_schema(): + # Create a client + client = discoveryengine_v1.SchemaServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.GetSchemaRequest( + name="name_value", + ) + + # Make the request + response = await client.get_schema(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1.types.GetSchemaRequest, dict]]): + The request object. Request message for + [SchemaService.GetSchema][google.cloud.discoveryengine.v1.SchemaService.GetSchema] + method. + name (:class:`str`): + Required. The full resource name of the schema, in the + format of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1.types.Schema: + Defines the structure and layout of a + type of document data. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = schema_service.GetSchemaRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_schema, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_schemas(self, + request: Optional[Union[schema_service.ListSchemasRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSchemasAsyncPager: + r"""Gets a list of + [Schema][google.cloud.discoveryengine.v1.Schema]s. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + async def sample_list_schemas(): + # Create a client + client = discoveryengine_v1.SchemaServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.ListSchemasRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_schemas(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1.types.ListSchemasRequest, dict]]): + The request object. Request message for + [SchemaService.ListSchemas][google.cloud.discoveryengine.v1.SchemaService.ListSchemas] + method. + parent (:class:`str`): + Required. The parent data store resource name, in the + format of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1.services.schema_service.pagers.ListSchemasAsyncPager: + Response message for + [SchemaService.ListSchemas][google.cloud.discoveryengine.v1.SchemaService.ListSchemas] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = schema_service.ListSchemasRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_schemas, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSchemasAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_schema(self, + request: Optional[Union[schema_service.CreateSchemaRequest, dict]] = None, + *, + parent: Optional[str] = None, + schema: Optional[gcd_schema.Schema] = None, + schema_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a [Schema][google.cloud.discoveryengine.v1.Schema]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + async def sample_create_schema(): + # Create a client + client = discoveryengine_v1.SchemaServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.CreateSchemaRequest( + parent="parent_value", + schema_id="schema_id_value", + ) + + # Make the request + operation = client.create_schema(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1.types.CreateSchemaRequest, dict]]): + The request object. Request message for + [SchemaService.CreateSchema][google.cloud.discoveryengine.v1.SchemaService.CreateSchema] + method. + parent (:class:`str`): + Required. The parent data store resource name, in the + format of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + schema (:class:`google.cloud.discoveryengine_v1.types.Schema`): + Required. The + [Schema][google.cloud.discoveryengine.v1.Schema] to + create. + + This corresponds to the ``schema`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + schema_id (:class:`str`): + Required. The ID to use for the + [Schema][google.cloud.discoveryengine.v1.Schema], which + will become the final component of the + [Schema.name][google.cloud.discoveryengine.v1.Schema.name]. + + This field should conform to + `RFC-1034 `__ + standard with a length limit of 63 characters. + + This corresponds to the ``schema_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.discoveryengine_v1.types.Schema` + Defines the structure and layout of a type of document + data. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, schema, schema_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = schema_service.CreateSchemaRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if schema is not None: + request.schema = schema + if schema_id is not None: + request.schema_id = schema_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_schema, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcd_schema.Schema, + metadata_type=schema_service.CreateSchemaMetadata, + ) + + # Done; return the response. + return response + + async def update_schema(self, + request: Optional[Union[schema_service.UpdateSchemaRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates a [Schema][google.cloud.discoveryengine.v1.Schema]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + async def sample_update_schema(): + # Create a client + client = discoveryengine_v1.SchemaServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.UpdateSchemaRequest( + ) + + # Make the request + operation = client.update_schema(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1.types.UpdateSchemaRequest, dict]]): + The request object. Request message for + [SchemaService.UpdateSchema][google.cloud.discoveryengine.v1.SchemaService.UpdateSchema] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.discoveryengine_v1.types.Schema` + Defines the structure and layout of a type of document + data. + + """ + # Create or coerce a protobuf request object. + request = schema_service.UpdateSchemaRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_schema, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("schema.name", request.schema.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + schema.Schema, + metadata_type=schema_service.UpdateSchemaMetadata, + ) + + # Done; return the response. + return response + + async def delete_schema(self, + request: Optional[Union[schema_service.DeleteSchemaRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a [Schema][google.cloud.discoveryengine.v1.Schema]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + async def sample_delete_schema(): + # Create a client + client = discoveryengine_v1.SchemaServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.DeleteSchemaRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_schema(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1.types.DeleteSchemaRequest, dict]]): + The request object. Request message for + [SchemaService.DeleteSchema][google.cloud.discoveryengine.v1.SchemaService.DeleteSchema] + method. + name (:class:`str`): + Required. The full resource name of the schema, in the + format of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = schema_service.DeleteSchemaRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_schema, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=schema_service.DeleteSchemaMetadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "SchemaServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "SchemaServiceAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/client.py new file mode 100644 index 000000000000..3a41eac1ffc0 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/client.py @@ -0,0 +1,1119 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.discoveryengine_v1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.discoveryengine_v1.services.schema_service import pagers +from google.cloud.discoveryengine_v1.types import schema +from google.cloud.discoveryengine_v1.types import schema as gcd_schema +from google.cloud.discoveryengine_v1.types import schema_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from .transports.base import SchemaServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SchemaServiceGrpcTransport +from .transports.grpc_asyncio import SchemaServiceGrpcAsyncIOTransport +from .transports.rest import SchemaServiceRestTransport + + +class SchemaServiceClientMeta(type): + """Metaclass for the SchemaService 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[SchemaServiceTransport]] + _transport_registry["grpc"] = SchemaServiceGrpcTransport + _transport_registry["grpc_asyncio"] = SchemaServiceGrpcAsyncIOTransport + _transport_registry["rest"] = SchemaServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[SchemaServiceTransport]: + """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 SchemaServiceClient(metaclass=SchemaServiceClientMeta): + """Service for managing + [Schema][google.cloud.discoveryengine.v1.Schema]s. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SchemaServiceClient: 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: + SchemaServiceClient: 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) -> SchemaServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SchemaServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def data_store_path(project: str,location: str,data_store: str,) -> str: + """Returns a fully-qualified data_store string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) + + @staticmethod + def parse_data_store_path(path: str) -> Dict[str,str]: + """Parses a data_store path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def schema_path(project: str,location: str,data_store: str,schema: str,) -> str: + """Returns a fully-qualified schema string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/schemas/{schema}".format(project=project, location=location, data_store=data_store, schema=schema, ) + + @staticmethod + def parse_schema_path(path: str) -> Dict[str,str]: + """Parses a schema path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/schemas/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, SchemaServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the schema 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 (Union[str, SchemaServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, SchemaServiceTransport): + # transport is a SchemaServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def get_schema(self, + request: Optional[Union[schema_service.GetSchemaRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> schema.Schema: + r"""Gets a [Schema][google.cloud.discoveryengine.v1.Schema]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + def sample_get_schema(): + # Create a client + client = discoveryengine_v1.SchemaServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.GetSchemaRequest( + name="name_value", + ) + + # Make the request + response = client.get_schema(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1.types.GetSchemaRequest, dict]): + The request object. Request message for + [SchemaService.GetSchema][google.cloud.discoveryengine.v1.SchemaService.GetSchema] + method. + name (str): + Required. The full resource name of the schema, in the + format of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1.types.Schema: + Defines the structure and layout of a + type of document data. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a schema_service.GetSchemaRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, schema_service.GetSchemaRequest): + request = schema_service.GetSchemaRequest(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_schema] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_schemas(self, + request: Optional[Union[schema_service.ListSchemasRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSchemasPager: + r"""Gets a list of + [Schema][google.cloud.discoveryengine.v1.Schema]s. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + def sample_list_schemas(): + # Create a client + client = discoveryengine_v1.SchemaServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.ListSchemasRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_schemas(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1.types.ListSchemasRequest, dict]): + The request object. Request message for + [SchemaService.ListSchemas][google.cloud.discoveryengine.v1.SchemaService.ListSchemas] + method. + parent (str): + Required. The parent data store resource name, in the + format of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1.services.schema_service.pagers.ListSchemasPager: + Response message for + [SchemaService.ListSchemas][google.cloud.discoveryengine.v1.SchemaService.ListSchemas] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a schema_service.ListSchemasRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, schema_service.ListSchemasRequest): + request = schema_service.ListSchemasRequest(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_schemas] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListSchemasPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_schema(self, + request: Optional[Union[schema_service.CreateSchemaRequest, dict]] = None, + *, + parent: Optional[str] = None, + schema: Optional[gcd_schema.Schema] = None, + schema_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a [Schema][google.cloud.discoveryengine.v1.Schema]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + def sample_create_schema(): + # Create a client + client = discoveryengine_v1.SchemaServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.CreateSchemaRequest( + parent="parent_value", + schema_id="schema_id_value", + ) + + # Make the request + operation = client.create_schema(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1.types.CreateSchemaRequest, dict]): + The request object. Request message for + [SchemaService.CreateSchema][google.cloud.discoveryengine.v1.SchemaService.CreateSchema] + method. + parent (str): + Required. The parent data store resource name, in the + format of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + schema (google.cloud.discoveryengine_v1.types.Schema): + Required. The + [Schema][google.cloud.discoveryengine.v1.Schema] to + create. + + This corresponds to the ``schema`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + schema_id (str): + Required. The ID to use for the + [Schema][google.cloud.discoveryengine.v1.Schema], which + will become the final component of the + [Schema.name][google.cloud.discoveryengine.v1.Schema.name]. + + This field should conform to + `RFC-1034 `__ + standard with a length limit of 63 characters. + + This corresponds to the ``schema_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.discoveryengine_v1.types.Schema` + Defines the structure and layout of a type of document + data. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, schema, schema_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a schema_service.CreateSchemaRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, schema_service.CreateSchemaRequest): + request = schema_service.CreateSchemaRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if schema is not None: + request.schema = schema + if schema_id is not None: + request.schema_id = schema_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_schema] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gcd_schema.Schema, + metadata_type=schema_service.CreateSchemaMetadata, + ) + + # Done; return the response. + return response + + def update_schema(self, + request: Optional[Union[schema_service.UpdateSchemaRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates a [Schema][google.cloud.discoveryengine.v1.Schema]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + def sample_update_schema(): + # Create a client + client = discoveryengine_v1.SchemaServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.UpdateSchemaRequest( + ) + + # Make the request + operation = client.update_schema(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1.types.UpdateSchemaRequest, dict]): + The request object. Request message for + [SchemaService.UpdateSchema][google.cloud.discoveryengine.v1.SchemaService.UpdateSchema] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.discoveryengine_v1.types.Schema` + Defines the structure and layout of a type of document + data. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a schema_service.UpdateSchemaRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, schema_service.UpdateSchemaRequest): + request = schema_service.UpdateSchemaRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_schema] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("schema.name", request.schema.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + schema.Schema, + metadata_type=schema_service.UpdateSchemaMetadata, + ) + + # Done; return the response. + return response + + def delete_schema(self, + request: Optional[Union[schema_service.DeleteSchemaRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a [Schema][google.cloud.discoveryengine.v1.Schema]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + def sample_delete_schema(): + # Create a client + client = discoveryengine_v1.SchemaServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.DeleteSchemaRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_schema(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1.types.DeleteSchemaRequest, dict]): + The request object. Request message for + [SchemaService.DeleteSchema][google.cloud.discoveryengine.v1.SchemaService.DeleteSchema] + method. + name (str): + Required. The full resource name of the schema, in the + format of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a schema_service.DeleteSchemaRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, schema_service.DeleteSchemaRequest): + request = schema_service.DeleteSchemaRequest(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_schema] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=schema_service.DeleteSchemaMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "SchemaServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "SchemaServiceClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/pagers.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/pagers.py new file mode 100644 index 000000000000..72fef28d4880 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.discoveryengine_v1.types import schema +from google.cloud.discoveryengine_v1.types import schema_service + + +class ListSchemasPager: + """A pager for iterating through ``list_schemas`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1.types.ListSchemasResponse` object, and + provides an ``__iter__`` method to iterate through its + ``schemas`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSchemas`` requests and continue to iterate + through the ``schemas`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1.types.ListSchemasResponse` + 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[..., schema_service.ListSchemasResponse], + request: schema_service.ListSchemasRequest, + response: schema_service.ListSchemasResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.discoveryengine_v1.types.ListSchemasRequest): + The initial request object. + response (google.cloud.discoveryengine_v1.types.ListSchemasResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = schema_service.ListSchemasRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[schema_service.ListSchemasResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[schema.Schema]: + for page in self.pages: + yield from page.schemas + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSchemasAsyncPager: + """A pager for iterating through ``list_schemas`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1.types.ListSchemasResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``schemas`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSchemas`` requests and continue to iterate + through the ``schemas`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1.types.ListSchemasResponse` + 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[schema_service.ListSchemasResponse]], + request: schema_service.ListSchemasRequest, + response: schema_service.ListSchemasResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.discoveryengine_v1.types.ListSchemasRequest): + The initial request object. + response (google.cloud.discoveryengine_v1.types.ListSchemasResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = schema_service.ListSchemasRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[schema_service.ListSchemasResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[schema.Schema]: + async def async_generator(): + async for page in self.pages: + for response in page.schemas: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/__init__.py new file mode 100644 index 000000000000..d5ebd14e657b --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import SchemaServiceTransport +from .grpc import SchemaServiceGrpcTransport +from .grpc_asyncio import SchemaServiceGrpcAsyncIOTransport +from .rest import SchemaServiceRestTransport +from .rest import SchemaServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SchemaServiceTransport]] +_transport_registry['grpc'] = SchemaServiceGrpcTransport +_transport_registry['grpc_asyncio'] = SchemaServiceGrpcAsyncIOTransport +_transport_registry['rest'] = SchemaServiceRestTransport + +__all__ = ( + 'SchemaServiceTransport', + 'SchemaServiceGrpcTransport', + 'SchemaServiceGrpcAsyncIOTransport', + 'SchemaServiceRestTransport', + 'SchemaServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/base.py new file mode 100644 index 000000000000..5a729d24911c --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/base.py @@ -0,0 +1,231 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.discoveryengine_v1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.discoveryengine_v1.types import schema +from google.cloud.discoveryengine_v1.types import schema_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class SchemaServiceTransport(abc.ABC): + """Abstract transport class for SchemaService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'discoveryengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_schema: gapic_v1.method.wrap_method( + self.get_schema, + default_timeout=None, + client_info=client_info, + ), + self.list_schemas: gapic_v1.method.wrap_method( + self.list_schemas, + default_timeout=None, + client_info=client_info, + ), + self.create_schema: gapic_v1.method.wrap_method( + self.create_schema, + default_timeout=None, + client_info=client_info, + ), + self.update_schema: gapic_v1.method.wrap_method( + self.update_schema, + default_timeout=None, + client_info=client_info, + ), + self.delete_schema: gapic_v1.method.wrap_method( + self.delete_schema, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def get_schema(self) -> Callable[ + [schema_service.GetSchemaRequest], + Union[ + schema.Schema, + Awaitable[schema.Schema] + ]]: + raise NotImplementedError() + + @property + def list_schemas(self) -> Callable[ + [schema_service.ListSchemasRequest], + Union[ + schema_service.ListSchemasResponse, + Awaitable[schema_service.ListSchemasResponse] + ]]: + raise NotImplementedError() + + @property + def create_schema(self) -> Callable[ + [schema_service.CreateSchemaRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_schema(self) -> Callable[ + [schema_service.UpdateSchemaRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_schema(self) -> Callable[ + [schema_service.DeleteSchemaRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'SchemaServiceTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/grpc.py new file mode 100644 index 000000000000..6eaf4f1a4fb4 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/grpc.py @@ -0,0 +1,427 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.discoveryengine_v1.types import schema +from google.cloud.discoveryengine_v1.types import schema_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import SchemaServiceTransport, DEFAULT_CLIENT_INFO + + +class SchemaServiceGrpcTransport(SchemaServiceTransport): + """gRPC backend transport for SchemaService. + + Service for managing + [Schema][google.cloud.discoveryengine.v1.Schema]s. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def get_schema(self) -> Callable[ + [schema_service.GetSchemaRequest], + schema.Schema]: + r"""Return a callable for the get schema method over gRPC. + + Gets a [Schema][google.cloud.discoveryengine.v1.Schema]. + + Returns: + Callable[[~.GetSchemaRequest], + ~.Schema]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_schema' not in self._stubs: + self._stubs['get_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.SchemaService/GetSchema', + request_serializer=schema_service.GetSchemaRequest.serialize, + response_deserializer=schema.Schema.deserialize, + ) + return self._stubs['get_schema'] + + @property + def list_schemas(self) -> Callable[ + [schema_service.ListSchemasRequest], + schema_service.ListSchemasResponse]: + r"""Return a callable for the list schemas method over gRPC. + + Gets a list of + [Schema][google.cloud.discoveryengine.v1.Schema]s. + + Returns: + Callable[[~.ListSchemasRequest], + ~.ListSchemasResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_schemas' not in self._stubs: + self._stubs['list_schemas'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.SchemaService/ListSchemas', + request_serializer=schema_service.ListSchemasRequest.serialize, + response_deserializer=schema_service.ListSchemasResponse.deserialize, + ) + return self._stubs['list_schemas'] + + @property + def create_schema(self) -> Callable[ + [schema_service.CreateSchemaRequest], + operations_pb2.Operation]: + r"""Return a callable for the create schema method over gRPC. + + Creates a [Schema][google.cloud.discoveryengine.v1.Schema]. + + Returns: + Callable[[~.CreateSchemaRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_schema' not in self._stubs: + self._stubs['create_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.SchemaService/CreateSchema', + request_serializer=schema_service.CreateSchemaRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_schema'] + + @property + def update_schema(self) -> Callable[ + [schema_service.UpdateSchemaRequest], + operations_pb2.Operation]: + r"""Return a callable for the update schema method over gRPC. + + Updates a [Schema][google.cloud.discoveryengine.v1.Schema]. + + Returns: + Callable[[~.UpdateSchemaRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_schema' not in self._stubs: + self._stubs['update_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.SchemaService/UpdateSchema', + request_serializer=schema_service.UpdateSchemaRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_schema'] + + @property + def delete_schema(self) -> Callable[ + [schema_service.DeleteSchemaRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete schema method over gRPC. + + Deletes a [Schema][google.cloud.discoveryengine.v1.Schema]. + + Returns: + Callable[[~.DeleteSchemaRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_schema' not in self._stubs: + self._stubs['delete_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.SchemaService/DeleteSchema', + request_serializer=schema_service.DeleteSchemaRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_schema'] + + def close(self): + self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'SchemaServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..3b81e8f16872 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/grpc_asyncio.py @@ -0,0 +1,426 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.discoveryengine_v1.types import schema +from google.cloud.discoveryengine_v1.types import schema_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import SchemaServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import SchemaServiceGrpcTransport + + +class SchemaServiceGrpcAsyncIOTransport(SchemaServiceTransport): + """gRPC AsyncIO backend transport for SchemaService. + + Service for managing + [Schema][google.cloud.discoveryengine.v1.Schema]s. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def get_schema(self) -> Callable[ + [schema_service.GetSchemaRequest], + Awaitable[schema.Schema]]: + r"""Return a callable for the get schema method over gRPC. + + Gets a [Schema][google.cloud.discoveryengine.v1.Schema]. + + Returns: + Callable[[~.GetSchemaRequest], + Awaitable[~.Schema]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_schema' not in self._stubs: + self._stubs['get_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.SchemaService/GetSchema', + request_serializer=schema_service.GetSchemaRequest.serialize, + response_deserializer=schema.Schema.deserialize, + ) + return self._stubs['get_schema'] + + @property + def list_schemas(self) -> Callable[ + [schema_service.ListSchemasRequest], + Awaitable[schema_service.ListSchemasResponse]]: + r"""Return a callable for the list schemas method over gRPC. + + Gets a list of + [Schema][google.cloud.discoveryengine.v1.Schema]s. + + Returns: + Callable[[~.ListSchemasRequest], + Awaitable[~.ListSchemasResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_schemas' not in self._stubs: + self._stubs['list_schemas'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.SchemaService/ListSchemas', + request_serializer=schema_service.ListSchemasRequest.serialize, + response_deserializer=schema_service.ListSchemasResponse.deserialize, + ) + return self._stubs['list_schemas'] + + @property + def create_schema(self) -> Callable[ + [schema_service.CreateSchemaRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create schema method over gRPC. + + Creates a [Schema][google.cloud.discoveryengine.v1.Schema]. + + Returns: + Callable[[~.CreateSchemaRequest], + 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_schema' not in self._stubs: + self._stubs['create_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.SchemaService/CreateSchema', + request_serializer=schema_service.CreateSchemaRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_schema'] + + @property + def update_schema(self) -> Callable[ + [schema_service.UpdateSchemaRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update schema method over gRPC. + + Updates a [Schema][google.cloud.discoveryengine.v1.Schema]. + + Returns: + Callable[[~.UpdateSchemaRequest], + 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_schema' not in self._stubs: + self._stubs['update_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.SchemaService/UpdateSchema', + request_serializer=schema_service.UpdateSchemaRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_schema'] + + @property + def delete_schema(self) -> Callable[ + [schema_service.DeleteSchemaRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete schema method over gRPC. + + Deletes a [Schema][google.cloud.discoveryengine.v1.Schema]. + + Returns: + Callable[[~.DeleteSchemaRequest], + 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_schema' not in self._stubs: + self._stubs['delete_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.SchemaService/DeleteSchema', + request_serializer=schema_service.DeleteSchemaRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_schema'] + + def close(self): + return self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ( + 'SchemaServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/rest.py new file mode 100644 index 000000000000..d5003908f820 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/rest.py @@ -0,0 +1,1208 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.cloud.location import locations_pb2 # type: ignore +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.discoveryengine_v1.types import schema +from google.cloud.discoveryengine_v1.types import schema_service +from google.longrunning import operations_pb2 # type: ignore + +from .base import SchemaServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class SchemaServiceRestInterceptor: + """Interceptor for SchemaService. + + 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 SchemaServiceRestTransport. + + .. code-block:: python + class MyCustomSchemaServiceInterceptor(SchemaServiceRestInterceptor): + def pre_create_schema(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_schema(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_schema(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_schema(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_schema(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_schema(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_schemas(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_schemas(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_schema(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_schema(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SchemaServiceRestTransport(interceptor=MyCustomSchemaServiceInterceptor()) + client = SchemaServiceClient(transport=transport) + + + """ + def pre_create_schema(self, request: schema_service.CreateSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[schema_service.CreateSchemaRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_schema + + Override in a subclass to manipulate the request or metadata + before they are sent to the SchemaService server. + """ + return request, metadata + + def post_create_schema(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_schema + + Override in a subclass to manipulate the response + after it is returned by the SchemaService server but before + it is returned to user code. + """ + return response + def pre_delete_schema(self, request: schema_service.DeleteSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[schema_service.DeleteSchemaRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_schema + + Override in a subclass to manipulate the request or metadata + before they are sent to the SchemaService server. + """ + return request, metadata + + def post_delete_schema(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_schema + + Override in a subclass to manipulate the response + after it is returned by the SchemaService server but before + it is returned to user code. + """ + return response + def pre_get_schema(self, request: schema_service.GetSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[schema_service.GetSchemaRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_schema + + Override in a subclass to manipulate the request or metadata + before they are sent to the SchemaService server. + """ + return request, metadata + + def post_get_schema(self, response: schema.Schema) -> schema.Schema: + """Post-rpc interceptor for get_schema + + Override in a subclass to manipulate the response + after it is returned by the SchemaService server but before + it is returned to user code. + """ + return response + def pre_list_schemas(self, request: schema_service.ListSchemasRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[schema_service.ListSchemasRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_schemas + + Override in a subclass to manipulate the request or metadata + before they are sent to the SchemaService server. + """ + return request, metadata + + def post_list_schemas(self, response: schema_service.ListSchemasResponse) -> schema_service.ListSchemasResponse: + """Post-rpc interceptor for list_schemas + + Override in a subclass to manipulate the response + after it is returned by the SchemaService server but before + it is returned to user code. + """ + return response + def pre_update_schema(self, request: schema_service.UpdateSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[schema_service.UpdateSchemaRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_schema + + Override in a subclass to manipulate the request or metadata + before they are sent to the SchemaService server. + """ + return request, metadata + + def post_update_schema(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_schema + + Override in a subclass to manipulate the response + after it is returned by the SchemaService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the SchemaService 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 SchemaService server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the SchemaService 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 SchemaService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class SchemaServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: SchemaServiceRestInterceptor + + +class SchemaServiceRestTransport(SchemaServiceTransport): + """REST backend transport for SchemaService. + + Service for managing + [Schema][google.cloud.discoveryengine.v1.Schema]s. + + 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 = 'discoveryengine.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[SchemaServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or SchemaServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/engines/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/models/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CreateSchema(SchemaServiceRestStub): + def __hash__(self): + return hash("CreateSchema") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "schemaId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: schema_service.CreateSchemaRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create schema method over HTTP. + + Args: + request (~.schema_service.CreateSchemaRequest): + The request object. Request message for + [SchemaService.CreateSchema][google.cloud.discoveryengine.v1.SchemaService.CreateSchema] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/dataStores/*}/schemas', + 'body': 'schema', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/collections/*/dataStores/*}/schemas', + 'body': 'schema', + }, + ] + request, metadata = self._interceptor.pre_create_schema(request, metadata) + pb_request = schema_service.CreateSchemaRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_schema(resp) + return resp + + class _DeleteSchema(SchemaServiceRestStub): + def __hash__(self): + return hash("DeleteSchema") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: schema_service.DeleteSchemaRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete schema method over HTTP. + + Args: + request (~.schema_service.DeleteSchemaRequest): + The request object. Request message for + [SchemaService.DeleteSchema][google.cloud.discoveryengine.v1.SchemaService.DeleteSchema] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/schemas/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_schema(request, metadata) + pb_request = schema_service.DeleteSchemaRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_schema(resp) + return resp + + class _GetSchema(SchemaServiceRestStub): + def __hash__(self): + return hash("GetSchema") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: schema_service.GetSchemaRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> schema.Schema: + r"""Call the get schema method over HTTP. + + Args: + request (~.schema_service.GetSchemaRequest): + The request object. Request message for + [SchemaService.GetSchema][google.cloud.discoveryengine.v1.SchemaService.GetSchema] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.schema.Schema: + Defines the structure and layout of a + type of document data. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/schemas/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}', + }, + ] + request, metadata = self._interceptor.pre_get_schema(request, metadata) + pb_request = schema_service.GetSchemaRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = schema.Schema() + pb_resp = schema.Schema.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_schema(resp) + return resp + + class _ListSchemas(SchemaServiceRestStub): + def __hash__(self): + return hash("ListSchemas") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: schema_service.ListSchemasRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> schema_service.ListSchemasResponse: + r"""Call the list schemas method over HTTP. + + Args: + request (~.schema_service.ListSchemasRequest): + The request object. Request message for + [SchemaService.ListSchemas][google.cloud.discoveryengine.v1.SchemaService.ListSchemas] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.schema_service.ListSchemasResponse: + Response message for + [SchemaService.ListSchemas][google.cloud.discoveryengine.v1.SchemaService.ListSchemas] + method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/dataStores/*}/schemas', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/collections/*/dataStores/*}/schemas', + }, + ] + request, metadata = self._interceptor.pre_list_schemas(request, metadata) + pb_request = schema_service.ListSchemasRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = schema_service.ListSchemasResponse() + pb_resp = schema_service.ListSchemasResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_schemas(resp) + return resp + + class _UpdateSchema(SchemaServiceRestStub): + def __hash__(self): + return hash("UpdateSchema") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: schema_service.UpdateSchemaRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update schema method over HTTP. + + Args: + request (~.schema_service.UpdateSchemaRequest): + The request object. Request message for + [SchemaService.UpdateSchema][google.cloud.discoveryengine.v1.SchemaService.UpdateSchema] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{schema.name=projects/*/locations/*/dataStores/*/schemas/*}', + 'body': 'schema', + }, +{ + 'method': 'patch', + 'uri': '/v1/{schema.name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}', + 'body': 'schema', + }, + ] + request, metadata = self._interceptor.pre_update_schema(request, metadata) + pb_request = schema_service.UpdateSchemaRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_schema(resp) + return resp + + @property + def create_schema(self) -> Callable[ + [schema_service.CreateSchemaRequest], + 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._CreateSchema(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_schema(self) -> Callable[ + [schema_service.DeleteSchemaRequest], + 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._DeleteSchema(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_schema(self) -> Callable[ + [schema_service.GetSchemaRequest], + schema.Schema]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSchema(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_schemas(self) -> Callable[ + [schema_service.ListSchemasRequest], + schema_service.ListSchemasResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSchemas(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_schema(self) -> Callable[ + [schema_service.UpdateSchemaRequest], + 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._UpdateSchema(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(SchemaServiceRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(SchemaServiceRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/engines/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'SchemaServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/__init__.py new file mode 100644 index 000000000000..0355170e3569 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import SearchServiceClient +from .async_client import SearchServiceAsyncClient + +__all__ = ( + 'SearchServiceClient', + 'SearchServiceAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/async_client.py new file mode 100644 index 000000000000..82217b20b1f8 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/async_client.py @@ -0,0 +1,402 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.discoveryengine_v1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.discoveryengine_v1.services.search_service import pagers +from google.cloud.discoveryengine_v1.types import search_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport +from .client import SearchServiceClient + + +class SearchServiceAsyncClient: + """Service for search.""" + + _client: SearchServiceClient + + DEFAULT_ENDPOINT = SearchServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SearchServiceClient.DEFAULT_MTLS_ENDPOINT + + branch_path = staticmethod(SearchServiceClient.branch_path) + parse_branch_path = staticmethod(SearchServiceClient.parse_branch_path) + document_path = staticmethod(SearchServiceClient.document_path) + parse_document_path = staticmethod(SearchServiceClient.parse_document_path) + serving_config_path = staticmethod(SearchServiceClient.serving_config_path) + parse_serving_config_path = staticmethod(SearchServiceClient.parse_serving_config_path) + common_billing_account_path = staticmethod(SearchServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SearchServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SearchServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(SearchServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(SearchServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(SearchServiceClient.parse_common_organization_path) + common_project_path = staticmethod(SearchServiceClient.common_project_path) + parse_common_project_path = staticmethod(SearchServiceClient.parse_common_project_path) + common_location_path = staticmethod(SearchServiceClient.common_location_path) + parse_common_location_path = staticmethod(SearchServiceClient.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: + SearchServiceAsyncClient: The constructed client. + """ + return SearchServiceClient.from_service_account_info.__func__(SearchServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceAsyncClient: The constructed client. + """ + return SearchServiceClient.from_service_account_file.__func__(SearchServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return SearchServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SearchServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SearchServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(SearchServiceClient).get_transport_class, type(SearchServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, SearchServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the search 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 (Union[str, ~.SearchServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = SearchServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def search(self, + request: Optional[Union[search_service.SearchRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAsyncPager: + r"""Performs a search. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + async def sample_search(): + # Create a client + client = discoveryengine_v1.SearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.SearchRequest( + serving_config="serving_config_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1.types.SearchRequest, dict]]): + The request object. Request message for + [SearchService.Search][google.cloud.discoveryengine.v1.SearchService.Search] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1.services.search_service.pagers.SearchAsyncPager: + Response message for + [SearchService.Search][google.cloud.discoveryengine.v1.SearchService.Search] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + request = search_service.SearchRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.search, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config", request.serving_config), + )), + ) + + # 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.SearchAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "SearchServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "SearchServiceAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/client.py new file mode 100644 index 000000000000..32942a207220 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/client.py @@ -0,0 +1,628 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.discoveryengine_v1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.discoveryengine_v1.services.search_service import pagers +from google.cloud.discoveryengine_v1.types import search_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SearchServiceGrpcTransport +from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport +from .transports.rest import SearchServiceRestTransport + + +class SearchServiceClientMeta(type): + """Metaclass for the SearchService 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[SearchServiceTransport]] + _transport_registry["grpc"] = SearchServiceGrpcTransport + _transport_registry["grpc_asyncio"] = SearchServiceGrpcAsyncIOTransport + _transport_registry["rest"] = SearchServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[SearchServiceTransport]: + """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 SearchServiceClient(metaclass=SearchServiceClientMeta): + """Service for search.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceClient: 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: + SearchServiceClient: 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) -> SearchServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SearchServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def branch_path(project: str,location: str,data_store: str,branch: str,) -> str: + """Returns a fully-qualified branch string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}".format(project=project, location=location, data_store=data_store, branch=branch, ) + + @staticmethod + def parse_branch_path(path: str) -> Dict[str,str]: + """Parses a branch path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def document_path(project: str,location: str,data_store: str,branch: str,document: str,) -> str: + """Returns a fully-qualified document string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) + + @staticmethod + def parse_document_path(path: str) -> Dict[str,str]: + """Parses a document path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)/documents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def serving_config_path(project: str,location: str,data_store: str,serving_config: str,) -> str: + """Returns a fully-qualified serving_config string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/servingConfigs/{serving_config}".format(project=project, location=location, data_store=data_store, serving_config=serving_config, ) + + @staticmethod + def parse_serving_config_path(path: str) -> Dict[str,str]: + """Parses a serving_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/servingConfigs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, SearchServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the search 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 (Union[str, SearchServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, SearchServiceTransport): + # transport is a SearchServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def search(self, + request: Optional[Union[search_service.SearchRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchPager: + r"""Performs a search. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + def sample_search(): + # Create a client + client = discoveryengine_v1.SearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.SearchRequest( + serving_config="serving_config_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1.types.SearchRequest, dict]): + The request object. Request message for + [SearchService.Search][google.cloud.discoveryengine.v1.SearchService.Search] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1.services.search_service.pagers.SearchPager: + Response message for + [SearchService.Search][google.cloud.discoveryengine.v1.SearchService.Search] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a search_service.SearchRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, search_service.SearchRequest): + request = search_service.SearchRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config", request.serving_config), + )), + ) + + # 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.SearchPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "SearchServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "SearchServiceClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/pagers.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/pagers.py new file mode 100644 index 000000000000..34caebaa5864 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/pagers.py @@ -0,0 +1,139 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.discoveryengine_v1.types import search_service + + +class SearchPager: + """A pager for iterating through ``search`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1.types.SearchResponse` object, and + provides an ``__iter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``Search`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1.types.SearchResponse` + 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[..., search_service.SearchResponse], + request: search_service.SearchRequest, + response: search_service.SearchResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.discoveryengine_v1.types.SearchRequest): + The initial request object. + response (google.cloud.discoveryengine_v1.types.SearchResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = search_service.SearchRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[search_service.SearchResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[search_service.SearchResponse.SearchResult]: + for page in self.pages: + yield from page.results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchAsyncPager: + """A pager for iterating through ``search`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1.types.SearchResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``Search`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1.types.SearchResponse` + 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[search_service.SearchResponse]], + request: search_service.SearchRequest, + response: search_service.SearchResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.discoveryengine_v1.types.SearchRequest): + The initial request object. + response (google.cloud.discoveryengine_v1.types.SearchResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = search_service.SearchRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[search_service.SearchResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[search_service.SearchResponse.SearchResult]: + async def async_generator(): + async for page in self.pages: + for response in page.results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/__init__.py new file mode 100644 index 000000000000..4282aef080e3 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import SearchServiceTransport +from .grpc import SearchServiceGrpcTransport +from .grpc_asyncio import SearchServiceGrpcAsyncIOTransport +from .rest import SearchServiceRestTransport +from .rest import SearchServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] +_transport_registry['grpc'] = SearchServiceGrpcTransport +_transport_registry['grpc_asyncio'] = SearchServiceGrpcAsyncIOTransport +_transport_registry['rest'] = SearchServiceRestTransport + +__all__ = ( + 'SearchServiceTransport', + 'SearchServiceGrpcTransport', + 'SearchServiceGrpcAsyncIOTransport', + 'SearchServiceRestTransport', + 'SearchServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/base.py new file mode 100644 index 000000000000..9266e6b82fae --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/base.py @@ -0,0 +1,168 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.discoveryengine_v1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.discoveryengine_v1.types import search_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class SearchServiceTransport(abc.ABC): + """Abstract transport class for SearchService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'discoveryengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.search: gapic_v1.method.wrap_method( + self.search, + 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 search(self) -> Callable[ + [search_service.SearchRequest], + Union[ + search_service.SearchResponse, + Awaitable[search_service.SearchResponse] + ]]: + 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 kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'SearchServiceTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/grpc.py new file mode 100644 index 000000000000..804ede46eaa7 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/grpc.py @@ -0,0 +1,302 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.discoveryengine_v1.types import search_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO + + +class SearchServiceGrpcTransport(SearchServiceTransport): + """gRPC backend transport for SearchService. + + Service for search. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def search(self) -> Callable[ + [search_service.SearchRequest], + search_service.SearchResponse]: + r"""Return a callable for the search method over gRPC. + + Performs a search. + + Returns: + Callable[[~.SearchRequest], + ~.SearchResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search' not in self._stubs: + self._stubs['search'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.SearchService/Search', + request_serializer=search_service.SearchRequest.serialize, + response_deserializer=search_service.SearchResponse.deserialize, + ) + return self._stubs['search'] + + def close(self): + self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'SearchServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..a12464fae22f --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/grpc_asyncio.py @@ -0,0 +1,301 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.discoveryengine_v1.types import search_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import SearchServiceGrpcTransport + + +class SearchServiceGrpcAsyncIOTransport(SearchServiceTransport): + """gRPC AsyncIO backend transport for SearchService. + + Service for search. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def search(self) -> Callable[ + [search_service.SearchRequest], + Awaitable[search_service.SearchResponse]]: + r"""Return a callable for the search method over gRPC. + + Performs a search. + + Returns: + Callable[[~.SearchRequest], + Awaitable[~.SearchResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search' not in self._stubs: + self._stubs['search'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.SearchService/Search', + request_serializer=search_service.SearchRequest.serialize, + response_deserializer=search_service.SearchResponse.deserialize, + ) + return self._stubs['search'] + + def close(self): + return self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ( + 'SearchServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/rest.py new file mode 100644 index 000000000000..255451db805f --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/rest.py @@ -0,0 +1,584 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.cloud.location import locations_pb2 # type: ignore +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.discoveryengine_v1.types import search_service +from google.longrunning import operations_pb2 # type: ignore + +from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class SearchServiceRestInterceptor: + """Interceptor for SearchService. + + 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 SearchServiceRestTransport. + + .. code-block:: python + class MyCustomSearchServiceInterceptor(SearchServiceRestInterceptor): + def pre_search(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_search(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SearchServiceRestTransport(interceptor=MyCustomSearchServiceInterceptor()) + client = SearchServiceClient(transport=transport) + + + """ + def pre_search(self, request: search_service.SearchRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[search_service.SearchRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for search + + Override in a subclass to manipulate the request or metadata + before they are sent to the SearchService server. + """ + return request, metadata + + def post_search(self, response: search_service.SearchResponse) -> search_service.SearchResponse: + """Post-rpc interceptor for search + + Override in a subclass to manipulate the response + after it is returned by the SearchService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the SearchService 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 SearchService server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the SearchService 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 SearchService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class SearchServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: SearchServiceRestInterceptor + + +class SearchServiceRestTransport(SearchServiceTransport): + """REST backend transport for SearchService. + + Service for search. + + 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 = 'discoveryengine.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[SearchServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or SearchServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _Search(SearchServiceRestStub): + def __hash__(self): + return hash("Search") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: search_service.SearchRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> search_service.SearchResponse: + r"""Call the search method over HTTP. + + Args: + request (~.search_service.SearchRequest): + The request object. Request message for + [SearchService.Search][google.cloud.discoveryengine.v1.SearchService.Search] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.search_service.SearchResponse: + Response message for + [SearchService.Search][google.cloud.discoveryengine.v1.SearchService.Search] + method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{serving_config=projects/*/locations/*/dataStores/*/servingConfigs/*}:search', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{serving_config=projects/*/locations/*/collections/*/dataStores/*/servingConfigs/*}:search', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_search(request, metadata) + pb_request = search_service.SearchRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = search_service.SearchResponse() + pb_resp = search_service.SearchResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_search(resp) + return resp + + @property + def search(self) -> Callable[ + [search_service.SearchRequest], + search_service.SearchResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Search(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(SearchServiceRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(SearchServiceRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/engines/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'SearchServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/__init__.py new file mode 100644 index 000000000000..387c002d1701 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import UserEventServiceClient +from .async_client import UserEventServiceAsyncClient + +__all__ = ( + 'UserEventServiceClient', + 'UserEventServiceAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/async_client.py new file mode 100644 index 000000000000..257240b756f1 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/async_client.py @@ -0,0 +1,644 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.discoveryengine_v1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.discoveryengine_v1.types import common +from google.cloud.discoveryengine_v1.types import import_config +from google.cloud.discoveryengine_v1.types import user_event +from google.cloud.discoveryengine_v1.types import user_event_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport +from .client import UserEventServiceClient + + +class UserEventServiceAsyncClient: + """Service for ingesting end user actions on a website to + Discovery Engine API. + """ + + _client: UserEventServiceClient + + DEFAULT_ENDPOINT = UserEventServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = UserEventServiceClient.DEFAULT_MTLS_ENDPOINT + + data_store_path = staticmethod(UserEventServiceClient.data_store_path) + parse_data_store_path = staticmethod(UserEventServiceClient.parse_data_store_path) + document_path = staticmethod(UserEventServiceClient.document_path) + parse_document_path = staticmethod(UserEventServiceClient.parse_document_path) + common_billing_account_path = staticmethod(UserEventServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(UserEventServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(UserEventServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(UserEventServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(UserEventServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(UserEventServiceClient.parse_common_organization_path) + common_project_path = staticmethod(UserEventServiceClient.common_project_path) + parse_common_project_path = staticmethod(UserEventServiceClient.parse_common_project_path) + common_location_path = staticmethod(UserEventServiceClient.common_location_path) + parse_common_location_path = staticmethod(UserEventServiceClient.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: + UserEventServiceAsyncClient: The constructed client. + """ + return UserEventServiceClient.from_service_account_info.__func__(UserEventServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceAsyncClient: The constructed client. + """ + return UserEventServiceClient.from_service_account_file.__func__(UserEventServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return UserEventServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> UserEventServiceTransport: + """Returns the transport used by the client instance. + + Returns: + UserEventServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(UserEventServiceClient).get_transport_class, type(UserEventServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, UserEventServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the user event 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 (Union[str, ~.UserEventServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = UserEventServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def write_user_event(self, + request: Optional[Union[user_event_service.WriteUserEventRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> user_event.UserEvent: + r"""Writes a single user event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + async def sample_write_user_event(): + # Create a client + client = discoveryengine_v1.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.WriteUserEventRequest( + parent="parent_value", + ) + + # Make the request + response = await client.write_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1.types.WriteUserEventRequest, dict]]): + The request object. Request message for WriteUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1.types.UserEvent: + UserEvent captures all metadata + information Discovery Engine API needs + to know about how end users interact + with customers' website. + + """ + # Create or coerce a protobuf request object. + request = user_event_service.WriteUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.write_user_event, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def collect_user_event(self, + request: Optional[Union[user_event_service.CollectUserEventRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> httpbody_pb2.HttpBody: + r"""Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a third-party domain. + + This method is used only by the Discovery Engine API + JavaScript pixel and Google Tag Manager. Users should + not call this method directly. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + async def sample_collect_user_event(): + # Create a client + client = discoveryengine_v1.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = await client.collect_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1.types.CollectUserEventRequest, dict]]): + The request object. Request message for CollectUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It should only be used for + payload formats that can't be represented as JSON, + such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as + the response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request + fields and also want access to the raw HTTP body. + + Example: + + message GetResourceRequest { + // A unique request id. string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + # Create or coerce a protobuf request object. + request = user_event_service.CollectUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.collect_user_event, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def import_user_events(self, + request: Optional[Union[import_config.ImportUserEventsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + async def sample_import_user_events(): + # Create a client + client = discoveryengine_v1.UserEventServiceAsyncClient() + + # Initialize request argument(s) + inline_source = discoveryengine_v1.InlineSource() + inline_source.user_events.event_type = "event_type_value" + inline_source.user_events.user_pseudo_id = "user_pseudo_id_value" + + request = discoveryengine_v1.ImportUserEventsRequest( + inline_source=inline_source, + parent="parent_value", + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1.types.ImportUserEventsRequest, dict]]): + The request object. Request message for the + ImportUserEvents request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is + returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + request = import_config.ImportUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_user_events, + default_retry=retries.Retry( +initial=1.0,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_config.ImportUserEventsResponse, + metadata_type=import_config.ImportUserEventsMetadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "UserEventServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "UserEventServiceAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/client.py new file mode 100644 index 000000000000..80ca814e4647 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/client.py @@ -0,0 +1,857 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.discoveryengine_v1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.discoveryengine_v1.types import common +from google.cloud.discoveryengine_v1.types import import_config +from google.cloud.discoveryengine_v1.types import user_event +from google.cloud.discoveryengine_v1.types import user_event_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import UserEventServiceGrpcTransport +from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport +from .transports.rest import UserEventServiceRestTransport + + +class UserEventServiceClientMeta(type): + """Metaclass for the UserEventService 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[UserEventServiceTransport]] + _transport_registry["grpc"] = UserEventServiceGrpcTransport + _transport_registry["grpc_asyncio"] = UserEventServiceGrpcAsyncIOTransport + _transport_registry["rest"] = UserEventServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[UserEventServiceTransport]: + """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 UserEventServiceClient(metaclass=UserEventServiceClientMeta): + """Service for ingesting end user actions on a website to + Discovery Engine API. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceClient: 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: + UserEventServiceClient: 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) -> UserEventServiceTransport: + """Returns the transport used by the client instance. + + Returns: + UserEventServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def data_store_path(project: str,location: str,data_store: str,) -> str: + """Returns a fully-qualified data_store string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) + + @staticmethod + def parse_data_store_path(path: str) -> Dict[str,str]: + """Parses a data_store path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def document_path(project: str,location: str,data_store: str,branch: str,document: str,) -> str: + """Returns a fully-qualified document string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) + + @staticmethod + def parse_document_path(path: str) -> Dict[str,str]: + """Parses a document path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)/documents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, UserEventServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the user event 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 (Union[str, UserEventServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, UserEventServiceTransport): + # transport is a UserEventServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def write_user_event(self, + request: Optional[Union[user_event_service.WriteUserEventRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> user_event.UserEvent: + r"""Writes a single user event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + def sample_write_user_event(): + # Create a client + client = discoveryengine_v1.UserEventServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.WriteUserEventRequest( + parent="parent_value", + ) + + # Make the request + response = client.write_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1.types.WriteUserEventRequest, dict]): + The request object. Request message for WriteUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1.types.UserEvent: + UserEvent captures all metadata + information Discovery Engine API needs + to know about how end users interact + with customers' website. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.WriteUserEventRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, user_event_service.WriteUserEventRequest): + request = user_event_service.WriteUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.write_user_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def collect_user_event(self, + request: Optional[Union[user_event_service.CollectUserEventRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> httpbody_pb2.HttpBody: + r"""Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a third-party domain. + + This method is used only by the Discovery Engine API + JavaScript pixel and Google Tag Manager. Users should + not call this method directly. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + def sample_collect_user_event(): + # Create a client + client = discoveryengine_v1.UserEventServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = client.collect_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1.types.CollectUserEventRequest, dict]): + The request object. Request message for CollectUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It should only be used for + payload formats that can't be represented as JSON, + such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as + the response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request + fields and also want access to the raw HTTP body. + + Example: + + message GetResourceRequest { + // A unique request id. string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.CollectUserEventRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, user_event_service.CollectUserEventRequest): + request = user_event_service.CollectUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.collect_user_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def import_user_events(self, + request: Optional[Union[import_config.ImportUserEventsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1 + + def sample_import_user_events(): + # Create a client + client = discoveryengine_v1.UserEventServiceClient() + + # Initialize request argument(s) + inline_source = discoveryengine_v1.InlineSource() + inline_source.user_events.event_type = "event_type_value" + inline_source.user_events.user_pseudo_id = "user_pseudo_id_value" + + request = discoveryengine_v1.ImportUserEventsRequest( + inline_source=inline_source, + parent="parent_value", + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1.types.ImportUserEventsRequest, dict]): + The request object. Request message for the + ImportUserEvents request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is + returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a import_config.ImportUserEventsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, import_config.ImportUserEventsRequest): + request = import_config.ImportUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_user_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_config.ImportUserEventsResponse, + metadata_type=import_config.ImportUserEventsMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "UserEventServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "UserEventServiceClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/__init__.py new file mode 100644 index 000000000000..bea95d5a9d94 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import UserEventServiceTransport +from .grpc import UserEventServiceGrpcTransport +from .grpc_asyncio import UserEventServiceGrpcAsyncIOTransport +from .rest import UserEventServiceRestTransport +from .rest import UserEventServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] +_transport_registry['grpc'] = UserEventServiceGrpcTransport +_transport_registry['grpc_asyncio'] = UserEventServiceGrpcAsyncIOTransport +_transport_registry['rest'] = UserEventServiceRestTransport + +__all__ = ( + 'UserEventServiceTransport', + 'UserEventServiceGrpcTransport', + 'UserEventServiceGrpcAsyncIOTransport', + 'UserEventServiceRestTransport', + 'UserEventServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/base.py new file mode 100644 index 000000000000..ecbf50a999fd --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/base.py @@ -0,0 +1,211 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.discoveryengine_v1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.discoveryengine_v1.types import import_config +from google.cloud.discoveryengine_v1.types import user_event +from google.cloud.discoveryengine_v1.types import user_event_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class UserEventServiceTransport(abc.ABC): + """Abstract transport class for UserEventService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'discoveryengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.write_user_event: gapic_v1.method.wrap_method( + self.write_user_event, + default_timeout=None, + client_info=client_info, + ), + self.collect_user_event: gapic_v1.method.wrap_method( + self.collect_user_event, + default_timeout=None, + client_info=client_info, + ), + self.import_user_events: gapic_v1.method.wrap_method( + self.import_user_events, + default_retry=retries.Retry( +initial=1.0,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + Union[ + user_event.UserEvent, + Awaitable[user_event.UserEvent] + ]]: + raise NotImplementedError() + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + Union[ + httpbody_pb2.HttpBody, + Awaitable[httpbody_pb2.HttpBody] + ]]: + raise NotImplementedError() + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'UserEventServiceTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/grpc.py new file mode 100644 index 000000000000..a8947aaaf1de --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/grpc.py @@ -0,0 +1,389 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.discoveryengine_v1.types import import_config +from google.cloud.discoveryengine_v1.types import user_event +from google.cloud.discoveryengine_v1.types import user_event_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO + + +class UserEventServiceGrpcTransport(UserEventServiceTransport): + """gRPC backend transport for UserEventService. + + Service for ingesting end user actions on a website to + Discovery Engine 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 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + user_event.UserEvent]: + r"""Return a callable for the write user event method over gRPC. + + Writes a single user event. + + Returns: + Callable[[~.WriteUserEventRequest], + ~.UserEvent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'write_user_event' not in self._stubs: + self._stubs['write_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.UserEventService/WriteUserEvent', + request_serializer=user_event_service.WriteUserEventRequest.serialize, + response_deserializer=user_event.UserEvent.deserialize, + ) + return self._stubs['write_user_event'] + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + httpbody_pb2.HttpBody]: + r"""Return a callable for the collect user event method over gRPC. + + Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a third-party domain. + + This method is used only by the Discovery Engine API + JavaScript pixel and Google Tag Manager. Users should + not call this method directly. + + Returns: + Callable[[~.CollectUserEventRequest], + ~.HttpBody]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'collect_user_event' not in self._stubs: + self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.UserEventService/CollectUserEvent', + request_serializer=user_event_service.CollectUserEventRequest.serialize, + response_deserializer=httpbody_pb2.HttpBody.FromString, + ) + return self._stubs['collect_user_event'] + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + operations_pb2.Operation]: + r"""Return a callable for the import user events method over gRPC. + + Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + Returns: + Callable[[~.ImportUserEventsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_user_events' not in self._stubs: + self._stubs['import_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.UserEventService/ImportUserEvents', + request_serializer=import_config.ImportUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_user_events'] + + def close(self): + self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'UserEventServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..2053f8993009 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/grpc_asyncio.py @@ -0,0 +1,388 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.discoveryengine_v1.types import import_config +from google.cloud.discoveryengine_v1.types import user_event +from google.cloud.discoveryengine_v1.types import user_event_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import UserEventServiceGrpcTransport + + +class UserEventServiceGrpcAsyncIOTransport(UserEventServiceTransport): + """gRPC AsyncIO backend transport for UserEventService. + + Service for ingesting end user actions on a website to + Discovery Engine 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 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + Awaitable[user_event.UserEvent]]: + r"""Return a callable for the write user event method over gRPC. + + Writes a single user event. + + Returns: + Callable[[~.WriteUserEventRequest], + Awaitable[~.UserEvent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'write_user_event' not in self._stubs: + self._stubs['write_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.UserEventService/WriteUserEvent', + request_serializer=user_event_service.WriteUserEventRequest.serialize, + response_deserializer=user_event.UserEvent.deserialize, + ) + return self._stubs['write_user_event'] + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + Awaitable[httpbody_pb2.HttpBody]]: + r"""Return a callable for the collect user event method over gRPC. + + Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a third-party domain. + + This method is used only by the Discovery Engine API + JavaScript pixel and Google Tag Manager. Users should + not call this method directly. + + Returns: + Callable[[~.CollectUserEventRequest], + Awaitable[~.HttpBody]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'collect_user_event' not in self._stubs: + self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.UserEventService/CollectUserEvent', + request_serializer=user_event_service.CollectUserEventRequest.serialize, + response_deserializer=httpbody_pb2.HttpBody.FromString, + ) + return self._stubs['collect_user_event'] + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import user events method over gRPC. + + Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + Returns: + Callable[[~.ImportUserEventsRequest], + 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 'import_user_events' not in self._stubs: + self._stubs['import_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1.UserEventService/ImportUserEvents', + request_serializer=import_config.ImportUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_user_events'] + + def close(self): + return self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ( + 'UserEventServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/rest.py new file mode 100644 index 000000000000..9b065bb735a0 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/rest.py @@ -0,0 +1,1021 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.cloud.location import locations_pb2 # type: ignore +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.discoveryengine_v1.types import import_config +from google.cloud.discoveryengine_v1.types import user_event +from google.cloud.discoveryengine_v1.types import user_event_service +from google.longrunning import operations_pb2 # type: ignore + +from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class UserEventServiceRestInterceptor: + """Interceptor for UserEventService. + + 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 UserEventServiceRestTransport. + + .. code-block:: python + class MyCustomUserEventServiceInterceptor(UserEventServiceRestInterceptor): + def pre_collect_user_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_collect_user_event(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_import_user_events(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_import_user_events(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_write_user_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_write_user_event(self, response): + logging.log(f"Received response: {response}") + return response + + transport = UserEventServiceRestTransport(interceptor=MyCustomUserEventServiceInterceptor()) + client = UserEventServiceClient(transport=transport) + + + """ + def pre_collect_user_event(self, request: user_event_service.CollectUserEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[user_event_service.CollectUserEventRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for collect_user_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserEventService server. + """ + return request, metadata + + def post_collect_user_event(self, response: httpbody_pb2.HttpBody) -> httpbody_pb2.HttpBody: + """Post-rpc interceptor for collect_user_event + + Override in a subclass to manipulate the response + after it is returned by the UserEventService server but before + it is returned to user code. + """ + return response + def pre_import_user_events(self, request: import_config.ImportUserEventsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[import_config.ImportUserEventsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for import_user_events + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserEventService server. + """ + return request, metadata + + def post_import_user_events(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for import_user_events + + Override in a subclass to manipulate the response + after it is returned by the UserEventService server but before + it is returned to user code. + """ + return response + def pre_write_user_event(self, request: user_event_service.WriteUserEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[user_event_service.WriteUserEventRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for write_user_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserEventService server. + """ + return request, metadata + + def post_write_user_event(self, response: user_event.UserEvent) -> user_event.UserEvent: + """Post-rpc interceptor for write_user_event + + Override in a subclass to manipulate the response + after it is returned by the UserEventService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserEventService 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 UserEventService server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserEventService 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 UserEventService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class UserEventServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: UserEventServiceRestInterceptor + + +class UserEventServiceRestTransport(UserEventServiceTransport): + """REST backend transport for UserEventService. + + Service for ingesting end user actions on a website to + Discovery Engine 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 = 'discoveryengine.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[UserEventServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or UserEventServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/engines/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/models/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1/{name=projects/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CollectUserEvent(UserEventServiceRestStub): + def __hash__(self): + return hash("CollectUserEvent") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "userEvent" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: user_event_service.CollectUserEventRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> httpbody_pb2.HttpBody: + r"""Call the collect user event method over HTTP. + + Args: + request (~.user_event_service.CollectUserEventRequest): + The request object. Request message for CollectUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It + should only be used for payload formats that can't be + represented as JSON, such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as the + response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request fields + and also want access to the raw HTTP body. + + Example: + + :: + + message GetResourceRequest { + // A unique request id. + string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + :: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/dataStores/*}/userEvents:collect', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/collections/*/dataStores/*}/userEvents:collect', + }, + ] + request, metadata = self._interceptor.pre_collect_user_event(request, metadata) + pb_request = user_event_service.CollectUserEventRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = httpbody_pb2.HttpBody() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_collect_user_event(resp) + return resp + + class _ImportUserEvents(UserEventServiceRestStub): + def __hash__(self): + return hash("ImportUserEvents") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: import_config.ImportUserEventsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the import user events method over HTTP. + + Args: + request (~.import_config.ImportUserEventsRequest): + The request object. Request message for the + ImportUserEvents request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/dataStores/*}/userEvents:import', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/collections/*/dataStores/*}/userEvents:import', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_import_user_events(request, metadata) + pb_request = import_config.ImportUserEventsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_import_user_events(resp) + return resp + + class _WriteUserEvent(UserEventServiceRestStub): + def __hash__(self): + return hash("WriteUserEvent") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: user_event_service.WriteUserEventRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> user_event.UserEvent: + r"""Call the write user event method over HTTP. + + Args: + request (~.user_event_service.WriteUserEventRequest): + The request object. Request message for WriteUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.user_event.UserEvent: + UserEvent captures all metadata + information Discovery Engine API needs + to know about how end users interact + with customers' website. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/dataStores/*}/userEvents:write', + 'body': 'user_event', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/collections/*/dataStores/*}/userEvents:write', + 'body': 'user_event', + }, + ] + request, metadata = self._interceptor.pre_write_user_event(request, metadata) + pb_request = user_event_service.WriteUserEventRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = user_event.UserEvent() + pb_resp = user_event.UserEvent.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_write_user_event(resp) + return resp + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + httpbody_pb2.HttpBody]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CollectUserEvent(self._session, self._host, self._interceptor) # type: ignore + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + 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._ImportUserEvents(self._session, self._host, self._interceptor) # type: ignore + + @property + def write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + user_event.UserEvent]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._WriteUserEvent(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(UserEventServiceRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(UserEventServiceRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*/engines/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/collections/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'UserEventServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/__init__.py new file mode 100644 index 000000000000..146eeae9f7dc --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/__init__.py @@ -0,0 +1,162 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .common import ( + CustomAttribute, + Interval, + UserInfo, +) +from .completion_service import ( + CompleteQueryRequest, + CompleteQueryResponse, +) +from .conversation import ( + Conversation, + ConversationContext, + ConversationMessage, + Reply, + TextInput, +) +from .conversational_search_service import ( + ConverseConversationRequest, + ConverseConversationResponse, + CreateConversationRequest, + DeleteConversationRequest, + GetConversationRequest, + ListConversationsRequest, + ListConversationsResponse, + UpdateConversationRequest, +) +from .document import ( + Document, +) +from .document_service import ( + CreateDocumentRequest, + DeleteDocumentRequest, + GetDocumentRequest, + ListDocumentsRequest, + ListDocumentsResponse, + UpdateDocumentRequest, +) +from .import_config import ( + BigQuerySource, + GcsSource, + ImportDocumentsMetadata, + ImportDocumentsRequest, + ImportDocumentsResponse, + ImportErrorConfig, + ImportUserEventsMetadata, + ImportUserEventsRequest, + ImportUserEventsResponse, +) +from .purge_config import ( + PurgeDocumentsMetadata, + PurgeDocumentsRequest, + PurgeDocumentsResponse, +) +from .schema import ( + Schema, +) +from .schema_service import ( + CreateSchemaMetadata, + CreateSchemaRequest, + DeleteSchemaMetadata, + DeleteSchemaRequest, + GetSchemaRequest, + ListSchemasRequest, + ListSchemasResponse, + UpdateSchemaMetadata, + UpdateSchemaRequest, +) +from .search_service import ( + SearchRequest, + SearchResponse, +) +from .user_event import ( + CompletionInfo, + DocumentInfo, + MediaInfo, + PageInfo, + PanelInfo, + SearchInfo, + TransactionInfo, + UserEvent, +) +from .user_event_service import ( + CollectUserEventRequest, + WriteUserEventRequest, +) + +__all__ = ( + 'CustomAttribute', + 'Interval', + 'UserInfo', + 'CompleteQueryRequest', + 'CompleteQueryResponse', + 'Conversation', + 'ConversationContext', + 'ConversationMessage', + 'Reply', + 'TextInput', + 'ConverseConversationRequest', + 'ConverseConversationResponse', + 'CreateConversationRequest', + 'DeleteConversationRequest', + 'GetConversationRequest', + 'ListConversationsRequest', + 'ListConversationsResponse', + 'UpdateConversationRequest', + 'Document', + 'CreateDocumentRequest', + 'DeleteDocumentRequest', + 'GetDocumentRequest', + 'ListDocumentsRequest', + 'ListDocumentsResponse', + 'UpdateDocumentRequest', + 'BigQuerySource', + 'GcsSource', + 'ImportDocumentsMetadata', + 'ImportDocumentsRequest', + 'ImportDocumentsResponse', + 'ImportErrorConfig', + 'ImportUserEventsMetadata', + 'ImportUserEventsRequest', + 'ImportUserEventsResponse', + 'PurgeDocumentsMetadata', + 'PurgeDocumentsRequest', + 'PurgeDocumentsResponse', + 'Schema', + 'CreateSchemaMetadata', + 'CreateSchemaRequest', + 'DeleteSchemaMetadata', + 'DeleteSchemaRequest', + 'GetSchemaRequest', + 'ListSchemasRequest', + 'ListSchemasResponse', + 'UpdateSchemaMetadata', + 'UpdateSchemaRequest', + 'SearchRequest', + 'SearchResponse', + 'CompletionInfo', + 'DocumentInfo', + 'MediaInfo', + 'PageInfo', + 'PanelInfo', + 'SearchInfo', + 'TransactionInfo', + 'UserEvent', + 'CollectUserEventRequest', + 'WriteUserEventRequest', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/common.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/common.py new file mode 100644 index 000000000000..724d1429b4a0 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/common.py @@ -0,0 +1,167 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.discoveryengine.v1', + manifest={ + 'Interval', + 'CustomAttribute', + 'UserInfo', + }, +) + + +class Interval(proto.Message): + r"""A floating point interval. + + 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: + minimum (float): + Inclusive lower bound. + + This field is a member of `oneof`_ ``min``. + exclusive_minimum (float): + Exclusive lower bound. + + This field is a member of `oneof`_ ``min``. + maximum (float): + Inclusive upper bound. + + This field is a member of `oneof`_ ``max``. + exclusive_maximum (float): + Exclusive upper bound. + + This field is a member of `oneof`_ ``max``. + """ + + minimum: float = proto.Field( + proto.DOUBLE, + number=1, + oneof='min', + ) + exclusive_minimum: float = proto.Field( + proto.DOUBLE, + number=2, + oneof='min', + ) + maximum: float = proto.Field( + proto.DOUBLE, + number=3, + oneof='max', + ) + exclusive_maximum: float = proto.Field( + proto.DOUBLE, + number=4, + oneof='max', + ) + + +class CustomAttribute(proto.Message): + r"""A custom attribute that is not explicitly modeled in a resource, + e.g. [UserEvent][google.cloud.discoveryengine.v1.UserEvent]. + + Attributes: + text (MutableSequence[str]): + The textual values of this custom attribute. For example, + ``["yellow", "green"]`` when the key is "color". + + Empty string is not allowed. Otherwise, an + ``INVALID_ARGUMENT`` error is returned. + + Exactly one of + [CustomAttribute.text][google.cloud.discoveryengine.v1.CustomAttribute.text] + or + [CustomAttribute.numbers][google.cloud.discoveryengine.v1.CustomAttribute.numbers] + should be set. Otherwise, an ``INVALID_ARGUMENT`` error is + returned. + numbers (MutableSequence[float]): + The numerical values of this custom attribute. For example, + ``[2.3, 15.4]`` when the key is "lengths_cm". + + Exactly one of + [CustomAttribute.text][google.cloud.discoveryengine.v1.CustomAttribute.text] + or + [CustomAttribute.numbers][google.cloud.discoveryengine.v1.CustomAttribute.numbers] + should be set. Otherwise, an ``INVALID_ARGUMENT`` error is + returned. + """ + + text: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + numbers: MutableSequence[float] = proto.RepeatedField( + proto.DOUBLE, + number=2, + ) + + +class UserInfo(proto.Message): + r"""Information of an end user. + + Attributes: + user_id (str): + Highly recommended for logged-in users. Unique identifier + for logged-in user, such as a user name. Don't set for + anonymous users. + + Always use a hashed value for this ID. + + Don't set the field to the same fixed ID for different + users. This mixes the event history of those users together, + which results in degraded model quality. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an ``INVALID_ARGUMENT`` error + is returned. + user_agent (str): + User agent as included in the HTTP header. + + The field must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an ``INVALID_ARGUMENT`` + error is returned. + + This should not be set when using the client side event + reporting with GTM or JavaScript tag in + [UserEventService.CollectUserEvent][google.cloud.discoveryengine.v1.UserEventService.CollectUserEvent] + or if + [UserEvent.direct_user_request][google.cloud.discoveryengine.v1.UserEvent.direct_user_request] + is set. + """ + + user_id: str = proto.Field( + proto.STRING, + number=1, + ) + user_agent: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/completion_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/completion_service.py new file mode 100644 index 000000000000..5a956b2a746b --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/completion_service.py @@ -0,0 +1,158 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.discoveryengine.v1', + manifest={ + 'CompleteQueryRequest', + 'CompleteQueryResponse', + }, +) + + +class CompleteQueryRequest(proto.Message): + r"""Request message for + [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1.CompletionService.CompleteQuery] + method. + + Attributes: + data_store (str): + Required. The parent data store resource name for which the + completion is performed, such as + ``projects/*/locations/global/collections/default_collection/dataStores/default_data_store``. + query (str): + Required. The typeahead input used to fetch + suggestions. Maximum length is 128 characters. + query_model (str): + Selects data model of query suggestions for serving. + Currently supported values: + + - ``document`` - Using suggestions generated from + user-imported documents. + - ``search-history`` - Using suggestions generated from the + past history of + [SearchService.Search][google.cloud.discoveryengine.v1.SearchService.Search] + API calls. Do not use it when there is no traffic for + Search API. + - ``user-event`` - Using suggestions generated from + user-imported search events. + - ``document-completable`` - Using suggestions taken + directly from user-imported document fields marked as + completable. + + Default values: + + - ``document`` is the default model for regular dataStores. + - ``search-history`` is the default model for + [IndustryVertical.SITE_SEARCH][] dataStores. + user_pseudo_id (str): + A unique identifier for tracking visitors. For example, this + could be implemented with an HTTP cookie, which should be + able to uniquely identify a visitor on a single device. This + unique identifier should not change if the visitor logs in + or out of the website. + + This field should NOT have a fixed value such as + ``unknown_visitor``. + + This should be the same identifier as + [UserEvent.user_pseudo_id][google.cloud.discoveryengine.v1.UserEvent.user_pseudo_id] + and + [SearchRequest.user_pseudo_id][google.cloud.discoveryengine.v1.SearchRequest.user_pseudo_id]. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an ``INVALID_ARGUMENT`` error + is returned. + include_tail_suggestions (bool): + Indicates if tail suggestions should be + returned if there are no suggestions that match + the full query. Even if set to true, if there + are suggestions that match the full query, those + are returned and no tail suggestions are + returned. + """ + + data_store: str = proto.Field( + proto.STRING, + number=1, + ) + query: str = proto.Field( + proto.STRING, + number=2, + ) + query_model: str = proto.Field( + proto.STRING, + number=3, + ) + user_pseudo_id: str = proto.Field( + proto.STRING, + number=4, + ) + include_tail_suggestions: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class CompleteQueryResponse(proto.Message): + r"""Response message for + [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1.CompletionService.CompleteQuery] + method. + + Attributes: + query_suggestions (MutableSequence[google.cloud.discoveryengine_v1.types.CompleteQueryResponse.QuerySuggestion]): + Results of the matched query suggestions. The + result list is ordered and the first result is a + top suggestion. + tail_match_triggered (bool): + True if the returned suggestions are all tail suggestions. + + For tail matching to be triggered, include_tail_suggestions + in the request must be true and there must be no suggestions + that match the full query. + """ + + class QuerySuggestion(proto.Message): + r"""Suggestions as search queries. + + Attributes: + suggestion (str): + The suggestion for the query. + """ + + suggestion: str = proto.Field( + proto.STRING, + number=1, + ) + + query_suggestions: MutableSequence[QuerySuggestion] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=QuerySuggestion, + ) + tail_match_triggered: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/conversation.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/conversation.py new file mode 100644 index 000000000000..9f24e918cc42 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/conversation.py @@ -0,0 +1,204 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.discoveryengine_v1.types import search_service +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1', + manifest={ + 'Conversation', + 'Reply', + 'ConversationContext', + 'TextInput', + 'ConversationMessage', + }, +) + + +class Conversation(proto.Message): + r"""External conversation proto definition. + + Attributes: + name (str): + Immutable. Fully qualified name + ``project/*/locations/global/collections/{collection}/dataStore/*/conversations/*`` + state (google.cloud.discoveryengine_v1.types.Conversation.State): + The state of the Conversation. + user_pseudo_id (str): + A unique identifier for tracking users. + messages (MutableSequence[google.cloud.discoveryengine_v1.types.ConversationMessage]): + Conversation messages. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the conversation + started. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the conversation + finished. + """ + class State(proto.Enum): + r"""Enumeration of the state of the conversation. + + Values: + STATE_UNSPECIFIED (0): + Unknown. + IN_PROGRESS (1): + Conversation is currently open. + COMPLETED (2): + Conversation has been completed. + """ + STATE_UNSPECIFIED = 0 + IN_PROGRESS = 1 + COMPLETED = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + state: State = proto.Field( + proto.ENUM, + number=2, + enum=State, + ) + user_pseudo_id: str = proto.Field( + proto.STRING, + number=3, + ) + messages: MutableSequence['ConversationMessage'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='ConversationMessage', + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + + +class Reply(proto.Message): + r"""Defines a reply message to user. + + Attributes: + summary (google.cloud.discoveryengine_v1.types.SearchResponse.Summary): + Summary based on search results. + """ + + summary: search_service.SearchResponse.Summary = proto.Field( + proto.MESSAGE, + number=3, + message=search_service.SearchResponse.Summary, + ) + + +class ConversationContext(proto.Message): + r"""Defines context of the conversation + + Attributes: + context_documents (MutableSequence[str]): + The current list of documents the user is + seeing. It contains the document resource + references. + active_document (str): + The current active document the user opened. + It contains the document resource reference. + """ + + context_documents: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + active_document: str = proto.Field( + proto.STRING, + number=2, + ) + + +class TextInput(proto.Message): + r"""Defines text input. + + Attributes: + input (str): + Text input. + context (google.cloud.discoveryengine_v1.types.ConversationContext): + Conversation context of the input. + """ + + input: str = proto.Field( + proto.STRING, + number=1, + ) + context: 'ConversationContext' = proto.Field( + proto.MESSAGE, + number=2, + message='ConversationContext', + ) + + +class ConversationMessage(proto.Message): + r"""Defines a conversation 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: + user_input (google.cloud.discoveryengine_v1.types.TextInput): + User text input. + + This field is a member of `oneof`_ ``message``. + reply (google.cloud.discoveryengine_v1.types.Reply): + Search reply. + + This field is a member of `oneof`_ ``message``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Message creation timestamp. + """ + + user_input: 'TextInput' = proto.Field( + proto.MESSAGE, + number=1, + oneof='message', + message='TextInput', + ) + reply: 'Reply' = proto.Field( + proto.MESSAGE, + number=2, + oneof='message', + message='Reply', + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/conversational_search_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/conversational_search_service.py new file mode 100644 index 000000000000..8666504225a4 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/conversational_search_service.py @@ -0,0 +1,322 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.discoveryengine_v1.types import conversation as gcd_conversation +from google.cloud.discoveryengine_v1.types import search_service +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1', + manifest={ + 'ConverseConversationRequest', + 'ConverseConversationResponse', + 'CreateConversationRequest', + 'UpdateConversationRequest', + 'DeleteConversationRequest', + 'GetConversationRequest', + 'ListConversationsRequest', + 'ListConversationsResponse', + }, +) + + +class ConverseConversationRequest(proto.Message): + r"""Request message for + [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1.ConversationalSearchService.ConverseConversation] + method. + + Attributes: + name (str): + Required. The resource name of the Conversation to get. + Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}``. + Use + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/-`` + to activate auto session mode, which automatically creates a + new conversation inside a ConverseConversation session. + query (google.cloud.discoveryengine_v1.types.TextInput): + Required. Current user input. + serving_config (str): + The resource name of the Serving Config to use. Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/servingConfigs/{serving_config_id}`` + If this is not set, the default serving config will be used. + conversation (google.cloud.discoveryengine_v1.types.Conversation): + The conversation to be used by auto session + only. The name field will be ignored as we + automatically assign new name for the + conversation in auto session. + safe_search (bool): + Whether to turn on safe search. + user_labels (MutableMapping[str, str]): + The user labels applied to a resource must meet the + following requirements: + + - Each resource can have multiple labels, up to a maximum + of 64. + - Each label must be a key-value pair. + - Keys have a minimum length of 1 character and a maximum + length of 63 characters and cannot be empty. Values can + be empty and have a maximum length of 63 characters. + - Keys and values can contain only lowercase letters, + numeric characters, underscores, and dashes. All + characters must use UTF-8 encoding, and international + characters are allowed. + - The key portion of a label must be unique. However, you + can use the same key with multiple resources. + - Keys must start with a lowercase letter or international + character. + + See `Google Cloud + Document `__ + for more details. + summary_spec (google.cloud.discoveryengine_v1.types.SearchRequest.ContentSearchSpec.SummarySpec): + A specification for configuring the summary + returned in the response. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + query: gcd_conversation.TextInput = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_conversation.TextInput, + ) + serving_config: str = proto.Field( + proto.STRING, + number=3, + ) + conversation: gcd_conversation.Conversation = proto.Field( + proto.MESSAGE, + number=5, + message=gcd_conversation.Conversation, + ) + safe_search: bool = proto.Field( + proto.BOOL, + number=6, + ) + user_labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + summary_spec: search_service.SearchRequest.ContentSearchSpec.SummarySpec = proto.Field( + proto.MESSAGE, + number=8, + message=search_service.SearchRequest.ContentSearchSpec.SummarySpec, + ) + + +class ConverseConversationResponse(proto.Message): + r"""Response message for + [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1.ConversationalSearchService.ConverseConversation] + method. + + Attributes: + reply (google.cloud.discoveryengine_v1.types.Reply): + Answer to the current query. + conversation (google.cloud.discoveryengine_v1.types.Conversation): + Updated conversation including the answer. + search_results (MutableSequence[google.cloud.discoveryengine_v1.types.SearchResponse.SearchResult]): + Search Results. + """ + + reply: gcd_conversation.Reply = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_conversation.Reply, + ) + conversation: gcd_conversation.Conversation = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_conversation.Conversation, + ) + search_results: MutableSequence[search_service.SearchResponse.SearchResult] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=search_service.SearchResponse.SearchResult, + ) + + +class CreateConversationRequest(proto.Message): + r"""Request for CreateConversation method. + + Attributes: + parent (str): + Required. Full resource name of parent data store. Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` + conversation (google.cloud.discoveryengine_v1.types.Conversation): + Required. The conversation to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + conversation: gcd_conversation.Conversation = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_conversation.Conversation, + ) + + +class UpdateConversationRequest(proto.Message): + r"""Request for UpdateConversation method. + + Attributes: + conversation (google.cloud.discoveryengine_v1.types.Conversation): + Required. The Conversation to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [Conversation][google.cloud.discoveryengine.v1.Conversation] + to update. The following are NOT supported: + + - [conversation.name][] + + If not set or empty, all supported fields are updated. + """ + + conversation: gcd_conversation.Conversation = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_conversation.Conversation, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteConversationRequest(proto.Message): + r"""Request for DeleteConversation method. + + Attributes: + name (str): + Required. The resource name of the Conversation to delete. + Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetConversationRequest(proto.Message): + r"""Request for GetConversation method. + + Attributes: + name (str): + Required. The resource name of the Conversation to get. + Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListConversationsRequest(proto.Message): + r"""Request for ListConversations method. + + Attributes: + parent (str): + Required. The data store resource name. Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` + page_size (int): + Maximum number of results to return. If + unspecified, defaults to 50. Max allowed value + is 1000. + page_token (str): + A page token, received from a previous ``ListConversations`` + call. Provide this to retrieve the subsequent page. + filter (str): + A filter to apply on the list results. The supported + features are: user_pseudo_id, state. + + Example: "user_pseudo_id = some_id". + order_by (str): + A comma-separated list of fields to order by, sorted in + ascending order. Use "desc" after a field name for + descending. Supported fields: + + - ``update_time`` + - ``create_time`` + - ``conversation_name`` + + Example: "update_time desc" "create_time". + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListConversationsResponse(proto.Message): + r"""Response for ListConversations method. + + Attributes: + conversations (MutableSequence[google.cloud.discoveryengine_v1.types.Conversation]): + All the Conversations for a given data store. + next_page_token (str): + Pagination token, if not returned indicates + the last page. + """ + + @property + def raw_page(self): + return self + + conversations: MutableSequence[gcd_conversation.Conversation] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_conversation.Conversation, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/document.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/document.py new file mode 100644 index 000000000000..a53c978fb7b8 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/document.py @@ -0,0 +1,189 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1', + manifest={ + 'Document', + }, +) + + +class Document(proto.Message): + r"""Document captures all raw metadata information of items to be + recommended or searched. + + 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: + struct_data (google.protobuf.struct_pb2.Struct): + The structured JSON data for the document. It should conform + to the registered + [Schema][google.cloud.discoveryengine.v1.Schema] or an + ``INVALID_ARGUMENT`` error is thrown. + + This field is a member of `oneof`_ ``data``. + json_data (str): + The JSON string representation of the document. It should + conform to the registered + [Schema][google.cloud.discoveryengine.v1.Schema] or an + ``INVALID_ARGUMENT`` error is thrown. + + This field is a member of `oneof`_ ``data``. + name (str): + Immutable. The full resource name of the document. Format: + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document_id}``. + + This field must be a UTF-8 encoded string with a length + limit of 1024 characters. + id (str): + Immutable. The identifier of the document. + + Id should conform to + `RFC-1034 `__ standard + with a length limit of 63 characters. + schema_id (str): + The identifier of the schema located in the + same data store. + content (google.cloud.discoveryengine_v1.types.Document.Content): + The unstructured data linked to this document. Content must + be set if this document is under a ``CONTENT_REQUIRED`` data + store. + parent_document_id (str): + The identifier of the parent document. Currently supports at + most two level document hierarchy. + + Id should conform to + `RFC-1034 `__ standard + with a length limit of 63 characters. + derived_struct_data (google.protobuf.struct_pb2.Struct): + Output only. This field is OUTPUT_ONLY. It contains derived + data that are not in the original input document. + """ + + class Content(proto.Message): + r"""Unstructured data linked to this document. + + 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: + raw_bytes (bytes): + The content represented as a stream of bytes. The maximum + length is 1,000,000 bytes (1 MB / ~0.95 MiB). + + Note: As with all ``bytes`` fields, this field is + represented as pure binary in Protocol Buffers and + base64-encoded string in JSON. For example, + ``abc123!?$*&()'-=@~`` should be represented as + ``YWJjMTIzIT8kKiYoKSctPUB+`` in JSON. See + https://developers.google.com/protocol-buffers/docs/proto3#json. + + This field is a member of `oneof`_ ``content``. + uri (str): + The URI of the content. Only Cloud Storage URIs (e.g. + ``gs://bucket-name/path/to/file``) are supported. The + maximum file size is 100 MB. + + This field is a member of `oneof`_ ``content``. + mime_type (str): + The MIME type of the content. Supported types: + + - ``application/pdf`` (PDF, only native PDFs are supported + for now) + - ``text/html`` (HTML) + - ``application/vnd.openxmlformats-officedocument.wordprocessingml.document`` + (DOCX) + - ``application/vnd.openxmlformats-officedocument.presentationml.presentation`` + (PPTX) + - ``text/plain`` (TXT) + + See + https://www.iana.org/assignments/media-types/media-types.xhtml. + """ + + raw_bytes: bytes = proto.Field( + proto.BYTES, + number=2, + oneof='content', + ) + uri: str = proto.Field( + proto.STRING, + number=3, + oneof='content', + ) + mime_type: str = proto.Field( + proto.STRING, + number=1, + ) + + struct_data: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=4, + oneof='data', + message=struct_pb2.Struct, + ) + json_data: str = proto.Field( + proto.STRING, + number=5, + oneof='data', + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + id: str = proto.Field( + proto.STRING, + number=2, + ) + schema_id: str = proto.Field( + proto.STRING, + number=3, + ) + content: Content = proto.Field( + proto.MESSAGE, + number=10, + message=Content, + ) + parent_document_id: str = proto.Field( + proto.STRING, + number=7, + ) + derived_struct_data: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=6, + message=struct_pb2.Struct, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/document_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/document_service.py new file mode 100644 index 000000000000..f998f8bef4c3 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/document_service.py @@ -0,0 +1,262 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.discoveryengine_v1.types import document as gcd_document + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1', + manifest={ + 'GetDocumentRequest', + 'ListDocumentsRequest', + 'ListDocumentsResponse', + 'CreateDocumentRequest', + 'UpdateDocumentRequest', + 'DeleteDocumentRequest', + }, +) + + +class GetDocumentRequest(proto.Message): + r"""Request message for + [DocumentService.GetDocument][google.cloud.discoveryengine.v1.DocumentService.GetDocument] + method. + + Attributes: + name (str): + Required. Full resource name of + [Document][google.cloud.discoveryengine.v1.Document], such + as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. + + If the caller does not have permission to access the + [Document][google.cloud.discoveryengine.v1.Document], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the requested + [Document][google.cloud.discoveryengine.v1.Document] does + not exist, a ``NOT_FOUND`` error is returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListDocumentsRequest(proto.Message): + r"""Request message for + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1.DocumentService.ListDocuments] + method. + + Attributes: + parent (str): + Required. The parent branch resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. + Use ``default_branch`` as the branch ID, to list documents + under the default branch. + + If the caller does not have permission to list + [Document][google.cloud.discoveryengine.v1.Document]s under + this branch, regardless of whether or not this branch + exists, a ``PERMISSION_DENIED`` error is returned. + page_size (int): + Maximum number of + [Document][google.cloud.discoveryengine.v1.Document]s to + return. If unspecified, defaults to 100. The maximum allowed + value is 1000. Values above 1000 will be coerced to 1000. + + If this field is negative, an ``INVALID_ARGUMENT`` error is + returned. + page_token (str): + A page token + [ListDocumentsResponse.next_page_token][google.cloud.discoveryengine.v1.ListDocumentsResponse.next_page_token], + received from a previous + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1.DocumentService.ListDocuments] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1.DocumentService.ListDocuments] + must match the call that provided the page token. Otherwise, + an ``INVALID_ARGUMENT`` error is returned. + """ + + 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 ListDocumentsResponse(proto.Message): + r"""Response message for + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1.DocumentService.ListDocuments] + method. + + Attributes: + documents (MutableSequence[google.cloud.discoveryengine_v1.types.Document]): + The [Document][google.cloud.discoveryengine.v1.Document]s. + next_page_token (str): + A token that can be sent as + [ListDocumentsRequest.page_token][google.cloud.discoveryengine.v1.ListDocumentsRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + documents: MutableSequence[gcd_document.Document] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_document.Document, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateDocumentRequest(proto.Message): + r"""Request message for + [DocumentService.CreateDocument][google.cloud.discoveryengine.v1.DocumentService.CreateDocument] + method. + + Attributes: + parent (str): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. + document (google.cloud.discoveryengine_v1.types.Document): + Required. The + [Document][google.cloud.discoveryengine.v1.Document] to + create. + document_id (str): + Required. The ID to use for the + [Document][google.cloud.discoveryengine.v1.Document], which + will become the final component of the + [Document.name][google.cloud.discoveryengine.v1.Document.name]. + + If the caller does not have permission to create the + [Document][google.cloud.discoveryengine.v1.Document], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + This field must be unique among all + [Document][google.cloud.discoveryengine.v1.Document]s with + the same + [parent][google.cloud.discoveryengine.v1.CreateDocumentRequest.parent]. + Otherwise, an ``ALREADY_EXISTS`` error is returned. + + This field must conform to + `RFC-1034 `__ standard + with a length limit of 63 characters. Otherwise, an + ``INVALID_ARGUMENT`` error is returned. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + document: gcd_document.Document = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_document.Document, + ) + document_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateDocumentRequest(proto.Message): + r"""Request message for + [DocumentService.UpdateDocument][google.cloud.discoveryengine.v1.DocumentService.UpdateDocument] + method. + + Attributes: + document (google.cloud.discoveryengine_v1.types.Document): + Required. The document to update/create. + + If the caller does not have permission to update the + [Document][google.cloud.discoveryengine.v1.Document], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the [Document][google.cloud.discoveryengine.v1.Document] + to update does not exist and + [allow_missing][google.cloud.discoveryengine.v1.UpdateDocumentRequest.allow_missing] + is not set, a ``NOT_FOUND`` error is returned. + allow_missing (bool): + If set to true, and the + [Document][google.cloud.discoveryengine.v1.Document] is not + found, a new + [Document][google.cloud.discoveryengine.v1.Document] will be + created. + """ + + document: gcd_document.Document = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_document.Document, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class DeleteDocumentRequest(proto.Message): + r"""Request message for + [DocumentService.DeleteDocument][google.cloud.discoveryengine.v1.DocumentService.DeleteDocument] + method. + + Attributes: + name (str): + Required. Full resource name of + [Document][google.cloud.discoveryengine.v1.Document], such + as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. + + If the caller does not have permission to delete the + [Document][google.cloud.discoveryengine.v1.Document], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the [Document][google.cloud.discoveryengine.v1.Document] + to delete does not exist, a ``NOT_FOUND`` error is returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/import_config.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/import_config.py new file mode 100644 index 000000000000..b5a383b3d8ad --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/import_config.py @@ -0,0 +1,604 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.discoveryengine_v1.types import document +from google.cloud.discoveryengine_v1.types import user_event +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import date_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1', + manifest={ + 'GcsSource', + 'BigQuerySource', + 'ImportErrorConfig', + 'ImportUserEventsRequest', + 'ImportUserEventsResponse', + 'ImportUserEventsMetadata', + 'ImportDocumentsMetadata', + 'ImportDocumentsRequest', + 'ImportDocumentsResponse', + }, +) + + +class GcsSource(proto.Message): + r"""Cloud Storage location for input content. + + Attributes: + input_uris (MutableSequence[str]): + Required. Cloud Storage URIs to input files. URI can be up + to 2000 characters long. URIs can match the full object path + (for example, ``gs://bucket/directory/object.json``) or a + pattern matching one or more files, such as + ``gs://bucket/directory/*.json``. + + A request can contain at most 100 files (or 100,000 files if + ``data_schema`` is ``content``). Each file can be up to 2 GB + (or 100 MB if ``data_schema`` is ``content``). + data_schema (str): + The schema to use when parsing the data from the source. + + Supported values for document imports: + + - ``document`` (default): One JSON + [Document][google.cloud.discoveryengine.v1.Document] per + line. Each document must have a valid + [Document.id][google.cloud.discoveryengine.v1.Document.id]. + - ``content``: Unstructured data (e.g. PDF, HTML). Each + file matched by ``input_uris`` becomes a document, with + the ID set to the first 128 bits of SHA256(URI) encoded + as a hex string. + - ``custom``: One custom data JSON per row in arbitrary + format that conforms to the defined + [Schema][google.cloud.discoveryengine.v1.Schema] of the + data store. This can only be used by Gen App Builder. + - ``csv``: A CSV file with header conforming to the defined + [Schema][google.cloud.discoveryengine.v1.Schema] of the + data store. Each entry after the header is imported as a + Document. This can only be used by Gen App Builder. + + Supported values for user even imports: + + - ``user_event`` (default): One JSON + [UserEvent][google.cloud.discoveryengine.v1.UserEvent] + per line. + """ + + input_uris: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + data_schema: str = proto.Field( + proto.STRING, + number=2, + ) + + +class BigQuerySource(proto.Message): + r"""BigQuery source import data from. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + partition_date (google.type.date_pb2.Date): + BigQuery time partitioned table's \_PARTITIONDATE in + YYYY-MM-DD format. + + This field is a member of `oneof`_ ``partition``. + project_id (str): + The project ID (can be project # or ID) that + the BigQuery source is in with a length limit of + 128 characters. If not specified, inherits the + project ID from the parent request. + dataset_id (str): + Required. The BigQuery data set to copy the + data from with a length limit of 1,024 + characters. + table_id (str): + Required. The BigQuery table to copy the data + from with a length limit of 1,024 characters. + gcs_staging_dir (str): + Intermediate Cloud Storage directory used for + the import with a length limit of 2,000 + characters. Can be specified if one wants to + have the BigQuery export to a specific Cloud + Storage directory. + data_schema (str): + The schema to use when parsing the data from the source. + + Supported values for user event imports: + + - ``user_event`` (default): One + [UserEvent][google.cloud.discoveryengine.v1.UserEvent] + per row. + + Supported values for document imports: + + - ``document`` (default): One + [Document][google.cloud.discoveryengine.v1.Document] + format per row. Each document must have a valid + [Document.id][google.cloud.discoveryengine.v1.Document.id] + and one of + [Document.json_data][google.cloud.discoveryengine.v1.Document.json_data] + or + [Document.struct_data][google.cloud.discoveryengine.v1.Document.struct_data]. + - ``custom``: One custom data per row in arbitrary format + that conforms to the defined + [Schema][google.cloud.discoveryengine.v1.Schema] of the + data store. This can only be used by Gen App Builder. + """ + + partition_date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=5, + oneof='partition', + message=date_pb2.Date, + ) + project_id: str = proto.Field( + proto.STRING, + number=1, + ) + dataset_id: str = proto.Field( + proto.STRING, + number=2, + ) + table_id: str = proto.Field( + proto.STRING, + number=3, + ) + gcs_staging_dir: str = proto.Field( + proto.STRING, + number=4, + ) + data_schema: str = proto.Field( + proto.STRING, + number=6, + ) + + +class ImportErrorConfig(proto.Message): + r"""Configuration of destination for Import related errors. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_prefix (str): + Cloud Storage prefix for import errors. This must be an + empty, existing Cloud Storage directory. Import errors are + written to sharded files in this directory, one per line, as + a JSON-encoded ``google.rpc.Status`` message. + + This field is a member of `oneof`_ ``destination``. + """ + + gcs_prefix: str = proto.Field( + proto.STRING, + number=1, + oneof='destination', + ) + + +class ImportUserEventsRequest(proto.Message): + r"""Request message for the ImportUserEvents request. + + 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: + inline_source (google.cloud.discoveryengine_v1.types.ImportUserEventsRequest.InlineSource): + The Inline source for the input content for + UserEvents. + + This field is a member of `oneof`_ ``source``. + gcs_source (google.cloud.discoveryengine_v1.types.GcsSource): + Cloud Storage location for the input content. + + This field is a member of `oneof`_ ``source``. + bigquery_source (google.cloud.discoveryengine_v1.types.BigQuerySource): + BigQuery input source. + + This field is a member of `oneof`_ ``source``. + parent (str): + Required. Parent DataStore resource name, of the form + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}`` + error_config (google.cloud.discoveryengine_v1.types.ImportErrorConfig): + The desired location of errors incurred + during the Import. Cannot be set for inline user + event imports. + """ + + class InlineSource(proto.Message): + r"""The inline source for the input config for ImportUserEvents + method. + + Attributes: + user_events (MutableSequence[google.cloud.discoveryengine_v1.types.UserEvent]): + Required. A list of user events to import. + Recommended max of 10k items. + """ + + user_events: MutableSequence[user_event.UserEvent] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=user_event.UserEvent, + ) + + inline_source: InlineSource = proto.Field( + proto.MESSAGE, + number=2, + oneof='source', + message=InlineSource, + ) + gcs_source: 'GcsSource' = proto.Field( + proto.MESSAGE, + number=3, + oneof='source', + message='GcsSource', + ) + bigquery_source: 'BigQuerySource' = proto.Field( + proto.MESSAGE, + number=4, + oneof='source', + message='BigQuerySource', + ) + parent: str = proto.Field( + proto.STRING, + number=1, + ) + error_config: 'ImportErrorConfig' = proto.Field( + proto.MESSAGE, + number=5, + message='ImportErrorConfig', + ) + + +class ImportUserEventsResponse(proto.Message): + r"""Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is returned by the + google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (MutableSequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + error_config (google.cloud.discoveryengine_v1.types.ImportErrorConfig): + Echoes the destination for the complete + errors if this field was set in the request. + joined_events_count (int): + Count of user events imported with complete + existing Documents. + unjoined_events_count (int): + Count of user events imported, but with + Document information not found in the existing + Branch. + """ + + error_samples: MutableSequence[status_pb2.Status] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + error_config: 'ImportErrorConfig' = proto.Field( + proto.MESSAGE, + number=2, + message='ImportErrorConfig', + ) + joined_events_count: int = proto.Field( + proto.INT64, + number=3, + ) + unjoined_events_count: int = proto.Field( + proto.INT64, + number=4, + ) + + +class ImportUserEventsMetadata(proto.Message): + r"""Metadata related to the progress of the Import operation. + This is returned by the google.longrunning.Operation.metadata + field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + success_count (int): + Count of entries that were processed + successfully. + failure_count (int): + Count of entries that encountered errors + while processing. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + success_count: int = proto.Field( + proto.INT64, + number=3, + ) + failure_count: int = proto.Field( + proto.INT64, + number=4, + ) + + +class ImportDocumentsMetadata(proto.Message): + r"""Metadata related to the progress of the ImportDocuments + operation. This is returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + success_count (int): + Count of entries that were processed + successfully. + failure_count (int): + Count of entries that encountered errors + while processing. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + success_count: int = proto.Field( + proto.INT64, + number=3, + ) + failure_count: int = proto.Field( + proto.INT64, + number=4, + ) + + +class ImportDocumentsRequest(proto.Message): + r"""Request message for Import methods. + + 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: + inline_source (google.cloud.discoveryengine_v1.types.ImportDocumentsRequest.InlineSource): + The Inline source for the input content for + documents. + + This field is a member of `oneof`_ ``source``. + gcs_source (google.cloud.discoveryengine_v1.types.GcsSource): + Cloud Storage location for the input content. + + This field is a member of `oneof`_ ``source``. + bigquery_source (google.cloud.discoveryengine_v1.types.BigQuerySource): + BigQuery input source. + + This field is a member of `oneof`_ ``source``. + parent (str): + Required. The parent branch resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. + Requires create/update permission. + error_config (google.cloud.discoveryengine_v1.types.ImportErrorConfig): + The desired location of errors incurred + during the Import. + reconciliation_mode (google.cloud.discoveryengine_v1.types.ImportDocumentsRequest.ReconciliationMode): + The mode of reconciliation between existing documents and + the documents to be imported. Defaults to + [ReconciliationMode.INCREMENTAL][google.cloud.discoveryengine.v1.ImportDocumentsRequest.ReconciliationMode.INCREMENTAL]. + auto_generate_ids (bool): + Whether to automatically generate IDs for the documents if + absent. + + If set to ``true``, + [Document.id][google.cloud.discoveryengine.v1.Document.id]s + are automatically generated based on the hash of the + payload, where IDs may not be consistent during multiple + imports. In which case + [ReconciliationMode.FULL][google.cloud.discoveryengine.v1.ImportDocumentsRequest.ReconciliationMode.FULL] + is highly recommended to avoid duplicate contents. If unset + or set to ``false``, + [Document.id][google.cloud.discoveryengine.v1.Document.id]s + have to be specified using + [id_field][google.cloud.discoveryengine.v1.ImportDocumentsRequest.id_field], + otherwise, documents without IDs fail to be imported. + + Only set this field when using + [GcsSource][google.cloud.discoveryengine.v1.GcsSource] or + [BigQuerySource][google.cloud.discoveryengine.v1.BigQuerySource], + and when + [GcsSource.data_schema][google.cloud.discoveryengine.v1.GcsSource.data_schema] + or + [BigQuerySource.data_schema][google.cloud.discoveryengine.v1.BigQuerySource.data_schema] + is ``custom`` or ``csv``. Otherwise, an INVALID_ARGUMENT + error is thrown. + id_field (str): + The field in the Cloud Storage and BigQuery sources that + indicates the unique IDs of the documents. + + For [GcsSource][google.cloud.discoveryengine.v1.GcsSource] + it is the key of the JSON field. For instance, ``my_id`` for + JSON ``{"my_id": "some_uuid"}``. For + [BigQuerySource][google.cloud.discoveryengine.v1.BigQuerySource] + it is the column name of the BigQuery table where the unique + ids are stored. + + The values of the JSON field or the BigQuery column are used + as the + [Document.id][google.cloud.discoveryengine.v1.Document.id]s. + The JSON field or the BigQuery column must be of string + type, and the values must be set as valid strings conform to + `RFC-1034 `__ with 1-63 + characters. Otherwise, documents without valid IDs fail to + be imported. + + Only set this field when using + [GcsSource][google.cloud.discoveryengine.v1.GcsSource] or + [BigQuerySource][google.cloud.discoveryengine.v1.BigQuerySource], + and when + [GcsSource.data_schema][google.cloud.discoveryengine.v1.GcsSource.data_schema] + or + [BigQuerySource.data_schema][google.cloud.discoveryengine.v1.BigQuerySource.data_schema] + is ``custom``. And only set this field when + [auto_generate_ids][google.cloud.discoveryengine.v1.ImportDocumentsRequest.auto_generate_ids] + is unset or set as ``false``. Otherwise, an INVALID_ARGUMENT + error is thrown. + + If it is unset, a default value ``_id`` is used when + importing from the allowed data sources. + """ + class ReconciliationMode(proto.Enum): + r"""Indicates how imported documents are reconciled with the + existing documents created or imported before. + + Values: + RECONCILIATION_MODE_UNSPECIFIED (0): + Defaults to ``INCREMENTAL``. + INCREMENTAL (1): + Inserts new documents or updates existing + documents. + FULL (2): + Calculates diff and replaces the entire + document dataset. Existing documents may be + deleted if they are not present in the source + location. + """ + RECONCILIATION_MODE_UNSPECIFIED = 0 + INCREMENTAL = 1 + FULL = 2 + + class InlineSource(proto.Message): + r"""The inline source for the input config for ImportDocuments + method. + + Attributes: + documents (MutableSequence[google.cloud.discoveryengine_v1.types.Document]): + Required. A list of documents to update/create. Each + document must have a valid + [Document.id][google.cloud.discoveryengine.v1.Document.id]. + Recommended max of 100 items. + """ + + documents: MutableSequence[document.Document] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=document.Document, + ) + + inline_source: InlineSource = proto.Field( + proto.MESSAGE, + number=2, + oneof='source', + message=InlineSource, + ) + gcs_source: 'GcsSource' = proto.Field( + proto.MESSAGE, + number=3, + oneof='source', + message='GcsSource', + ) + bigquery_source: 'BigQuerySource' = proto.Field( + proto.MESSAGE, + number=4, + oneof='source', + message='BigQuerySource', + ) + parent: str = proto.Field( + proto.STRING, + number=1, + ) + error_config: 'ImportErrorConfig' = proto.Field( + proto.MESSAGE, + number=5, + message='ImportErrorConfig', + ) + reconciliation_mode: ReconciliationMode = proto.Field( + proto.ENUM, + number=6, + enum=ReconciliationMode, + ) + auto_generate_ids: bool = proto.Field( + proto.BOOL, + number=8, + ) + id_field: str = proto.Field( + proto.STRING, + number=9, + ) + + +class ImportDocumentsResponse(proto.Message): + r"""Response of the + [ImportDocumentsRequest][google.cloud.discoveryengine.v1.ImportDocumentsRequest]. + If the long running operation is done, then this message is returned + by the google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (MutableSequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + error_config (google.cloud.discoveryengine_v1.types.ImportErrorConfig): + Echoes the destination for the complete + errors in the request if set. + """ + + error_samples: MutableSequence[status_pb2.Status] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + error_config: 'ImportErrorConfig' = proto.Field( + proto.MESSAGE, + number=2, + message='ImportErrorConfig', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/purge_config.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/purge_config.py new file mode 100644 index 000000000000..0a2d90e89a28 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/purge_config.py @@ -0,0 +1,133 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1', + manifest={ + 'PurgeDocumentsRequest', + 'PurgeDocumentsResponse', + 'PurgeDocumentsMetadata', + }, +) + + +class PurgeDocumentsRequest(proto.Message): + r"""Request message for + [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1.DocumentService.PurgeDocuments] + method. + + Attributes: + parent (str): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. + filter (str): + Required. Filter matching documents to purge. Only currently + supported value is ``*`` (all items). + force (bool): + Actually performs the purge. If ``force`` is set to false, + return the expected purge count without deleting any + documents. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + force: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class PurgeDocumentsResponse(proto.Message): + r"""Response message for + [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1.DocumentService.PurgeDocuments] + method. If the long running operation is successfully done, then + this message is returned by the + google.longrunning.Operations.response field. + + Attributes: + purge_count (int): + The total count of documents purged as a + result of the operation. + purge_sample (MutableSequence[str]): + A sample of document names that will be deleted. Only + populated if ``force`` is set to false. A max of 100 names + will be returned and the names are chosen at random. + """ + + purge_count: int = proto.Field( + proto.INT64, + number=1, + ) + purge_sample: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class PurgeDocumentsMetadata(proto.Message): + r"""Metadata related to the progress of the PurgeDocuments + operation. This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + success_count (int): + Count of entries that were deleted + successfully. + failure_count (int): + Count of entries that encountered errors + while processing. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + success_count: int = proto.Field( + proto.INT64, + number=3, + ) + failure_count: int = proto.Field( + proto.INT64, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/schema.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/schema.py new file mode 100644 index 000000000000..a2ca29c61266 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/schema.py @@ -0,0 +1,78 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1', + manifest={ + 'Schema', + }, +) + + +class Schema(proto.Message): + r"""Defines the structure and layout of a type of document data. + + 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: + struct_schema (google.protobuf.struct_pb2.Struct): + The structured representation of the schema. + + This field is a member of `oneof`_ ``schema``. + json_schema (str): + The JSON representation of the schema. + + This field is a member of `oneof`_ ``schema``. + name (str): + Immutable. The full resource name of the schema, in the + format of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. + + This field must be a UTF-8 encoded string with a length + limit of 1024 characters. + """ + + struct_schema: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=2, + oneof='schema', + message=struct_pb2.Struct, + ) + json_schema: str = proto.Field( + proto.STRING, + number=3, + oneof='schema', + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/schema_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/schema_service.py new file mode 100644 index 000000000000..c5d4330960b1 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/schema_service.py @@ -0,0 +1,289 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.discoveryengine_v1.types import schema as gcd_schema +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1', + manifest={ + 'GetSchemaRequest', + 'ListSchemasRequest', + 'ListSchemasResponse', + 'CreateSchemaRequest', + 'UpdateSchemaRequest', + 'DeleteSchemaRequest', + 'CreateSchemaMetadata', + 'UpdateSchemaMetadata', + 'DeleteSchemaMetadata', + }, +) + + +class GetSchemaRequest(proto.Message): + r"""Request message for + [SchemaService.GetSchema][google.cloud.discoveryengine.v1.SchemaService.GetSchema] + method. + + Attributes: + name (str): + Required. The full resource name of the schema, in the + format of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListSchemasRequest(proto.Message): + r"""Request message for + [SchemaService.ListSchemas][google.cloud.discoveryengine.v1.SchemaService.ListSchemas] + method. + + Attributes: + parent (str): + Required. The parent data store resource name, in the format + of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. + page_size (int): + The maximum number of + [Schema][google.cloud.discoveryengine.v1.Schema]s to return. + The service may return fewer than this value. + + If unspecified, at most 100 + [Schema][google.cloud.discoveryengine.v1.Schema]s will be + returned. + + The maximum value is 1000; values above 1000 will be coerced + to 1000. + page_token (str): + A page token, received from a previous + [SchemaService.ListSchemas][google.cloud.discoveryengine.v1.SchemaService.ListSchemas] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [SchemaService.ListSchemas][google.cloud.discoveryengine.v1.SchemaService.ListSchemas] + 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 ListSchemasResponse(proto.Message): + r"""Response message for + [SchemaService.ListSchemas][google.cloud.discoveryengine.v1.SchemaService.ListSchemas] + method. + + Attributes: + schemas (MutableSequence[google.cloud.discoveryengine_v1.types.Schema]): + The [Schema][google.cloud.discoveryengine.v1.Schema]s. + next_page_token (str): + A token that can be sent as + [ListSchemasRequest.page_token][google.cloud.discoveryengine.v1.ListSchemasRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + schemas: MutableSequence[gcd_schema.Schema] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_schema.Schema, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateSchemaRequest(proto.Message): + r"""Request message for + [SchemaService.CreateSchema][google.cloud.discoveryengine.v1.SchemaService.CreateSchema] + method. + + Attributes: + parent (str): + Required. The parent data store resource name, in the format + of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. + schema (google.cloud.discoveryengine_v1.types.Schema): + Required. The + [Schema][google.cloud.discoveryengine.v1.Schema] to create. + schema_id (str): + Required. The ID to use for the + [Schema][google.cloud.discoveryengine.v1.Schema], which will + become the final component of the + [Schema.name][google.cloud.discoveryengine.v1.Schema.name]. + + This field should conform to + `RFC-1034 `__ standard + with a length limit of 63 characters. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + schema: gcd_schema.Schema = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_schema.Schema, + ) + schema_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateSchemaRequest(proto.Message): + r"""Request message for + [SchemaService.UpdateSchema][google.cloud.discoveryengine.v1.SchemaService.UpdateSchema] + method. + + Attributes: + schema (google.cloud.discoveryengine_v1.types.Schema): + Required. The + [Schema][google.cloud.discoveryengine.v1.Schema] to update. + allow_missing (bool): + If set to true, and the + [Schema][google.cloud.discoveryengine.v1.Schema] is not + found, a new + [Schema][google.cloud.discoveryengine.v1.Schema] will be + created. In this situation, ``update_mask`` is ignored. + """ + + schema: gcd_schema.Schema = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_schema.Schema, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class DeleteSchemaRequest(proto.Message): + r"""Request message for + [SchemaService.DeleteSchema][google.cloud.discoveryengine.v1.SchemaService.DeleteSchema] + method. + + Attributes: + name (str): + Required. The full resource name of the schema, in the + format of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateSchemaMetadata(proto.Message): + r"""Metadata for Create Schema LRO. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class UpdateSchemaMetadata(proto.Message): + r"""Metadata for UpdateSchema LRO. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class DeleteSchemaMetadata(proto.Message): + r"""Metadata for DeleteSchema LRO. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/search_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/search_service.py new file mode 100644 index 000000000000..b1189fdf4dc5 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/search_service.py @@ -0,0 +1,1089 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.discoveryengine_v1.types import common +from google.cloud.discoveryengine_v1.types import document as gcd_document +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1', + manifest={ + 'SearchRequest', + 'SearchResponse', + }, +) + + +class SearchRequest(proto.Message): + r"""Request message for + [SearchService.Search][google.cloud.discoveryengine.v1.SearchService.Search] + method. + + Attributes: + serving_config (str): + Required. The resource name of the Search serving config, + such as + ``projects/*/locations/global/collections/default_collection/dataStores/default_data_store/servingConfigs/default_serving_config``. + This field is used to identify the serving configuration + name, set of models used to make the search. + branch (str): + The branch resource name, such as + ``projects/*/locations/global/collections/default_collection/dataStores/default_data_store/branches/0``. + + Use ``default_branch`` as the branch ID or leave this field + empty, to search documents under the default branch. + query (str): + Raw search query. + image_query (google.cloud.discoveryengine_v1.types.SearchRequest.ImageQuery): + Raw image query. + page_size (int): + Maximum number of + [Document][google.cloud.discoveryengine.v1.Document]s to + return. If unspecified, defaults to a reasonable value. The + maximum allowed value is 100. Values above 100 are coerced + to 100. + + If this field is negative, an ``INVALID_ARGUMENT`` is + returned. + page_token (str): + A page token received from a previous + [SearchService.Search][google.cloud.discoveryengine.v1.SearchService.Search] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [SearchService.Search][google.cloud.discoveryengine.v1.SearchService.Search] + must match the call that provided the page token. Otherwise, + an ``INVALID_ARGUMENT`` error is returned. + offset (int): + A 0-indexed integer that specifies the current offset (that + is, starting result location, amongst the + [Document][google.cloud.discoveryengine.v1.Document]s deemed + by the API as relevant) in search results. This field is + only considered if + [page_token][google.cloud.discoveryengine.v1.SearchRequest.page_token] + is unset. + + If this field is negative, an ``INVALID_ARGUMENT`` is + returned. + filter (str): + The filter syntax consists of an expression language for + constructing a predicate from one or more fields of the + documents being filtered. Filter expression is + case-sensitive. + + If this field is unrecognizable, an ``INVALID_ARGUMENT`` is + returned. + order_by (str): + The order in which documents are returned. Documents can be + ordered by a field in an + [Document][google.cloud.discoveryengine.v1.Document] object. + Leave it unset if ordered by relevance. ``order_by`` + expression is case-sensitive. + + If this field is unrecognizable, an ``INVALID_ARGUMENT`` is + returned. + user_info (google.cloud.discoveryengine_v1.types.UserInfo): + Information about the end user. Highly recommended for + analytics. + [UserInfo.user_agent][google.cloud.discoveryengine.v1.UserInfo.user_agent] + is used to deduce ``device_type`` for analytics. + facet_specs (MutableSequence[google.cloud.discoveryengine_v1.types.SearchRequest.FacetSpec]): + Facet specifications for faceted search. If empty, no facets + are returned. + + A maximum of 100 values are allowed. Otherwise, an + ``INVALID_ARGUMENT`` error is returned. + boost_spec (google.cloud.discoveryengine_v1.types.SearchRequest.BoostSpec): + Boost specification to boost certain + documents. + params (MutableMapping[str, google.protobuf.struct_pb2.Value]): + Additional search parameters. + + For public website search only, supported values are: + + - ``user_country_code``: string. Default empty. If set to + non-empty, results are restricted or boosted based on the + location provided. + - ``search_type``: double. Default empty. Enables + non-webpage searching depending on the value. The only + valid non-default value is 1, which enables image + searching. + query_expansion_spec (google.cloud.discoveryengine_v1.types.SearchRequest.QueryExpansionSpec): + The query expansion specification that + specifies the conditions under which query + expansion occurs. + spell_correction_spec (google.cloud.discoveryengine_v1.types.SearchRequest.SpellCorrectionSpec): + The spell correction specification that + specifies the mode under which spell correction + takes effect. + user_pseudo_id (str): + A unique identifier for tracking visitors. For example, this + could be implemented with an HTTP cookie, which should be + able to uniquely identify a visitor on a single device. This + unique identifier should not change if the visitor logs in + or out of the website. + + This field should NOT have a fixed value such as + ``unknown_visitor``. + + This should be the same identifier as + [UserEvent.user_pseudo_id][google.cloud.discoveryengine.v1.UserEvent.user_pseudo_id] + and + [CompleteQueryRequest.user_pseudo_id][google.cloud.discoveryengine.v1.CompleteQueryRequest.user_pseudo_id] + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an ``INVALID_ARGUMENT`` error + is returned. + content_search_spec (google.cloud.discoveryengine_v1.types.SearchRequest.ContentSearchSpec): + A specification for configuring the behavior + of content search. + safe_search (bool): + Whether to turn on safe search. This is only + supported for website search. + user_labels (MutableMapping[str, str]): + The user labels applied to a resource must meet the + following requirements: + + - Each resource can have multiple labels, up to a maximum + of 64. + - Each label must be a key-value pair. + - Keys have a minimum length of 1 character and a maximum + length of 63 characters and cannot be empty. Values can + be empty and have a maximum length of 63 characters. + - Keys and values can contain only lowercase letters, + numeric characters, underscores, and dashes. All + characters must use UTF-8 encoding, and international + characters are allowed. + - The key portion of a label must be unique. However, you + can use the same key with multiple resources. + - Keys must start with a lowercase letter or international + character. + + See `Google Cloud + Document `__ + for more details. + """ + + class ImageQuery(proto.Message): + r"""Specifies the image query input. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + image_bytes (str): + Base64 encoded image bytes. Supported image + formats: JPEG, PNG, and BMP. + + This field is a member of `oneof`_ ``image``. + """ + + image_bytes: str = proto.Field( + proto.STRING, + number=1, + oneof='image', + ) + + class FacetSpec(proto.Message): + r"""A facet specification to perform faceted search. + + Attributes: + facet_key (google.cloud.discoveryengine_v1.types.SearchRequest.FacetSpec.FacetKey): + Required. The facet key specification. + limit (int): + Maximum of facet values that should be returned for this + facet. If unspecified, defaults to 20. The maximum allowed + value is 300. Values above 300 are coerced to 300. + + If this field is negative, an ``INVALID_ARGUMENT`` is + returned. + excluded_filter_keys (MutableSequence[str]): + List of keys to exclude when faceting. + + By default, + [FacetKey.key][google.cloud.discoveryengine.v1.SearchRequest.FacetSpec.FacetKey.key] + is not excluded from the filter unless it is listed in this + field. + + Listing a facet key in this field allows its values to + appear as facet results, even when they are filtered out of + search results. Using this field does not affect what search + results are returned. + + For example, suppose there are 100 documents with the color + facet "Red" and 200 documents with the color facet "Blue". A + query containing the filter "color:ANY("Red")" and having + "color" as + [FacetKey.key][google.cloud.discoveryengine.v1.SearchRequest.FacetSpec.FacetKey.key] + would by default return only "Red" documents in the search + results, and also return "Red" with count 100 as the only + color facet. Although there are also blue documents + available, "Blue" would not be shown as an available facet + value. + + If "color" is listed in "excludedFilterKeys", then the query + returns the facet values "Red" with count 100 and "Blue" + with count 200, because the "color" key is now excluded from + the filter. Because this field doesn't affect search + results, the search results are still correctly filtered to + return only "Red" documents. + + A maximum of 100 values are allowed. Otherwise, an + ``INVALID_ARGUMENT`` error is returned. + enable_dynamic_position (bool): + Enables dynamic position for this facet. If set to true, the + position of this facet among all facets in the response is + determined automatically. If dynamic facets are enabled, it + is ordered together. If set to false, the position of this + facet in the response is the same as in the request, and it + is ranked before the facets with dynamic position enable and + all dynamic facets. + + For example, you may always want to have rating facet + returned in the response, but it's not necessarily to always + display the rating facet at the top. In that case, you can + set enable_dynamic_position to true so that the position of + rating facet in response is determined automatically. + + Another example, assuming you have the following facets in + the request: + + - "rating", enable_dynamic_position = true + + - "price", enable_dynamic_position = false + + - "brands", enable_dynamic_position = false + + And also you have a dynamic facets enabled, which generates + a facet ``gender``. Then the final order of the facets in + the response can be ("price", "brands", "rating", "gender") + or ("price", "brands", "gender", "rating") depends on how + API orders "gender" and "rating" facets. However, notice + that "price" and "brands" are always ranked at first and + second position because their enable_dynamic_position is + false. + """ + + class FacetKey(proto.Message): + r"""Specifies how a facet is computed. + + Attributes: + key (str): + Required. Supported textual and numerical facet keys in + [Document][google.cloud.discoveryengine.v1.Document] object, + over which the facet values are computed. Facet key is + case-sensitive. + intervals (MutableSequence[google.cloud.discoveryengine_v1.types.Interval]): + Set only if values should be bucketed into + intervals. Must be set for facets with numerical + values. Must not be set for facet with text + values. Maximum number of intervals is 30. + restricted_values (MutableSequence[str]): + Only get facet for the given restricted values. Only + supported on textual fields. For example, suppose "category" + has three values "Action > 2022", "Action > 2021" and + "Sci-Fi > 2022". If set "restricted_values" to "Action > + 2022", the "category" facet only contains "Action > 2022". + Only supported on textual fields. Maximum is 10. + prefixes (MutableSequence[str]): + Only get facet values that start with the + given string prefix. For example, suppose + "category" has three values "Action > 2022", + "Action > 2021" and "Sci-Fi > 2022". If set + "prefixes" to "Action", the "category" facet + only contains "Action > 2022" and "Action > + 2021". Only supported on textual fields. Maximum + is 10. + contains (MutableSequence[str]): + Only get facet values that contains the given + strings. For example, suppose "category" has + three values "Action > 2022", "Action > 2021" + and "Sci-Fi > 2022". If set "contains" to + "2022", the "category" facet only contains + "Action > 2022" and "Sci-Fi > 2022". Only + supported on textual fields. Maximum is 10. + case_insensitive (bool): + True to make facet keys case insensitive when + getting faceting values with prefixes or + contains; false otherwise. + order_by (str): + The order in which documents are returned. + + Allowed values are: + + - "count desc", which means order by + [SearchResponse.Facet.values.count][google.cloud.discoveryengine.v1.SearchResponse.Facet.FacetValue.count] + descending. + + - "value desc", which means order by + [SearchResponse.Facet.values.value][google.cloud.discoveryengine.v1.SearchResponse.Facet.FacetValue.value] + descending. Only applies to textual facets. + + If not set, textual values are sorted in `natural + order `__; + numerical intervals are sorted in the order given by + [FacetSpec.FacetKey.intervals][google.cloud.discoveryengine.v1.SearchRequest.FacetSpec.FacetKey.intervals]. + """ + + key: str = proto.Field( + proto.STRING, + number=1, + ) + intervals: MutableSequence[common.Interval] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=common.Interval, + ) + restricted_values: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + prefixes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + contains: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + case_insensitive: bool = proto.Field( + proto.BOOL, + number=6, + ) + order_by: str = proto.Field( + proto.STRING, + number=7, + ) + + facet_key: 'SearchRequest.FacetSpec.FacetKey' = proto.Field( + proto.MESSAGE, + number=1, + message='SearchRequest.FacetSpec.FacetKey', + ) + limit: int = proto.Field( + proto.INT32, + number=2, + ) + excluded_filter_keys: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + enable_dynamic_position: bool = proto.Field( + proto.BOOL, + number=4, + ) + + class BoostSpec(proto.Message): + r"""Boost specification to boost certain documents. + + Attributes: + condition_boost_specs (MutableSequence[google.cloud.discoveryengine_v1.types.SearchRequest.BoostSpec.ConditionBoostSpec]): + Condition boost specifications. If a document + matches multiple conditions in the + specifictions, boost scores from these + specifications are all applied and combined in a + non-linear way. Maximum number of specifications + is 20. + """ + + class ConditionBoostSpec(proto.Message): + r"""Boost applies to documents which match a condition. + + Attributes: + condition (str): + An expression which specifies a boost condition. The syntax + and supported fields are the same as a filter expression. + See + [SearchRequest.filter][google.cloud.discoveryengine.v1.SearchRequest.filter] + for detail syntax and limitations. + + Examples: + + - To boost documents with document ID "doc_1" or "doc_2", + and color "Red" or "Blue": + + - (id: ANY("doc_1", "doc_2")) AND (color: + ANY("Red","Blue")) + boost (float): + Strength of the condition boost, which should be in [-1, 1]. + Negative boost means demotion. Default is 0.0. + + Setting to 1.0 gives the document a big promotion. However, + it does not necessarily mean that the boosted document will + be the top result at all times, nor that other documents + will be excluded. Results could still be shown even when + none of them matches the condition. And results that are + significantly more relevant to the search query can still + trump your heavily favored but irrelevant documents. + + Setting to -1.0 gives the document a big demotion. However, + results that are deeply relevant might still be shown. The + document will have an upstream battle to get a fairly high + ranking, but it is not blocked out completely. + + Setting to 0.0 means no boost applied. The boosting + condition is ignored. + """ + + condition: str = proto.Field( + proto.STRING, + number=1, + ) + boost: float = proto.Field( + proto.FLOAT, + number=2, + ) + + condition_boost_specs: MutableSequence['SearchRequest.BoostSpec.ConditionBoostSpec'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SearchRequest.BoostSpec.ConditionBoostSpec', + ) + + class QueryExpansionSpec(proto.Message): + r"""Specification to determine under which conditions query + expansion should occur. + + Attributes: + condition (google.cloud.discoveryengine_v1.types.SearchRequest.QueryExpansionSpec.Condition): + The condition under which query expansion should occur. + Default to + [Condition.DISABLED][google.cloud.discoveryengine.v1.SearchRequest.QueryExpansionSpec.Condition.DISABLED]. + pin_unexpanded_results (bool): + Whether to pin unexpanded results. If this + field is set to true, unexpanded products are + always at the top of the search results, + followed by the expanded results. + """ + class Condition(proto.Enum): + r"""Enum describing under which condition query expansion should + occur. + + Values: + CONDITION_UNSPECIFIED (0): + Unspecified query expansion condition. In this case, server + behavior defaults to + [Condition.DISABLED][google.cloud.discoveryengine.v1.SearchRequest.QueryExpansionSpec.Condition.DISABLED]. + DISABLED (1): + Disabled query expansion. Only the exact search query is + used, even if + [SearchResponse.total_size][google.cloud.discoveryengine.v1.SearchResponse.total_size] + is zero. + AUTO (2): + Automatic query expansion built by the Search + API. + """ + CONDITION_UNSPECIFIED = 0 + DISABLED = 1 + AUTO = 2 + + condition: 'SearchRequest.QueryExpansionSpec.Condition' = proto.Field( + proto.ENUM, + number=1, + enum='SearchRequest.QueryExpansionSpec.Condition', + ) + pin_unexpanded_results: bool = proto.Field( + proto.BOOL, + number=2, + ) + + class SpellCorrectionSpec(proto.Message): + r"""The specification for query spell correction. + + Attributes: + mode (google.cloud.discoveryengine_v1.types.SearchRequest.SpellCorrectionSpec.Mode): + The mode under which spell correction should take effect to + replace the original search query. Default to + [Mode.AUTO][google.cloud.discoveryengine.v1.SearchRequest.SpellCorrectionSpec.Mode.AUTO]. + """ + class Mode(proto.Enum): + r"""Enum describing under which mode spell correction should + occur. + + Values: + MODE_UNSPECIFIED (0): + Unspecified spell correction mode. In this case, server + behavior defaults to + [Mode.AUTO][google.cloud.discoveryengine.v1.SearchRequest.SpellCorrectionSpec.Mode.AUTO]. + SUGGESTION_ONLY (1): + Search API will try to find a spell suggestion if there is + any and put in the + [SearchResponse.corrected_query][google.cloud.discoveryengine.v1.SearchResponse.corrected_query]. + The spell suggestion will not be used as the search query. + AUTO (2): + Automatic spell correction built by the + Search API. Search will be based on the + corrected query if found. + """ + MODE_UNSPECIFIED = 0 + SUGGESTION_ONLY = 1 + AUTO = 2 + + mode: 'SearchRequest.SpellCorrectionSpec.Mode' = proto.Field( + proto.ENUM, + number=1, + enum='SearchRequest.SpellCorrectionSpec.Mode', + ) + + class ContentSearchSpec(proto.Message): + r"""A specification for configuring the behavior of content + search. + + Attributes: + snippet_spec (google.cloud.discoveryengine_v1.types.SearchRequest.ContentSearchSpec.SnippetSpec): + If ``snippetSpec`` is not specified, snippets are not + included in the search response. + summary_spec (google.cloud.discoveryengine_v1.types.SearchRequest.ContentSearchSpec.SummarySpec): + If ``summarySpec`` is not specified, summaries are not + included in the search response. + """ + + class SnippetSpec(proto.Message): + r"""A specification for configuring snippets in a search + response. + + Attributes: + max_snippet_count (int): + [DEPRECATED] This field is deprecated. To control snippet + return, use ``return_snippet`` field. For backwards + compatibility, we will return snippet if max_snippet_count > + 0. + reference_only (bool): + [DEPRECATED] This field is deprecated and will have no + affect on the snippet. + return_snippet (bool): + If ``true``, then return snippet. If no snippet can be + generated, we return "No snippet is available for this + page." A ``snippet_status`` with ``SUCCESS`` or + ``NO_SNIPPET_AVAILABLE`` will also be returned. + """ + + max_snippet_count: int = proto.Field( + proto.INT32, + number=1, + ) + reference_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + return_snippet: bool = proto.Field( + proto.BOOL, + number=3, + ) + + class SummarySpec(proto.Message): + r"""A specification for configuring a summary returned in a + search response. + + Attributes: + summary_result_count (int): + The number of top results to generate the summary from. If + the number of results returned is less than + ``summaryResultCount``, the summary is generated from all of + the results. + + At most five results can be used to generate a summary. + include_citations (bool): + Specifies whether to include citations in the summary. The + default value is ``false``. + + When this field is set to ``true``, summaries include + in-line citation numbers. + + Example summary including citations: + + BigQuery is Google Cloud's fully managed and completely + serverless enterprise data warehouse [1]. BigQuery supports + all data types, works across clouds, and has built-in + machine learning and business intelligence, all within a + unified platform [2, 3]. + + The citation numbers refer to the returned search results + and are 1-indexed. For example, [1] means that the sentence + is attributed to the first search result. [2, 3] means that + the sentence is attributed to both the second and third + search results. + ignore_adversarial_query (bool): + Specifies whether to filter out adversarial queries. The + default value is ``false``. + + Google employs search-query classification to detect + adversarial queries. No summary is returned if the search + query is classified as an adversarial query. For example, a + user might ask a question regarding negative comments about + the company or submit a query designed to generate unsafe, + policy-violating output. If this field is set to ``true``, + we skip generating summaries for adversarial queries and + return fallback messages instead. + ignore_non_summary_seeking_query (bool): + Specifies whether to filter out queries that are not + summary-seeking. The default value is ``false``. + + Google employs search-query classification to detect + summary-seeking queries. No summary is returned if the + search query is classified as a non-summary seeking query. + For example, ``why is the sky blue`` and + ``Who is the best soccer player in the world?`` are + summary-seeking queries, but ``SFO airport`` and + ``world cup 2026`` are not. They are most likely + navigational queries. If this field is set to ``true``, we + skip generating summaries for non-summary seeking queries + and return fallback messages instead. + language_code (str): + Language code for Summary. Use language tags defined by + [BCP47][https://www.rfc-editor.org/rfc/bcp/bcp47.txt]. + """ + + summary_result_count: int = proto.Field( + proto.INT32, + number=1, + ) + include_citations: bool = proto.Field( + proto.BOOL, + number=2, + ) + ignore_adversarial_query: bool = proto.Field( + proto.BOOL, + number=3, + ) + ignore_non_summary_seeking_query: bool = proto.Field( + proto.BOOL, + number=4, + ) + language_code: str = proto.Field( + proto.STRING, + number=6, + ) + + snippet_spec: 'SearchRequest.ContentSearchSpec.SnippetSpec' = proto.Field( + proto.MESSAGE, + number=1, + message='SearchRequest.ContentSearchSpec.SnippetSpec', + ) + summary_spec: 'SearchRequest.ContentSearchSpec.SummarySpec' = proto.Field( + proto.MESSAGE, + number=2, + message='SearchRequest.ContentSearchSpec.SummarySpec', + ) + + serving_config: str = proto.Field( + proto.STRING, + number=1, + ) + branch: str = proto.Field( + proto.STRING, + number=2, + ) + query: str = proto.Field( + proto.STRING, + number=3, + ) + image_query: ImageQuery = proto.Field( + proto.MESSAGE, + number=19, + message=ImageQuery, + ) + page_size: int = proto.Field( + proto.INT32, + number=4, + ) + page_token: str = proto.Field( + proto.STRING, + number=5, + ) + offset: int = proto.Field( + proto.INT32, + number=6, + ) + filter: str = proto.Field( + proto.STRING, + number=7, + ) + order_by: str = proto.Field( + proto.STRING, + number=8, + ) + user_info: common.UserInfo = proto.Field( + proto.MESSAGE, + number=21, + message=common.UserInfo, + ) + facet_specs: MutableSequence[FacetSpec] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message=FacetSpec, + ) + boost_spec: BoostSpec = proto.Field( + proto.MESSAGE, + number=10, + message=BoostSpec, + ) + params: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=11, + message=struct_pb2.Value, + ) + query_expansion_spec: QueryExpansionSpec = proto.Field( + proto.MESSAGE, + number=13, + message=QueryExpansionSpec, + ) + spell_correction_spec: SpellCorrectionSpec = proto.Field( + proto.MESSAGE, + number=14, + message=SpellCorrectionSpec, + ) + user_pseudo_id: str = proto.Field( + proto.STRING, + number=15, + ) + content_search_spec: ContentSearchSpec = proto.Field( + proto.MESSAGE, + number=24, + message=ContentSearchSpec, + ) + safe_search: bool = proto.Field( + proto.BOOL, + number=20, + ) + user_labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=22, + ) + + +class SearchResponse(proto.Message): + r"""Response message for + [SearchService.Search][google.cloud.discoveryengine.v1.SearchService.Search] + method. + + Attributes: + results (MutableSequence[google.cloud.discoveryengine_v1.types.SearchResponse.SearchResult]): + A list of matched documents. The order + represents the ranking. + facets (MutableSequence[google.cloud.discoveryengine_v1.types.SearchResponse.Facet]): + Results of facets requested by user. + total_size (int): + The estimated total count of matched items irrespective of + pagination. The count of + [results][google.cloud.discoveryengine.v1.SearchResponse.results] + returned by pagination may be less than the + [total_size][google.cloud.discoveryengine.v1.SearchResponse.total_size] + that matches. + attribution_token (str): + A unique search token. This should be included in the + [UserEvent][google.cloud.discoveryengine.v1.UserEvent] logs + resulting from this search, which enables accurate + attribution of search model performance. + redirect_uri (str): + The URI of a customer-defined redirect page. If redirect + action is triggered, no search is performed, and only + [redirect_uri][google.cloud.discoveryengine.v1.SearchResponse.redirect_uri] + and + [attribution_token][google.cloud.discoveryengine.v1.SearchResponse.attribution_token] + are set in the response. + next_page_token (str): + A token that can be sent as + [SearchRequest.page_token][google.cloud.discoveryengine.v1.SearchRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + corrected_query (str): + Contains the spell corrected query, if found. If the spell + correction type is AUTOMATIC, then the search results are + based on corrected_query. Otherwise the original query is + used for search. + summary (google.cloud.discoveryengine_v1.types.SearchResponse.Summary): + A summary as part of the search results. This field is only + returned if + [SearchRequest.ContentSearchSpec.summary_spec][google.cloud.discoveryengine.v1.SearchRequest.ContentSearchSpec.summary_spec] + is set. + query_expansion_info (google.cloud.discoveryengine_v1.types.SearchResponse.QueryExpansionInfo): + Query expansion information for the returned + results. + """ + + class SearchResult(proto.Message): + r"""Represents the search results. + + Attributes: + id (str): + [Document.id][google.cloud.discoveryengine.v1.Document.id] + of the searched + [Document][google.cloud.discoveryengine.v1.Document]. + document (google.cloud.discoveryengine_v1.types.Document): + The document data snippet in the search + response. Only fields that are marked as + retrievable are populated. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + document: gcd_document.Document = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_document.Document, + ) + + class Facet(proto.Message): + r"""A facet result. + + Attributes: + key (str): + The key for this facet. E.g., "colors" or "price". It + matches + [SearchRequest.FacetSpec.FacetKey.key][google.cloud.discoveryengine.v1.SearchRequest.FacetSpec.FacetKey.key]. + values (MutableSequence[google.cloud.discoveryengine_v1.types.SearchResponse.Facet.FacetValue]): + The facet values for this field. + dynamic_facet (bool): + Whether the facet is dynamically generated. + """ + + class FacetValue(proto.Message): + r"""A facet value which contains value names and their count. + + 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: + value (str): + Text value of a facet, such as "Black" for + facet "colors". + + This field is a member of `oneof`_ ``facet_value``. + interval (google.cloud.discoveryengine_v1.types.Interval): + Interval value for a facet, such as [10, 20) for facet + "price". It matches + [SearchRequest.FacetSpec.FacetKey.intervals][google.cloud.discoveryengine.v1.SearchRequest.FacetSpec.FacetKey.intervals]. + + This field is a member of `oneof`_ ``facet_value``. + count (int): + Number of items that have this facet value. + """ + + value: str = proto.Field( + proto.STRING, + number=1, + oneof='facet_value', + ) + interval: common.Interval = proto.Field( + proto.MESSAGE, + number=2, + oneof='facet_value', + message=common.Interval, + ) + count: int = proto.Field( + proto.INT64, + number=3, + ) + + key: str = proto.Field( + proto.STRING, + number=1, + ) + values: MutableSequence['SearchResponse.Facet.FacetValue'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='SearchResponse.Facet.FacetValue', + ) + dynamic_facet: bool = proto.Field( + proto.BOOL, + number=3, + ) + + class Summary(proto.Message): + r"""Summary of the top N search result specified by the summary + spec. + + Attributes: + summary_text (str): + The summary content. + summary_skipped_reasons (MutableSequence[google.cloud.discoveryengine_v1.types.SearchResponse.Summary.SummarySkippedReason]): + Additional summary-skipped reasons. This + provides the reason for ignored cases. If + nothing is skipped, this field is not set. + safety_attributes (google.cloud.discoveryengine_v1.types.SearchResponse.Summary.SafetyAttributes): + A collection of Safety Attribute categories + and their associated confidence scores. + """ + class SummarySkippedReason(proto.Enum): + r"""An Enum for summary-skipped reasons. + + Values: + SUMMARY_SKIPPED_REASON_UNSPECIFIED (0): + Default value. The summary skipped reason is + not specified. + ADVERSARIAL_QUERY_IGNORED (1): + The adversarial query ignored case. + + Only populated when + [SummarySpec.ignore_adversarial_query][google.cloud.discoveryengine.v1.SearchRequest.ContentSearchSpec.SummarySpec.ignore_adversarial_query] + is set to ``true``. + NON_SUMMARY_SEEKING_QUERY_IGNORED (2): + The non-summary seeking query ignored case. + + Only populated when + [SummarySpec.ignore_non_summary_seeking_query][google.cloud.discoveryengine.v1.SearchRequest.ContentSearchSpec.SummarySpec.ignore_non_summary_seeking_query] + is set to ``true``. + OUT_OF_DOMAIN_QUERY_IGNORED (3): + The out-of-domain query ignored case. + + Google skips the summary if there are no + high-relevance search results. For example, the + data store contains facts about company A but + the user query is asking questions about company + B. + POTENTIAL_POLICY_VIOLATION (4): + The potential policy violation case. + + Google skips the summary if there is a potential + policy violation detected. This includes content + that may be violent or toxic. + LLM_ADDON_NOT_ENABLED (5): + The LLM addon not enabled case. + + Google skips the summary if the LLM addon is not + enabled. + """ + SUMMARY_SKIPPED_REASON_UNSPECIFIED = 0 + ADVERSARIAL_QUERY_IGNORED = 1 + NON_SUMMARY_SEEKING_QUERY_IGNORED = 2 + OUT_OF_DOMAIN_QUERY_IGNORED = 3 + POTENTIAL_POLICY_VIOLATION = 4 + LLM_ADDON_NOT_ENABLED = 5 + + class SafetyAttributes(proto.Message): + r"""Safety Attribute categories and their associated confidence + scores. + + Attributes: + categories (MutableSequence[str]): + The display names of Safety Attribute + categories associated with the generated + content. Order matches the Scores. + scores (MutableSequence[float]): + The confidence scores of the each category, + higher value means higher confidence. Order + matches the Categories. + """ + + categories: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + scores: MutableSequence[float] = proto.RepeatedField( + proto.FLOAT, + number=2, + ) + + summary_text: str = proto.Field( + proto.STRING, + number=1, + ) + summary_skipped_reasons: MutableSequence['SearchResponse.Summary.SummarySkippedReason'] = proto.RepeatedField( + proto.ENUM, + number=2, + enum='SearchResponse.Summary.SummarySkippedReason', + ) + safety_attributes: 'SearchResponse.Summary.SafetyAttributes' = proto.Field( + proto.MESSAGE, + number=3, + message='SearchResponse.Summary.SafetyAttributes', + ) + + class QueryExpansionInfo(proto.Message): + r"""Information describing query expansion including whether + expansion has occurred. + + Attributes: + expanded_query (bool): + Bool describing whether query expansion has + occurred. + pinned_result_count (int): + Number of pinned results. This field will only be set when + expansion happens and + [SearchRequest.QueryExpansionSpec.pin_unexpanded_results][google.cloud.discoveryengine.v1.SearchRequest.QueryExpansionSpec.pin_unexpanded_results] + is set to true. + """ + + expanded_query: bool = proto.Field( + proto.BOOL, + number=1, + ) + pinned_result_count: int = proto.Field( + proto.INT64, + number=2, + ) + + @property + def raw_page(self): + return self + + results: MutableSequence[SearchResult] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=SearchResult, + ) + facets: MutableSequence[Facet] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Facet, + ) + total_size: int = proto.Field( + proto.INT32, + number=3, + ) + attribution_token: str = proto.Field( + proto.STRING, + number=4, + ) + redirect_uri: str = proto.Field( + proto.STRING, + number=12, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=5, + ) + corrected_query: str = proto.Field( + proto.STRING, + number=7, + ) + summary: Summary = proto.Field( + proto.MESSAGE, + number=9, + message=Summary, + ) + query_expansion_info: QueryExpansionInfo = proto.Field( + proto.MESSAGE, + number=14, + message=QueryExpansionInfo, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/user_event.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/user_event.py new file mode 100644 index 000000000000..2b309b8f2f08 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/user_event.py @@ -0,0 +1,754 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.discoveryengine_v1.types import common +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1', + manifest={ + 'UserEvent', + 'PageInfo', + 'SearchInfo', + 'CompletionInfo', + 'TransactionInfo', + 'DocumentInfo', + 'PanelInfo', + 'MediaInfo', + }, +) + + +class UserEvent(proto.Message): + r"""UserEvent captures all metadata information Discovery Engine + API needs to know about how end users interact with customers' + website. + + Attributes: + event_type (str): + Required. User event type. Allowed values are: + + Generic values: + + - ``search``: Search for Documents. + - ``view-item``: Detailed page view of a Document. + - ``view-item-list``: View of a panel or ordered list of + Documents. + - ``view-home-page``: View of the home page. + - ``view-category-page``: View of a category page, e.g. + Home > Men > Jeans + + Retail-related values: + + - ``add-to-cart``: Add an item(s) to cart, e.g. in Retail + online shopping + - ``purchase``: Purchase an item(s) + + Media-related values: + + - ``media-play``: Start/resume watching a video, playing a + song, etc. + - ``media-complete``: Finished or stopped midway through a + video, song, etc. + user_pseudo_id (str): + Required. A unique identifier for tracking visitors. + + For example, this could be implemented with an HTTP cookie, + which should be able to uniquely identify a visitor on a + single device. This unique identifier should not change if + the visitor log in/out of the website. + + Do not set the field to the same fixed ID for different + users. This mixes the event history of those users together, + which results in degraded model quality. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an ``INVALID_ARGUMENT`` error + is returned. + + The field should not contain PII or user-data. We recommend + to use Google Analytics `Client + ID `__ + for this field. + event_time (google.protobuf.timestamp_pb2.Timestamp): + Only required for + [UserEventService.ImportUserEvents][google.cloud.discoveryengine.v1.UserEventService.ImportUserEvents] + method. Timestamp of when the user event happened. + user_info (google.cloud.discoveryengine_v1.types.UserInfo): + Information about the end user. + direct_user_request (bool): + Should set to true if the request is made directly from the + end user, in which case the + [UserEvent.user_info.user_agent][google.cloud.discoveryengine.v1.UserInfo.user_agent] + can be populated from the HTTP request. + + This flag should be set only if the API request is made + directly from the end user such as a mobile app (and not if + a gateway or a server is processing and pushing the user + events). + + This should not be set when using the JavaScript tag in + [UserEventService.CollectUserEvent][google.cloud.discoveryengine.v1.UserEventService.CollectUserEvent]. + session_id (str): + A unique identifier for tracking a visitor session with a + length limit of 128 bytes. A session is an aggregation of an + end user behavior in a time span. + + A general guideline to populate the session_id: + + 1. If user has no activity for 30 min, a new session_id + should be assigned. + 2. The session_id should be unique across users, suggest use + uuid or add + [UserEvent.user_pseudo_id][google.cloud.discoveryengine.v1.UserEvent.user_pseudo_id] + as prefix. + page_info (google.cloud.discoveryengine_v1.types.PageInfo): + Page metadata such as categories and other critical + information for certain event types such as + ``view-category-page``. + attribution_token (str): + Token to attribute an API response to user action(s) to + trigger the event. + + Highly recommended for user events that are the result of + [RecommendationService.Recommend][]. This field enables + accurate attribution of recommendation model performance. + + The value must be one of: + + - [RecommendResponse.attribution_token][] for events that + are the result of [RecommendationService.Recommend][]. + - [SearchResponse.attribution_token][google.cloud.discoveryengine.v1.SearchResponse.attribution_token] + for events that are the result of + [SearchService.Search][google.cloud.discoveryengine.v1.SearchService.Search]. + + This token enables us to accurately attribute page view or + conversion completion back to the event and the particular + predict response containing this clicked/purchased product. + If user clicks on product K in the recommendation results, + pass [RecommendResponse.attribution_token][] as a URL + parameter to product K's page. When recording events on + product K's page, log the + [RecommendResponse.attribution_token][] to this field. + filter (str): + The filter syntax consists of an expression language for + constructing a predicate from one or more fields of the + documents being filtered. + + One example is for ``search`` events, the associated + [SearchRequest][google.cloud.discoveryengine.v1.SearchRequest] + may contain a filter expression in + [SearchRequest.filter][google.cloud.discoveryengine.v1.SearchRequest.filter] + conforming to https://google.aip.dev/160#filtering. + + Similarly, for ``view-item-list`` events that are generated + from a [RecommendationService.RecommendRequest][], this + field may be populated directly from + [RecommendationService.RecommendRequest.filter][] conforming + to https://google.aip.dev/160#filtering. + + The value must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an ``INVALID_ARGUMENT`` + error is returned. + documents (MutableSequence[google.cloud.discoveryengine_v1.types.DocumentInfo]): + List of + [Document][google.cloud.discoveryengine.v1.Document]s + associated with this user event. + + This field is optional except for the following event types: + + - ``view-item`` + - ``add-to-cart`` + - ``purchase`` + - ``media-play`` + - ``media-complete`` + + In a ``search`` event, this field represents the documents + returned to the end user on the current page (the end user + may have not finished browsing the whole page yet). When a + new page is returned to the end user, after + pagination/filtering/ordering even for the same query, a new + ``search`` event with different + [UserEvent.documents][google.cloud.discoveryengine.v1.UserEvent.documents] + is desired. + panel (google.cloud.discoveryengine_v1.types.PanelInfo): + Panel metadata associated with this user + event. + search_info (google.cloud.discoveryengine_v1.types.SearchInfo): + [SearchService.Search][google.cloud.discoveryengine.v1.SearchService.Search] + details related to the event. + + This field should be set for ``search`` event. + completion_info (google.cloud.discoveryengine_v1.types.CompletionInfo): + [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1.CompletionService.CompleteQuery] + details related to the event. + + This field should be set for ``search`` event when + autocomplete function is enabled and the user clicks a + suggestion for search. + transaction_info (google.cloud.discoveryengine_v1.types.TransactionInfo): + The transaction metadata (if any) associated + with this user event. + tag_ids (MutableSequence[str]): + A list of identifiers for the independent + experiment groups this user event belongs to. + This is used to distinguish between user events + associated with different experiment setups on + the customer end. + promotion_ids (MutableSequence[str]): + The promotion IDs if this is an event + associated with promotions. Currently, this + field is restricted to at most one ID. + attributes (MutableMapping[str, google.cloud.discoveryengine_v1.types.CustomAttribute]): + Extra user event features to include in the recommendation + model. These attributes must NOT contain data that needs to + be parsed or processed further, e.g. JSON or other + encodings. + + If you provide custom attributes for ingested user events, + also include them in the user events that you associate with + prediction requests. Custom attribute formatting must be + consistent between imported events and events provided with + prediction requests. This lets the Discovery Engine API use + those custom attributes when training models and serving + predictions, which helps improve recommendation quality. + + This field needs to pass all below criteria, otherwise an + ``INVALID_ARGUMENT`` error is returned: + + - The key must be a UTF-8 encoded string with a length + limit of 5,000 characters. + - For text attributes, at most 400 values are allowed. + Empty values are not allowed. Each value must be a UTF-8 + encoded string with a length limit of 256 characters. + - For number attributes, at most 400 values are allowed. + + For product recommendations, an example of extra user + information is ``traffic_channel``, which is how a user + arrives at the site. Users can arrive at the site by coming + to the site directly, coming through Google search, or in + other ways. + media_info (google.cloud.discoveryengine_v1.types.MediaInfo): + Media-specific info. + """ + + event_type: str = proto.Field( + proto.STRING, + number=1, + ) + user_pseudo_id: str = proto.Field( + proto.STRING, + number=2, + ) + event_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + user_info: common.UserInfo = proto.Field( + proto.MESSAGE, + number=4, + message=common.UserInfo, + ) + direct_user_request: bool = proto.Field( + proto.BOOL, + number=5, + ) + session_id: str = proto.Field( + proto.STRING, + number=6, + ) + page_info: 'PageInfo' = proto.Field( + proto.MESSAGE, + number=7, + message='PageInfo', + ) + attribution_token: str = proto.Field( + proto.STRING, + number=8, + ) + filter: str = proto.Field( + proto.STRING, + number=9, + ) + documents: MutableSequence['DocumentInfo'] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message='DocumentInfo', + ) + panel: 'PanelInfo' = proto.Field( + proto.MESSAGE, + number=11, + message='PanelInfo', + ) + search_info: 'SearchInfo' = proto.Field( + proto.MESSAGE, + number=12, + message='SearchInfo', + ) + completion_info: 'CompletionInfo' = proto.Field( + proto.MESSAGE, + number=13, + message='CompletionInfo', + ) + transaction_info: 'TransactionInfo' = proto.Field( + proto.MESSAGE, + number=14, + message='TransactionInfo', + ) + tag_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=15, + ) + promotion_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=16, + ) + attributes: MutableMapping[str, common.CustomAttribute] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=17, + message=common.CustomAttribute, + ) + media_info: 'MediaInfo' = proto.Field( + proto.MESSAGE, + number=18, + message='MediaInfo', + ) + + +class PageInfo(proto.Message): + r"""Detailed page information. + + Attributes: + pageview_id (str): + A unique ID of a web page view. + + This should be kept the same for all user events triggered + from the same pageview. For example, an item detail page + view could trigger multiple events as the user is browsing + the page. The ``pageview_id`` property should be kept the + same for all these events so that they can be grouped + together properly. + + When using the client side event reporting with JavaScript + pixel and Google Tag Manager, this value is filled in + automatically. + page_category (str): + The most specific category associated with a category page. + + To represent full path of category, use '>' sign to separate + different hierarchies. If '>' is part of the category name, + please replace it with other character(s). + + Category pages include special pages such as sales or + promotions. For instance, a special sale page may have the + category hierarchy: + ``"pageCategory" : "Sales > 2017 Black Friday Deals"``. + + Required for ``view-category-page`` events. Other event + types should not set this field. Otherwise, an + ``INVALID_ARGUMENT`` error is returned. + uri (str): + Complete URL (window.location.href) of the + user's current page. + When using the client side event reporting with + JavaScript pixel and Google Tag Manager, this + value is filled in automatically. Maximum length + 5,000 characters. + referrer_uri (str): + The referrer URL of the current page. + + When using the client side event reporting with + JavaScript pixel and Google Tag Manager, this + value is filled in automatically. However, some + browser privacy restrictions may cause this + field to be empty. + """ + + pageview_id: str = proto.Field( + proto.STRING, + number=1, + ) + page_category: str = proto.Field( + proto.STRING, + number=2, + ) + uri: str = proto.Field( + proto.STRING, + number=3, + ) + referrer_uri: str = proto.Field( + proto.STRING, + number=4, + ) + + +class SearchInfo(proto.Message): + r"""Detailed search information. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + search_query (str): + The user's search query. + + See + [SearchRequest.query][google.cloud.discoveryengine.v1.SearchRequest.query] + for definition. + + The value must be a UTF-8 encoded string with a length limit + of 5,000 characters. Otherwise, an ``INVALID_ARGUMENT`` + error is returned. + + At least one of + [search_query][google.cloud.discoveryengine.v1.SearchInfo.search_query] + or + [PageInfo.page_category][google.cloud.discoveryengine.v1.PageInfo.page_category] + is required for ``search`` events. Other event types should + not set this field. Otherwise, an ``INVALID_ARGUMENT`` error + is returned. + order_by (str): + The order in which products are returned, if applicable. + + See + [SearchRequest.order_by][google.cloud.discoveryengine.v1.SearchRequest.order_by] + for definition and syntax. + + The value must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an ``INVALID_ARGUMENT`` + error is returned. + + This can only be set for ``search`` events. Other event + types should not set this field. Otherwise, an + ``INVALID_ARGUMENT`` error is returned. + offset (int): + An integer that specifies the current offset for pagination + (the 0-indexed starting location, amongst the products + deemed by the API as relevant). + + See + [SearchRequest.offset][google.cloud.discoveryengine.v1.SearchRequest.offset] + for definition. + + If this field is negative, an ``INVALID_ARGUMENT`` is + returned. + + This can only be set for ``search`` events. Other event + types should not set this field. Otherwise, an + ``INVALID_ARGUMENT`` error is returned. + + This field is a member of `oneof`_ ``_offset``. + """ + + search_query: str = proto.Field( + proto.STRING, + number=1, + ) + order_by: str = proto.Field( + proto.STRING, + number=2, + ) + offset: int = proto.Field( + proto.INT32, + number=3, + optional=True, + ) + + +class CompletionInfo(proto.Message): + r"""Detailed completion information including completion + attribution token and clicked completion info. + + Attributes: + selected_suggestion (str): + End user selected + [CompleteQueryResponse.QuerySuggestion.suggestion][google.cloud.discoveryengine.v1.CompleteQueryResponse.QuerySuggestion.suggestion]. + selected_position (int): + End user selected + [CompleteQueryResponse.QuerySuggestion.suggestion][google.cloud.discoveryengine.v1.CompleteQueryResponse.QuerySuggestion.suggestion] + position, starting from 0. + """ + + selected_suggestion: str = proto.Field( + proto.STRING, + number=1, + ) + selected_position: int = proto.Field( + proto.INT32, + number=2, + ) + + +class TransactionInfo(proto.Message): + r"""A transaction represents the entire purchase transaction. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + value (float): + Required. Total non-zero value associated + with the transaction. This value may include + shipping, tax, or other adjustments to the total + value that you want to include. + + This field is a member of `oneof`_ ``_value``. + currency (str): + Required. Currency code. Use three-character + ISO-4217 code. + transaction_id (str): + The transaction ID with a length limit of 128 + characters. + tax (float): + All the taxes associated with the + transaction. + + This field is a member of `oneof`_ ``_tax``. + cost (float): + All the costs associated with the products. These can be + manufacturing costs, shipping expenses not borne by the end + user, or any other costs, such that: + + - Profit = + [value][google.cloud.discoveryengine.v1.TransactionInfo.value] + - + [tax][google.cloud.discoveryengine.v1.TransactionInfo.tax] + - + [cost][google.cloud.discoveryengine.v1.TransactionInfo.cost] + + This field is a member of `oneof`_ ``_cost``. + discount_value (float): + The total discount(s) value applied to this transaction. + This figure should be excluded from + [TransactionInfo.value][google.cloud.discoveryengine.v1.TransactionInfo.value] + + For example, if a user paid + [TransactionInfo.value][google.cloud.discoveryengine.v1.TransactionInfo.value] + amount, then nominal (pre-discount) value of the transaction + is the sum of + [TransactionInfo.value][google.cloud.discoveryengine.v1.TransactionInfo.value] + and + [TransactionInfo.discount_value][google.cloud.discoveryengine.v1.TransactionInfo.discount_value] + + This means that profit is calculated the same way, + regardless of the discount value, and that + [TransactionInfo.discount_value][google.cloud.discoveryengine.v1.TransactionInfo.discount_value] + can be larger than + [TransactionInfo.value][google.cloud.discoveryengine.v1.TransactionInfo.value]: + + - Profit = + [value][google.cloud.discoveryengine.v1.TransactionInfo.value] + - + [tax][google.cloud.discoveryengine.v1.TransactionInfo.tax] + - + [cost][google.cloud.discoveryengine.v1.TransactionInfo.cost] + + This field is a member of `oneof`_ ``_discount_value``. + """ + + value: float = proto.Field( + proto.FLOAT, + number=1, + optional=True, + ) + currency: str = proto.Field( + proto.STRING, + number=2, + ) + transaction_id: str = proto.Field( + proto.STRING, + number=3, + ) + tax: float = proto.Field( + proto.FLOAT, + number=4, + optional=True, + ) + cost: float = proto.Field( + proto.FLOAT, + number=5, + optional=True, + ) + discount_value: float = proto.Field( + proto.FLOAT, + number=6, + optional=True, + ) + + +class DocumentInfo(proto.Message): + r"""Detailed document information associated with a user event. + + 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: + id (str): + The [Document][google.cloud.discoveryengine.v1.Document] + resource ID. + + This field is a member of `oneof`_ ``document_descriptor``. + name (str): + The [Document][google.cloud.discoveryengine.v1.Document] + resource full name, of the form: + ``projects/{project_id}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}/branches/{branch_id}/documents/{document_id}`` + + This field is a member of `oneof`_ ``document_descriptor``. + uri (str): + The [Document][google.cloud.discoveryengine.v1.Document] URI + - only allowed for website data stores. + + This field is a member of `oneof`_ ``document_descriptor``. + quantity (int): + Quantity of the Document associated with the user event. + Defaults to 1. + + For example, this field will be 2 if two quantities of the + same Document are involved in a ``add-to-cart`` event. + + Required for events of the following event types: + + - ``add-to-cart`` + - ``purchase`` + + This field is a member of `oneof`_ ``_quantity``. + promotion_ids (MutableSequence[str]): + The promotion IDs associated with this + Document. Currently, this field is restricted to + at most one ID. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + oneof='document_descriptor', + ) + name: str = proto.Field( + proto.STRING, + number=2, + oneof='document_descriptor', + ) + uri: str = proto.Field( + proto.STRING, + number=6, + oneof='document_descriptor', + ) + quantity: int = proto.Field( + proto.INT32, + number=3, + optional=True, + ) + promotion_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + + +class PanelInfo(proto.Message): + r"""Detailed panel information associated with a user event. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + panel_id (str): + Required. The panel ID. + display_name (str): + The display name of the panel. + panel_position (int): + The ordered position of the panel, if shown to the user with + other panels. If set, then + [total_panels][google.cloud.discoveryengine.v1.PanelInfo.total_panels] + must also be set. + + This field is a member of `oneof`_ ``_panel_position``. + total_panels (int): + The total number of panels, including this one, shown to the + user. Must be set if + [panel_position][google.cloud.discoveryengine.v1.PanelInfo.panel_position] + is set. + + This field is a member of `oneof`_ ``_total_panels``. + """ + + panel_id: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + panel_position: int = proto.Field( + proto.INT32, + number=4, + optional=True, + ) + total_panels: int = proto.Field( + proto.INT32, + number=5, + optional=True, + ) + + +class MediaInfo(proto.Message): + r"""Media-specific user event information. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + media_progress_duration (google.protobuf.duration_pb2.Duration): + The media progress time in seconds, if applicable. For + example, if the end user has finished 90 seconds of a + playback video, then + [MediaInfo.media_progress_duration.seconds][google.protobuf.Duration.seconds] + should be set to 90. + media_progress_percentage (float): + Media progress should be computed using only the + [media_progress_duration][google.cloud.discoveryengine.v1.MediaInfo.media_progress_duration] + relative to the media total length. + + This value must be between ``[0, 1.0]`` inclusive. + + If this is not a playback or the progress cannot be computed + (e.g. ongoing livestream), this field should be unset. + + This field is a member of `oneof`_ ``_media_progress_percentage``. + """ + + media_progress_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + media_progress_percentage: float = proto.Field( + proto.FLOAT, + number=2, + optional=True, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/user_event_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/user_event_service.py new file mode 100644 index 000000000000..6ba8f47138eb --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/user_event_service.py @@ -0,0 +1,110 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.discoveryengine_v1.types import user_event as gcd_user_event + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1', + manifest={ + 'WriteUserEventRequest', + 'CollectUserEventRequest', + }, +) + + +class WriteUserEventRequest(proto.Message): + r"""Request message for WriteUserEvent method. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. The parent DataStore resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. + user_event (google.cloud.discoveryengine_v1.types.UserEvent): + Required. User event to write. + + This field is a member of `oneof`_ ``_user_event``. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + user_event: gcd_user_event.UserEvent = proto.Field( + proto.MESSAGE, + number=2, + optional=True, + message=gcd_user_event.UserEvent, + ) + + +class CollectUserEventRequest(proto.Message): + r"""Request message for CollectUserEvent method. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. The parent DataStore resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. + user_event (str): + Required. URL encoded UserEvent proto with a + length limit of 2,000,000 characters. + uri (str): + The URL including cgi-parameters but + excluding the hash fragment with a length limit + of 5,000 characters. This is often more useful + than the referer URL, because many browsers only + send the domain for third-party requests. + + This field is a member of `oneof`_ ``_uri``. + ets (int): + The event timestamp in milliseconds. This + prevents browser caching of otherwise identical + get requests. The name is abbreviated to reduce + the payload bytes. + + This field is a member of `oneof`_ ``_ets``. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + user_event: str = proto.Field( + proto.STRING, + number=2, + ) + uri: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + ets: int = proto.Field( + proto.INT64, + number=4, + optional=True, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/mypy.ini b/owl-bot-staging/google-cloud-discoveryengine/v1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/noxfile.py b/owl-bot-staging/google-cloud-discoveryengine/v1/noxfile.py new file mode 100644 index 000000000000..013a607914d2 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/noxfile.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.11" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/discoveryengine_v1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + 'mypy', + 'types-requests', + 'types-protobuf' + ) + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==7.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_completion_service_complete_query_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_completion_service_complete_query_async.py new file mode 100644 index 000000000000..dd296b1f8bec --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_completion_service_complete_query_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CompleteQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_CompletionService_CompleteQuery_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +async def sample_complete_query(): + # Create a client + client = discoveryengine_v1.CompletionServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.CompleteQueryRequest( + data_store="data_store_value", + query="query_value", + ) + + # Make the request + response = await client.complete_query(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1_generated_CompletionService_CompleteQuery_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_completion_service_complete_query_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_completion_service_complete_query_sync.py new file mode 100644 index 000000000000..8e2357df0dd7 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_completion_service_complete_query_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CompleteQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_CompletionService_CompleteQuery_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +def sample_complete_query(): + # Create a client + client = discoveryengine_v1.CompletionServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.CompleteQueryRequest( + data_store="data_store_value", + query="query_value", + ) + + # Make the request + response = client.complete_query(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1_generated_CompletionService_CompleteQuery_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_converse_conversation_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_converse_conversation_async.py new file mode 100644 index 000000000000..816c3b250de7 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_converse_conversation_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ConverseConversation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_ConversationalSearchService_ConverseConversation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +async def sample_converse_conversation(): + # Create a client + client = discoveryengine_v1.ConversationalSearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.ConverseConversationRequest( + name="name_value", + ) + + # Make the request + response = await client.converse_conversation(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1_generated_ConversationalSearchService_ConverseConversation_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_converse_conversation_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_converse_conversation_sync.py new file mode 100644 index 000000000000..7ee9ba54110c --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_converse_conversation_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ConverseConversation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_ConversationalSearchService_ConverseConversation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +def sample_converse_conversation(): + # Create a client + client = discoveryengine_v1.ConversationalSearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.ConverseConversationRequest( + name="name_value", + ) + + # Make the request + response = client.converse_conversation(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1_generated_ConversationalSearchService_ConverseConversation_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_create_conversation_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_create_conversation_async.py new file mode 100644 index 000000000000..ab3094fe6591 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_create_conversation_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateConversation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_ConversationalSearchService_CreateConversation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +async def sample_create_conversation(): + # Create a client + client = discoveryengine_v1.ConversationalSearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.CreateConversationRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_conversation(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1_generated_ConversationalSearchService_CreateConversation_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_create_conversation_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_create_conversation_sync.py new file mode 100644 index 000000000000..023d1d5ac2c2 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_create_conversation_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateConversation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_ConversationalSearchService_CreateConversation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +def sample_create_conversation(): + # Create a client + client = discoveryengine_v1.ConversationalSearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.CreateConversationRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_conversation(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1_generated_ConversationalSearchService_CreateConversation_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_delete_conversation_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_delete_conversation_async.py new file mode 100644 index 000000000000..b5149fbf7574 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_delete_conversation_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteConversation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_ConversationalSearchService_DeleteConversation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +async def sample_delete_conversation(): + # Create a client + client = discoveryengine_v1.ConversationalSearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.DeleteConversationRequest( + name="name_value", + ) + + # Make the request + await client.delete_conversation(request=request) + + +# [END discoveryengine_v1_generated_ConversationalSearchService_DeleteConversation_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_delete_conversation_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_delete_conversation_sync.py new file mode 100644 index 000000000000..b200a8c34650 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_delete_conversation_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteConversation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_ConversationalSearchService_DeleteConversation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +def sample_delete_conversation(): + # Create a client + client = discoveryengine_v1.ConversationalSearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.DeleteConversationRequest( + name="name_value", + ) + + # Make the request + client.delete_conversation(request=request) + + +# [END discoveryengine_v1_generated_ConversationalSearchService_DeleteConversation_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_get_conversation_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_get_conversation_async.py new file mode 100644 index 000000000000..4379c2ae855a --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_get_conversation_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetConversation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_ConversationalSearchService_GetConversation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +async def sample_get_conversation(): + # Create a client + client = discoveryengine_v1.ConversationalSearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.GetConversationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_conversation(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1_generated_ConversationalSearchService_GetConversation_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_get_conversation_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_get_conversation_sync.py new file mode 100644 index 000000000000..9685e1a75f86 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_get_conversation_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetConversation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_ConversationalSearchService_GetConversation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +def sample_get_conversation(): + # Create a client + client = discoveryengine_v1.ConversationalSearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.GetConversationRequest( + name="name_value", + ) + + # Make the request + response = client.get_conversation(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1_generated_ConversationalSearchService_GetConversation_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_list_conversations_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_list_conversations_async.py new file mode 100644 index 000000000000..5173cd8e1438 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_list_conversations_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListConversations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_ConversationalSearchService_ListConversations_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +async def sample_list_conversations(): + # Create a client + client = discoveryengine_v1.ConversationalSearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.ListConversationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_conversations(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END discoveryengine_v1_generated_ConversationalSearchService_ListConversations_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_list_conversations_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_list_conversations_sync.py new file mode 100644 index 000000000000..8677d2518cfa --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_list_conversations_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListConversations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_ConversationalSearchService_ListConversations_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +def sample_list_conversations(): + # Create a client + client = discoveryengine_v1.ConversationalSearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.ListConversationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_conversations(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END discoveryengine_v1_generated_ConversationalSearchService_ListConversations_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_update_conversation_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_update_conversation_async.py new file mode 100644 index 000000000000..f030ec185795 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_update_conversation_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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-discoveryengine + + +# [START discoveryengine_v1_generated_ConversationalSearchService_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 discoveryengine_v1 + + +async def sample_update_conversation(): + # Create a client + client = discoveryengine_v1.ConversationalSearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.UpdateConversationRequest( + ) + + # Make the request + response = await client.update_conversation(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1_generated_ConversationalSearchService_UpdateConversation_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_update_conversation_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_update_conversation_sync.py new file mode 100644 index 000000000000..b7a895b2c90b --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_update_conversation_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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-discoveryengine + + +# [START discoveryengine_v1_generated_ConversationalSearchService_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 discoveryengine_v1 + + +def sample_update_conversation(): + # Create a client + client = discoveryengine_v1.ConversationalSearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.UpdateConversationRequest( + ) + + # Make the request + response = client.update_conversation(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1_generated_ConversationalSearchService_UpdateConversation_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_create_document_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_create_document_async.py new file mode 100644 index 000000000000..a181b8613936 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_create_document_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateDocument +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_DocumentService_CreateDocument_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +async def sample_create_document(): + # Create a client + client = discoveryengine_v1.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.CreateDocumentRequest( + parent="parent_value", + document_id="document_id_value", + ) + + # Make the request + response = await client.create_document(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1_generated_DocumentService_CreateDocument_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_create_document_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_create_document_sync.py new file mode 100644 index 000000000000..22f9f29f516a --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_create_document_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateDocument +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_DocumentService_CreateDocument_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +def sample_create_document(): + # Create a client + client = discoveryengine_v1.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.CreateDocumentRequest( + parent="parent_value", + document_id="document_id_value", + ) + + # Make the request + response = client.create_document(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1_generated_DocumentService_CreateDocument_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_delete_document_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_delete_document_async.py new file mode 100644 index 000000000000..cebcfd6c60b1 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_delete_document_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteDocument +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_DocumentService_DeleteDocument_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +async def sample_delete_document(): + # Create a client + client = discoveryengine_v1.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.DeleteDocumentRequest( + name="name_value", + ) + + # Make the request + await client.delete_document(request=request) + + +# [END discoveryengine_v1_generated_DocumentService_DeleteDocument_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_delete_document_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_delete_document_sync.py new file mode 100644 index 000000000000..e9f56aae2e8b --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_delete_document_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteDocument +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_DocumentService_DeleteDocument_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +def sample_delete_document(): + # Create a client + client = discoveryengine_v1.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.DeleteDocumentRequest( + name="name_value", + ) + + # Make the request + client.delete_document(request=request) + + +# [END discoveryengine_v1_generated_DocumentService_DeleteDocument_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_get_document_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_get_document_async.py new file mode 100644 index 000000000000..9a6b33085029 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_get_document_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDocument +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_DocumentService_GetDocument_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +async def sample_get_document(): + # Create a client + client = discoveryengine_v1.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.GetDocumentRequest( + name="name_value", + ) + + # Make the request + response = await client.get_document(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1_generated_DocumentService_GetDocument_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_get_document_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_get_document_sync.py new file mode 100644 index 000000000000..35a409bd1698 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_get_document_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDocument +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_DocumentService_GetDocument_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +def sample_get_document(): + # Create a client + client = discoveryengine_v1.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.GetDocumentRequest( + name="name_value", + ) + + # Make the request + response = client.get_document(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1_generated_DocumentService_GetDocument_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_import_documents_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_import_documents_async.py new file mode 100644 index 000000000000..56a38712b91a --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_import_documents_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportDocuments +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_DocumentService_ImportDocuments_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +async def sample_import_documents(): + # Create a client + client = discoveryengine_v1.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.ImportDocumentsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.import_documents(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END discoveryengine_v1_generated_DocumentService_ImportDocuments_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_import_documents_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_import_documents_sync.py new file mode 100644 index 000000000000..e2c623f2be83 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_import_documents_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportDocuments +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_DocumentService_ImportDocuments_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +def sample_import_documents(): + # Create a client + client = discoveryengine_v1.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.ImportDocumentsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.import_documents(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END discoveryengine_v1_generated_DocumentService_ImportDocuments_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_list_documents_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_list_documents_async.py new file mode 100644 index 000000000000..7f05ac2f773f --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_list_documents_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDocuments +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_DocumentService_ListDocuments_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +async def sample_list_documents(): + # Create a client + client = discoveryengine_v1.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.ListDocumentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_documents(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END discoveryengine_v1_generated_DocumentService_ListDocuments_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_list_documents_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_list_documents_sync.py new file mode 100644 index 000000000000..d8becd95f391 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_list_documents_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDocuments +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_DocumentService_ListDocuments_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +def sample_list_documents(): + # Create a client + client = discoveryengine_v1.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.ListDocumentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_documents(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END discoveryengine_v1_generated_DocumentService_ListDocuments_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_purge_documents_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_purge_documents_async.py new file mode 100644 index 000000000000..6130f8ab9c23 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_purge_documents_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PurgeDocuments +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_DocumentService_PurgeDocuments_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +async def sample_purge_documents(): + # Create a client + client = discoveryengine_v1.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.PurgeDocumentsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_documents(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END discoveryengine_v1_generated_DocumentService_PurgeDocuments_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_purge_documents_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_purge_documents_sync.py new file mode 100644 index 000000000000..8c55663a89ce --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_purge_documents_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PurgeDocuments +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_DocumentService_PurgeDocuments_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +def sample_purge_documents(): + # Create a client + client = discoveryengine_v1.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.PurgeDocumentsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_documents(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END discoveryengine_v1_generated_DocumentService_PurgeDocuments_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_update_document_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_update_document_async.py new file mode 100644 index 000000000000..38823adc30dc --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_update_document_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateDocument +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_DocumentService_UpdateDocument_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +async def sample_update_document(): + # Create a client + client = discoveryengine_v1.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.UpdateDocumentRequest( + ) + + # Make the request + response = await client.update_document(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1_generated_DocumentService_UpdateDocument_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_update_document_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_update_document_sync.py new file mode 100644 index 000000000000..3831e7c83da4 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_update_document_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateDocument +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_DocumentService_UpdateDocument_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +def sample_update_document(): + # Create a client + client = discoveryengine_v1.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.UpdateDocumentRequest( + ) + + # Make the request + response = client.update_document(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1_generated_DocumentService_UpdateDocument_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_create_schema_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_create_schema_async.py new file mode 100644 index 000000000000..5db7f8cd3f68 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_create_schema_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_SchemaService_CreateSchema_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +async def sample_create_schema(): + # Create a client + client = discoveryengine_v1.SchemaServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.CreateSchemaRequest( + parent="parent_value", + schema_id="schema_id_value", + ) + + # Make the request + operation = client.create_schema(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END discoveryengine_v1_generated_SchemaService_CreateSchema_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_create_schema_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_create_schema_sync.py new file mode 100644 index 000000000000..c649d3018fc3 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_create_schema_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_SchemaService_CreateSchema_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +def sample_create_schema(): + # Create a client + client = discoveryengine_v1.SchemaServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.CreateSchemaRequest( + parent="parent_value", + schema_id="schema_id_value", + ) + + # Make the request + operation = client.create_schema(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END discoveryengine_v1_generated_SchemaService_CreateSchema_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_delete_schema_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_delete_schema_async.py new file mode 100644 index 000000000000..b96723396227 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_delete_schema_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_SchemaService_DeleteSchema_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +async def sample_delete_schema(): + # Create a client + client = discoveryengine_v1.SchemaServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.DeleteSchemaRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_schema(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END discoveryengine_v1_generated_SchemaService_DeleteSchema_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_delete_schema_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_delete_schema_sync.py new file mode 100644 index 000000000000..ed9a2f2bdc9b --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_delete_schema_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_SchemaService_DeleteSchema_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +def sample_delete_schema(): + # Create a client + client = discoveryengine_v1.SchemaServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.DeleteSchemaRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_schema(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END discoveryengine_v1_generated_SchemaService_DeleteSchema_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_get_schema_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_get_schema_async.py new file mode 100644 index 000000000000..2fc215c9a29c --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_get_schema_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_SchemaService_GetSchema_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +async def sample_get_schema(): + # Create a client + client = discoveryengine_v1.SchemaServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.GetSchemaRequest( + name="name_value", + ) + + # Make the request + response = await client.get_schema(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1_generated_SchemaService_GetSchema_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_get_schema_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_get_schema_sync.py new file mode 100644 index 000000000000..97cd74f9c228 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_get_schema_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_SchemaService_GetSchema_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +def sample_get_schema(): + # Create a client + client = discoveryengine_v1.SchemaServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.GetSchemaRequest( + name="name_value", + ) + + # Make the request + response = client.get_schema(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1_generated_SchemaService_GetSchema_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_list_schemas_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_list_schemas_async.py new file mode 100644 index 000000000000..a46cc07b32a4 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_list_schemas_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSchemas +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_SchemaService_ListSchemas_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +async def sample_list_schemas(): + # Create a client + client = discoveryengine_v1.SchemaServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.ListSchemasRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_schemas(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END discoveryengine_v1_generated_SchemaService_ListSchemas_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_list_schemas_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_list_schemas_sync.py new file mode 100644 index 000000000000..7476d67d150a --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_list_schemas_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSchemas +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_SchemaService_ListSchemas_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +def sample_list_schemas(): + # Create a client + client = discoveryengine_v1.SchemaServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.ListSchemasRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_schemas(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END discoveryengine_v1_generated_SchemaService_ListSchemas_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_update_schema_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_update_schema_async.py new file mode 100644 index 000000000000..353e941ff66b --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_update_schema_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_SchemaService_UpdateSchema_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +async def sample_update_schema(): + # Create a client + client = discoveryengine_v1.SchemaServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.UpdateSchemaRequest( + ) + + # Make the request + operation = client.update_schema(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END discoveryengine_v1_generated_SchemaService_UpdateSchema_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_update_schema_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_update_schema_sync.py new file mode 100644 index 000000000000..352ea1e343fc --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_update_schema_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_SchemaService_UpdateSchema_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +def sample_update_schema(): + # Create a client + client = discoveryengine_v1.SchemaServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.UpdateSchemaRequest( + ) + + # Make the request + operation = client.update_schema(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END discoveryengine_v1_generated_SchemaService_UpdateSchema_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_search_service_search_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_search_service_search_async.py new file mode 100644 index 000000000000..1a4950f86052 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_search_service_search_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Search +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_SearchService_Search_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +async def sample_search(): + # Create a client + client = discoveryengine_v1.SearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.SearchRequest( + serving_config="serving_config_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END discoveryengine_v1_generated_SearchService_Search_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_search_service_search_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_search_service_search_sync.py new file mode 100644 index 000000000000..0821a29337dd --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_search_service_search_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Search +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_SearchService_Search_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +def sample_search(): + # Create a client + client = discoveryengine_v1.SearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.SearchRequest( + serving_config="serving_config_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END discoveryengine_v1_generated_SearchService_Search_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_collect_user_event_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_collect_user_event_async.py new file mode 100644 index 000000000000..d19646672e50 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_collect_user_event_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CollectUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_UserEventService_CollectUserEvent_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +async def sample_collect_user_event(): + # Create a client + client = discoveryengine_v1.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = await client.collect_user_event(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1_generated_UserEventService_CollectUserEvent_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_collect_user_event_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_collect_user_event_sync.py new file mode 100644 index 000000000000..0ab2a0ba19bc --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_collect_user_event_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CollectUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_UserEventService_CollectUserEvent_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +def sample_collect_user_event(): + # Create a client + client = discoveryengine_v1.UserEventServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = client.collect_user_event(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1_generated_UserEventService_CollectUserEvent_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_import_user_events_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_import_user_events_async.py new file mode 100644 index 000000000000..7d65b34b8373 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_import_user_events_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_UserEventService_ImportUserEvents_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +async def sample_import_user_events(): + # Create a client + client = discoveryengine_v1.UserEventServiceAsyncClient() + + # Initialize request argument(s) + inline_source = discoveryengine_v1.InlineSource() + inline_source.user_events.event_type = "event_type_value" + inline_source.user_events.user_pseudo_id = "user_pseudo_id_value" + + request = discoveryengine_v1.ImportUserEventsRequest( + inline_source=inline_source, + parent="parent_value", + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END discoveryengine_v1_generated_UserEventService_ImportUserEvents_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_import_user_events_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_import_user_events_sync.py new file mode 100644 index 000000000000..b6bcb67c87ef --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_import_user_events_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_UserEventService_ImportUserEvents_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +def sample_import_user_events(): + # Create a client + client = discoveryengine_v1.UserEventServiceClient() + + # Initialize request argument(s) + inline_source = discoveryengine_v1.InlineSource() + inline_source.user_events.event_type = "event_type_value" + inline_source.user_events.user_pseudo_id = "user_pseudo_id_value" + + request = discoveryengine_v1.ImportUserEventsRequest( + inline_source=inline_source, + parent="parent_value", + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END discoveryengine_v1_generated_UserEventService_ImportUserEvents_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_write_user_event_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_write_user_event_async.py new file mode 100644 index 000000000000..25cc88027ac9 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_write_user_event_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for WriteUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_UserEventService_WriteUserEvent_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +async def sample_write_user_event(): + # Create a client + client = discoveryengine_v1.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.WriteUserEventRequest( + parent="parent_value", + ) + + # Make the request + response = await client.write_user_event(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1_generated_UserEventService_WriteUserEvent_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_write_user_event_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_write_user_event_sync.py new file mode 100644 index 000000000000..bf674d82b25c --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_write_user_event_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for WriteUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1_generated_UserEventService_WriteUserEvent_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1 + + +def sample_write_user_event(): + # Create a client + client = discoveryengine_v1.UserEventServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.WriteUserEventRequest( + parent="parent_value", + ) + + # Make the request + response = client.write_user_event(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1_generated_UserEventService_WriteUserEvent_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1.json b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1.json new file mode 100644 index 000000000000..7c1bfd82952e --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1.json @@ -0,0 +1,3690 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.discoveryengine.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-cloud-discoveryengine", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1.CompletionServiceAsyncClient", + "shortName": "CompletionServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1.CompletionServiceAsyncClient.complete_query", + "method": { + "fullName": "google.cloud.discoveryengine.v1.CompletionService.CompleteQuery", + "service": { + "fullName": "google.cloud.discoveryengine.v1.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "CompleteQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.CompleteQueryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1.types.CompleteQueryResponse", + "shortName": "complete_query" + }, + "description": "Sample for CompleteQuery", + "file": "discoveryengine_v1_generated_completion_service_complete_query_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_CompletionService_CompleteQuery_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": "discoveryengine_v1_generated_completion_service_complete_query_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1.CompletionServiceClient", + "shortName": "CompletionServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1.CompletionServiceClient.complete_query", + "method": { + "fullName": "google.cloud.discoveryengine.v1.CompletionService.CompleteQuery", + "service": { + "fullName": "google.cloud.discoveryengine.v1.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "CompleteQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.CompleteQueryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1.types.CompleteQueryResponse", + "shortName": "complete_query" + }, + "description": "Sample for CompleteQuery", + "file": "discoveryengine_v1_generated_completion_service_complete_query_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_CompletionService_CompleteQuery_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": "discoveryengine_v1_generated_completion_service_complete_query_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient", + "shortName": "ConversationalSearchServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.converse_conversation", + "method": { + "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.ConverseConversation", + "service": { + "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService", + "shortName": "ConversationalSearchService" + }, + "shortName": "ConverseConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.ConverseConversationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "query", + "type": "google.cloud.discoveryengine_v1.types.TextInput" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1.types.ConverseConversationResponse", + "shortName": "converse_conversation" + }, + "description": "Sample for ConverseConversation", + "file": "discoveryengine_v1_generated_conversational_search_service_converse_conversation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_ConverseConversation_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": "discoveryengine_v1_generated_conversational_search_service_converse_conversation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient", + "shortName": "ConversationalSearchServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.converse_conversation", + "method": { + "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.ConverseConversation", + "service": { + "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService", + "shortName": "ConversationalSearchService" + }, + "shortName": "ConverseConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.ConverseConversationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "query", + "type": "google.cloud.discoveryengine_v1.types.TextInput" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1.types.ConverseConversationResponse", + "shortName": "converse_conversation" + }, + "description": "Sample for ConverseConversation", + "file": "discoveryengine_v1_generated_conversational_search_service_converse_conversation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_ConverseConversation_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": "discoveryengine_v1_generated_conversational_search_service_converse_conversation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient", + "shortName": "ConversationalSearchServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.create_conversation", + "method": { + "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.CreateConversation", + "service": { + "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService", + "shortName": "ConversationalSearchService" + }, + "shortName": "CreateConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.CreateConversationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "conversation", + "type": "google.cloud.discoveryengine_v1.types.Conversation" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1.types.Conversation", + "shortName": "create_conversation" + }, + "description": "Sample for CreateConversation", + "file": "discoveryengine_v1_generated_conversational_search_service_create_conversation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_CreateConversation_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": "discoveryengine_v1_generated_conversational_search_service_create_conversation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient", + "shortName": "ConversationalSearchServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.create_conversation", + "method": { + "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.CreateConversation", + "service": { + "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService", + "shortName": "ConversationalSearchService" + }, + "shortName": "CreateConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.CreateConversationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "conversation", + "type": "google.cloud.discoveryengine_v1.types.Conversation" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1.types.Conversation", + "shortName": "create_conversation" + }, + "description": "Sample for CreateConversation", + "file": "discoveryengine_v1_generated_conversational_search_service_create_conversation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_CreateConversation_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": "discoveryengine_v1_generated_conversational_search_service_create_conversation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient", + "shortName": "ConversationalSearchServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.delete_conversation", + "method": { + "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.DeleteConversation", + "service": { + "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService", + "shortName": "ConversationalSearchService" + }, + "shortName": "DeleteConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.DeleteConversationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_conversation" + }, + "description": "Sample for DeleteConversation", + "file": "discoveryengine_v1_generated_conversational_search_service_delete_conversation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_DeleteConversation_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": "discoveryengine_v1_generated_conversational_search_service_delete_conversation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient", + "shortName": "ConversationalSearchServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.delete_conversation", + "method": { + "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.DeleteConversation", + "service": { + "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService", + "shortName": "ConversationalSearchService" + }, + "shortName": "DeleteConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.DeleteConversationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_conversation" + }, + "description": "Sample for DeleteConversation", + "file": "discoveryengine_v1_generated_conversational_search_service_delete_conversation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_DeleteConversation_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": "discoveryengine_v1_generated_conversational_search_service_delete_conversation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient", + "shortName": "ConversationalSearchServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.get_conversation", + "method": { + "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.GetConversation", + "service": { + "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService", + "shortName": "ConversationalSearchService" + }, + "shortName": "GetConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.GetConversationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1.types.Conversation", + "shortName": "get_conversation" + }, + "description": "Sample for GetConversation", + "file": "discoveryengine_v1_generated_conversational_search_service_get_conversation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_GetConversation_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": "discoveryengine_v1_generated_conversational_search_service_get_conversation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient", + "shortName": "ConversationalSearchServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.get_conversation", + "method": { + "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.GetConversation", + "service": { + "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService", + "shortName": "ConversationalSearchService" + }, + "shortName": "GetConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.GetConversationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1.types.Conversation", + "shortName": "get_conversation" + }, + "description": "Sample for GetConversation", + "file": "discoveryengine_v1_generated_conversational_search_service_get_conversation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_GetConversation_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": "discoveryengine_v1_generated_conversational_search_service_get_conversation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient", + "shortName": "ConversationalSearchServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.list_conversations", + "method": { + "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.ListConversations", + "service": { + "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService", + "shortName": "ConversationalSearchService" + }, + "shortName": "ListConversations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.ListConversationsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1.services.conversational_search_service.pagers.ListConversationsAsyncPager", + "shortName": "list_conversations" + }, + "description": "Sample for ListConversations", + "file": "discoveryengine_v1_generated_conversational_search_service_list_conversations_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_ListConversations_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": "discoveryengine_v1_generated_conversational_search_service_list_conversations_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient", + "shortName": "ConversationalSearchServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.list_conversations", + "method": { + "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.ListConversations", + "service": { + "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService", + "shortName": "ConversationalSearchService" + }, + "shortName": "ListConversations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.ListConversationsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1.services.conversational_search_service.pagers.ListConversationsPager", + "shortName": "list_conversations" + }, + "description": "Sample for ListConversations", + "file": "discoveryengine_v1_generated_conversational_search_service_list_conversations_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_ListConversations_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": "discoveryengine_v1_generated_conversational_search_service_list_conversations_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient", + "shortName": "ConversationalSearchServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.update_conversation", + "method": { + "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.UpdateConversation", + "service": { + "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService", + "shortName": "ConversationalSearchService" + }, + "shortName": "UpdateConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.UpdateConversationRequest" + }, + { + "name": "conversation", + "type": "google.cloud.discoveryengine_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, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1.types.Conversation", + "shortName": "update_conversation" + }, + "description": "Sample for UpdateConversation", + "file": "discoveryengine_v1_generated_conversational_search_service_update_conversation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_UpdateConversation_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": "discoveryengine_v1_generated_conversational_search_service_update_conversation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient", + "shortName": "ConversationalSearchServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.update_conversation", + "method": { + "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.UpdateConversation", + "service": { + "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService", + "shortName": "ConversationalSearchService" + }, + "shortName": "UpdateConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.UpdateConversationRequest" + }, + { + "name": "conversation", + "type": "google.cloud.discoveryengine_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, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1.types.Conversation", + "shortName": "update_conversation" + }, + "description": "Sample for UpdateConversation", + "file": "discoveryengine_v1_generated_conversational_search_service_update_conversation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_UpdateConversation_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": "discoveryengine_v1_generated_conversational_search_service_update_conversation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient", + "shortName": "DocumentServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient.create_document", + "method": { + "fullName": "google.cloud.discoveryengine.v1.DocumentService.CreateDocument", + "service": { + "fullName": "google.cloud.discoveryengine.v1.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "CreateDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.CreateDocumentRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "document", + "type": "google.cloud.discoveryengine_v1.types.Document" + }, + { + "name": "document_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1.types.Document", + "shortName": "create_document" + }, + "description": "Sample for CreateDocument", + "file": "discoveryengine_v1_generated_document_service_create_document_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_DocumentService_CreateDocument_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": "discoveryengine_v1_generated_document_service_create_document_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient", + "shortName": "DocumentServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient.create_document", + "method": { + "fullName": "google.cloud.discoveryengine.v1.DocumentService.CreateDocument", + "service": { + "fullName": "google.cloud.discoveryengine.v1.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "CreateDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.CreateDocumentRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "document", + "type": "google.cloud.discoveryengine_v1.types.Document" + }, + { + "name": "document_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1.types.Document", + "shortName": "create_document" + }, + "description": "Sample for CreateDocument", + "file": "discoveryengine_v1_generated_document_service_create_document_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_DocumentService_CreateDocument_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": "discoveryengine_v1_generated_document_service_create_document_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient", + "shortName": "DocumentServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient.delete_document", + "method": { + "fullName": "google.cloud.discoveryengine.v1.DocumentService.DeleteDocument", + "service": { + "fullName": "google.cloud.discoveryengine.v1.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "DeleteDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.DeleteDocumentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_document" + }, + "description": "Sample for DeleteDocument", + "file": "discoveryengine_v1_generated_document_service_delete_document_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_DocumentService_DeleteDocument_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": "discoveryengine_v1_generated_document_service_delete_document_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient", + "shortName": "DocumentServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient.delete_document", + "method": { + "fullName": "google.cloud.discoveryengine.v1.DocumentService.DeleteDocument", + "service": { + "fullName": "google.cloud.discoveryengine.v1.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "DeleteDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.DeleteDocumentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_document" + }, + "description": "Sample for DeleteDocument", + "file": "discoveryengine_v1_generated_document_service_delete_document_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_DocumentService_DeleteDocument_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": "discoveryengine_v1_generated_document_service_delete_document_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient", + "shortName": "DocumentServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient.get_document", + "method": { + "fullName": "google.cloud.discoveryengine.v1.DocumentService.GetDocument", + "service": { + "fullName": "google.cloud.discoveryengine.v1.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "GetDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.GetDocumentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1.types.Document", + "shortName": "get_document" + }, + "description": "Sample for GetDocument", + "file": "discoveryengine_v1_generated_document_service_get_document_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_DocumentService_GetDocument_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": "discoveryengine_v1_generated_document_service_get_document_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient", + "shortName": "DocumentServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient.get_document", + "method": { + "fullName": "google.cloud.discoveryengine.v1.DocumentService.GetDocument", + "service": { + "fullName": "google.cloud.discoveryengine.v1.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "GetDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.GetDocumentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1.types.Document", + "shortName": "get_document" + }, + "description": "Sample for GetDocument", + "file": "discoveryengine_v1_generated_document_service_get_document_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_DocumentService_GetDocument_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": "discoveryengine_v1_generated_document_service_get_document_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient", + "shortName": "DocumentServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient.import_documents", + "method": { + "fullName": "google.cloud.discoveryengine.v1.DocumentService.ImportDocuments", + "service": { + "fullName": "google.cloud.discoveryengine.v1.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "ImportDocuments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.ImportDocumentsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "import_documents" + }, + "description": "Sample for ImportDocuments", + "file": "discoveryengine_v1_generated_document_service_import_documents_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_DocumentService_ImportDocuments_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": "discoveryengine_v1_generated_document_service_import_documents_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient", + "shortName": "DocumentServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient.import_documents", + "method": { + "fullName": "google.cloud.discoveryengine.v1.DocumentService.ImportDocuments", + "service": { + "fullName": "google.cloud.discoveryengine.v1.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "ImportDocuments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.ImportDocumentsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "import_documents" + }, + "description": "Sample for ImportDocuments", + "file": "discoveryengine_v1_generated_document_service_import_documents_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_DocumentService_ImportDocuments_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": "discoveryengine_v1_generated_document_service_import_documents_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient", + "shortName": "DocumentServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient.list_documents", + "method": { + "fullName": "google.cloud.discoveryengine.v1.DocumentService.ListDocuments", + "service": { + "fullName": "google.cloud.discoveryengine.v1.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "ListDocuments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.ListDocumentsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1.services.document_service.pagers.ListDocumentsAsyncPager", + "shortName": "list_documents" + }, + "description": "Sample for ListDocuments", + "file": "discoveryengine_v1_generated_document_service_list_documents_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_DocumentService_ListDocuments_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": "discoveryengine_v1_generated_document_service_list_documents_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient", + "shortName": "DocumentServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient.list_documents", + "method": { + "fullName": "google.cloud.discoveryengine.v1.DocumentService.ListDocuments", + "service": { + "fullName": "google.cloud.discoveryengine.v1.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "ListDocuments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.ListDocumentsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1.services.document_service.pagers.ListDocumentsPager", + "shortName": "list_documents" + }, + "description": "Sample for ListDocuments", + "file": "discoveryengine_v1_generated_document_service_list_documents_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_DocumentService_ListDocuments_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": "discoveryengine_v1_generated_document_service_list_documents_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient", + "shortName": "DocumentServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient.purge_documents", + "method": { + "fullName": "google.cloud.discoveryengine.v1.DocumentService.PurgeDocuments", + "service": { + "fullName": "google.cloud.discoveryengine.v1.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "PurgeDocuments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.PurgeDocumentsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "purge_documents" + }, + "description": "Sample for PurgeDocuments", + "file": "discoveryengine_v1_generated_document_service_purge_documents_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_DocumentService_PurgeDocuments_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": "discoveryengine_v1_generated_document_service_purge_documents_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient", + "shortName": "DocumentServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient.purge_documents", + "method": { + "fullName": "google.cloud.discoveryengine.v1.DocumentService.PurgeDocuments", + "service": { + "fullName": "google.cloud.discoveryengine.v1.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "PurgeDocuments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.PurgeDocumentsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "purge_documents" + }, + "description": "Sample for PurgeDocuments", + "file": "discoveryengine_v1_generated_document_service_purge_documents_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_DocumentService_PurgeDocuments_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": "discoveryengine_v1_generated_document_service_purge_documents_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient", + "shortName": "DocumentServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient.update_document", + "method": { + "fullName": "google.cloud.discoveryengine.v1.DocumentService.UpdateDocument", + "service": { + "fullName": "google.cloud.discoveryengine.v1.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "UpdateDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.UpdateDocumentRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1.types.Document", + "shortName": "update_document" + }, + "description": "Sample for UpdateDocument", + "file": "discoveryengine_v1_generated_document_service_update_document_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_DocumentService_UpdateDocument_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": "discoveryengine_v1_generated_document_service_update_document_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient", + "shortName": "DocumentServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient.update_document", + "method": { + "fullName": "google.cloud.discoveryengine.v1.DocumentService.UpdateDocument", + "service": { + "fullName": "google.cloud.discoveryengine.v1.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "UpdateDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.UpdateDocumentRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1.types.Document", + "shortName": "update_document" + }, + "description": "Sample for UpdateDocument", + "file": "discoveryengine_v1_generated_document_service_update_document_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_DocumentService_UpdateDocument_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": "discoveryengine_v1_generated_document_service_update_document_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient", + "shortName": "SchemaServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient.create_schema", + "method": { + "fullName": "google.cloud.discoveryengine.v1.SchemaService.CreateSchema", + "service": { + "fullName": "google.cloud.discoveryengine.v1.SchemaService", + "shortName": "SchemaService" + }, + "shortName": "CreateSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.CreateSchemaRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "schema", + "type": "google.cloud.discoveryengine_v1.types.Schema" + }, + { + "name": "schema_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_schema" + }, + "description": "Sample for CreateSchema", + "file": "discoveryengine_v1_generated_schema_service_create_schema_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_SchemaService_CreateSchema_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": "discoveryengine_v1_generated_schema_service_create_schema_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient", + "shortName": "SchemaServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient.create_schema", + "method": { + "fullName": "google.cloud.discoveryengine.v1.SchemaService.CreateSchema", + "service": { + "fullName": "google.cloud.discoveryengine.v1.SchemaService", + "shortName": "SchemaService" + }, + "shortName": "CreateSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.CreateSchemaRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "schema", + "type": "google.cloud.discoveryengine_v1.types.Schema" + }, + { + "name": "schema_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_schema" + }, + "description": "Sample for CreateSchema", + "file": "discoveryengine_v1_generated_schema_service_create_schema_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_SchemaService_CreateSchema_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": "discoveryengine_v1_generated_schema_service_create_schema_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient", + "shortName": "SchemaServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient.delete_schema", + "method": { + "fullName": "google.cloud.discoveryengine.v1.SchemaService.DeleteSchema", + "service": { + "fullName": "google.cloud.discoveryengine.v1.SchemaService", + "shortName": "SchemaService" + }, + "shortName": "DeleteSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.DeleteSchemaRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_schema" + }, + "description": "Sample for DeleteSchema", + "file": "discoveryengine_v1_generated_schema_service_delete_schema_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_SchemaService_DeleteSchema_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": "discoveryengine_v1_generated_schema_service_delete_schema_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient", + "shortName": "SchemaServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient.delete_schema", + "method": { + "fullName": "google.cloud.discoveryengine.v1.SchemaService.DeleteSchema", + "service": { + "fullName": "google.cloud.discoveryengine.v1.SchemaService", + "shortName": "SchemaService" + }, + "shortName": "DeleteSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.DeleteSchemaRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_schema" + }, + "description": "Sample for DeleteSchema", + "file": "discoveryengine_v1_generated_schema_service_delete_schema_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_SchemaService_DeleteSchema_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": "discoveryengine_v1_generated_schema_service_delete_schema_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient", + "shortName": "SchemaServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient.get_schema", + "method": { + "fullName": "google.cloud.discoveryengine.v1.SchemaService.GetSchema", + "service": { + "fullName": "google.cloud.discoveryengine.v1.SchemaService", + "shortName": "SchemaService" + }, + "shortName": "GetSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.GetSchemaRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1.types.Schema", + "shortName": "get_schema" + }, + "description": "Sample for GetSchema", + "file": "discoveryengine_v1_generated_schema_service_get_schema_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_SchemaService_GetSchema_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": "discoveryengine_v1_generated_schema_service_get_schema_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient", + "shortName": "SchemaServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient.get_schema", + "method": { + "fullName": "google.cloud.discoveryengine.v1.SchemaService.GetSchema", + "service": { + "fullName": "google.cloud.discoveryengine.v1.SchemaService", + "shortName": "SchemaService" + }, + "shortName": "GetSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.GetSchemaRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1.types.Schema", + "shortName": "get_schema" + }, + "description": "Sample for GetSchema", + "file": "discoveryengine_v1_generated_schema_service_get_schema_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_SchemaService_GetSchema_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": "discoveryengine_v1_generated_schema_service_get_schema_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient", + "shortName": "SchemaServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient.list_schemas", + "method": { + "fullName": "google.cloud.discoveryengine.v1.SchemaService.ListSchemas", + "service": { + "fullName": "google.cloud.discoveryengine.v1.SchemaService", + "shortName": "SchemaService" + }, + "shortName": "ListSchemas" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.ListSchemasRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1.services.schema_service.pagers.ListSchemasAsyncPager", + "shortName": "list_schemas" + }, + "description": "Sample for ListSchemas", + "file": "discoveryengine_v1_generated_schema_service_list_schemas_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_SchemaService_ListSchemas_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": "discoveryengine_v1_generated_schema_service_list_schemas_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient", + "shortName": "SchemaServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient.list_schemas", + "method": { + "fullName": "google.cloud.discoveryengine.v1.SchemaService.ListSchemas", + "service": { + "fullName": "google.cloud.discoveryengine.v1.SchemaService", + "shortName": "SchemaService" + }, + "shortName": "ListSchemas" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.ListSchemasRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1.services.schema_service.pagers.ListSchemasPager", + "shortName": "list_schemas" + }, + "description": "Sample for ListSchemas", + "file": "discoveryengine_v1_generated_schema_service_list_schemas_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_SchemaService_ListSchemas_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": "discoveryengine_v1_generated_schema_service_list_schemas_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient", + "shortName": "SchemaServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient.update_schema", + "method": { + "fullName": "google.cloud.discoveryengine.v1.SchemaService.UpdateSchema", + "service": { + "fullName": "google.cloud.discoveryengine.v1.SchemaService", + "shortName": "SchemaService" + }, + "shortName": "UpdateSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.UpdateSchemaRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_schema" + }, + "description": "Sample for UpdateSchema", + "file": "discoveryengine_v1_generated_schema_service_update_schema_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_SchemaService_UpdateSchema_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1_generated_schema_service_update_schema_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient", + "shortName": "SchemaServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient.update_schema", + "method": { + "fullName": "google.cloud.discoveryengine.v1.SchemaService.UpdateSchema", + "service": { + "fullName": "google.cloud.discoveryengine.v1.SchemaService", + "shortName": "SchemaService" + }, + "shortName": "UpdateSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.UpdateSchemaRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_schema" + }, + "description": "Sample for UpdateSchema", + "file": "discoveryengine_v1_generated_schema_service_update_schema_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_SchemaService_UpdateSchema_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1_generated_schema_service_update_schema_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1.SearchServiceAsyncClient", + "shortName": "SearchServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1.SearchServiceAsyncClient.search", + "method": { + "fullName": "google.cloud.discoveryengine.v1.SearchService.Search", + "service": { + "fullName": "google.cloud.discoveryengine.v1.SearchService", + "shortName": "SearchService" + }, + "shortName": "Search" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.SearchRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1.services.search_service.pagers.SearchAsyncPager", + "shortName": "search" + }, + "description": "Sample for Search", + "file": "discoveryengine_v1_generated_search_service_search_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_SearchService_Search_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": "discoveryengine_v1_generated_search_service_search_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1.SearchServiceClient", + "shortName": "SearchServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1.SearchServiceClient.search", + "method": { + "fullName": "google.cloud.discoveryengine.v1.SearchService.Search", + "service": { + "fullName": "google.cloud.discoveryengine.v1.SearchService", + "shortName": "SearchService" + }, + "shortName": "Search" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.SearchRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1.services.search_service.pagers.SearchPager", + "shortName": "search" + }, + "description": "Sample for Search", + "file": "discoveryengine_v1_generated_search_service_search_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_SearchService_Search_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": "discoveryengine_v1_generated_search_service_search_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1.UserEventServiceAsyncClient.collect_user_event", + "method": { + "fullName": "google.cloud.discoveryengine.v1.UserEventService.CollectUserEvent", + "service": { + "fullName": "google.cloud.discoveryengine.v1.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "CollectUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.CollectUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api.httpbody_pb2.HttpBody", + "shortName": "collect_user_event" + }, + "description": "Sample for CollectUserEvent", + "file": "discoveryengine_v1_generated_user_event_service_collect_user_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_UserEventService_CollectUserEvent_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": "discoveryengine_v1_generated_user_event_service_collect_user_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1.UserEventServiceClient.collect_user_event", + "method": { + "fullName": "google.cloud.discoveryengine.v1.UserEventService.CollectUserEvent", + "service": { + "fullName": "google.cloud.discoveryengine.v1.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "CollectUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.CollectUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api.httpbody_pb2.HttpBody", + "shortName": "collect_user_event" + }, + "description": "Sample for CollectUserEvent", + "file": "discoveryengine_v1_generated_user_event_service_collect_user_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_UserEventService_CollectUserEvent_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": "discoveryengine_v1_generated_user_event_service_collect_user_event_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1.UserEventServiceAsyncClient.import_user_events", + "method": { + "fullName": "google.cloud.discoveryengine.v1.UserEventService.ImportUserEvents", + "service": { + "fullName": "google.cloud.discoveryengine.v1.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "ImportUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.ImportUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "import_user_events" + }, + "description": "Sample for ImportUserEvents", + "file": "discoveryengine_v1_generated_user_event_service_import_user_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_UserEventService_ImportUserEvents_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": "discoveryengine_v1_generated_user_event_service_import_user_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1.UserEventServiceClient.import_user_events", + "method": { + "fullName": "google.cloud.discoveryengine.v1.UserEventService.ImportUserEvents", + "service": { + "fullName": "google.cloud.discoveryengine.v1.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "ImportUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.ImportUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "import_user_events" + }, + "description": "Sample for ImportUserEvents", + "file": "discoveryengine_v1_generated_user_event_service_import_user_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_UserEventService_ImportUserEvents_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": "discoveryengine_v1_generated_user_event_service_import_user_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1.UserEventServiceAsyncClient.write_user_event", + "method": { + "fullName": "google.cloud.discoveryengine.v1.UserEventService.WriteUserEvent", + "service": { + "fullName": "google.cloud.discoveryengine.v1.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "WriteUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.WriteUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1.types.UserEvent", + "shortName": "write_user_event" + }, + "description": "Sample for WriteUserEvent", + "file": "discoveryengine_v1_generated_user_event_service_write_user_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_UserEventService_WriteUserEvent_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": "discoveryengine_v1_generated_user_event_service_write_user_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1.UserEventServiceClient.write_user_event", + "method": { + "fullName": "google.cloud.discoveryengine.v1.UserEventService.WriteUserEvent", + "service": { + "fullName": "google.cloud.discoveryengine.v1.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "WriteUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1.types.WriteUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1.types.UserEvent", + "shortName": "write_user_event" + }, + "description": "Sample for WriteUserEvent", + "file": "discoveryengine_v1_generated_user_event_service_write_user_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1_generated_UserEventService_WriteUserEvent_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": "discoveryengine_v1_generated_user_event_service_write_user_event_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/scripts/fixup_discoveryengine_v1_keywords.py b/owl-bot-staging/google-cloud-discoveryengine/v1/scripts/fixup_discoveryengine_v1_keywords.py new file mode 100644 index 000000000000..671ba001cfa9 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/scripts/fixup_discoveryengine_v1_keywords.py @@ -0,0 +1,198 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class discoveryengineCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'collect_user_event': ('parent', 'user_event', 'uri', 'ets', ), + 'complete_query': ('data_store', 'query', 'query_model', 'user_pseudo_id', 'include_tail_suggestions', ), + 'converse_conversation': ('name', 'query', 'serving_config', 'conversation', 'safe_search', 'user_labels', 'summary_spec', ), + 'create_conversation': ('parent', 'conversation', ), + 'create_document': ('parent', 'document', 'document_id', ), + 'create_schema': ('parent', 'schema', 'schema_id', ), + 'delete_conversation': ('name', ), + 'delete_document': ('name', ), + 'delete_schema': ('name', ), + 'get_conversation': ('name', ), + 'get_document': ('name', ), + 'get_schema': ('name', ), + 'import_documents': ('parent', 'inline_source', 'gcs_source', 'bigquery_source', 'error_config', 'reconciliation_mode', 'auto_generate_ids', 'id_field', ), + 'import_user_events': ('parent', 'inline_source', 'gcs_source', 'bigquery_source', 'error_config', ), + 'list_conversations': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_documents': ('parent', 'page_size', 'page_token', ), + 'list_schemas': ('parent', 'page_size', 'page_token', ), + 'purge_documents': ('parent', 'filter', 'force', ), + 'search': ('serving_config', 'branch', 'query', 'image_query', 'page_size', 'page_token', 'offset', 'filter', 'order_by', 'user_info', 'facet_specs', 'boost_spec', 'params', 'query_expansion_spec', 'spell_correction_spec', 'user_pseudo_id', 'content_search_spec', 'safe_search', 'user_labels', ), + 'update_conversation': ('conversation', 'update_mask', ), + 'update_document': ('document', 'allow_missing', ), + 'update_schema': ('schema', 'allow_missing', ), + 'write_user_event': ('parent', 'user_event', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=discoveryengineCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the discoveryengine client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/setup.py b/owl-bot-staging/google-cloud-discoveryengine/v1/setup.py new file mode 100644 index 000000000000..513896d68575 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/setup.py @@ -0,0 +1,90 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-discoveryengine' + + +description = "Google Cloud Discoveryengine API client library" + +version = {} +with open(os.path.join(package_root, 'google/cloud/discoveryengine/gapic_version.py')) as fp: + exec(fp.read(), version) +version = version["__version__"] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + "proto-plus >= 1.22.0, <2.0.0dev", + "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", + "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +url = "https://github.com/googleapis/python-discoveryengine" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.PEP420PackageFinder.find() + if package.startswith("google") +] + +namespaces = ["google", "google.cloud"] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + namespace_packages=namespaces, + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.10.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.11.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.12.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..6c44adfea7ee --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.7.txt @@ -0,0 +1,9 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.0 +proto-plus==1.22.0 +protobuf==3.19.5 diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.8.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.9.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/tests/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/tests/__init__.py new file mode 100644 index 000000000000..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/__init__.py new file mode 100644 index 000000000000..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/__init__.py new file mode 100644 index 000000000000..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_completion_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_completion_service.py new file mode 100644 index 000000000000..415348b10cc9 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_completion_service.py @@ -0,0 +1,1920 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.discoveryengine_v1.services.completion_service import CompletionServiceAsyncClient +from google.cloud.discoveryengine_v1.services.completion_service import CompletionServiceClient +from google.cloud.discoveryengine_v1.services.completion_service import transports +from google.cloud.discoveryengine_v1.types import completion_service +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert CompletionServiceClient._get_default_mtls_endpoint(None) is None + assert CompletionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (CompletionServiceClient, "grpc"), + (CompletionServiceAsyncClient, "grpc_asyncio"), + (CompletionServiceClient, "rest"), +]) +def test_completion_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.CompletionServiceGrpcTransport, "grpc"), + (transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.CompletionServiceRestTransport, "rest"), +]) +def test_completion_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", [ + (CompletionServiceClient, "grpc"), + (CompletionServiceAsyncClient, "grpc_asyncio"), + (CompletionServiceClient, "rest"), +]) +def test_completion_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +def test_completion_service_client_get_transport_class(): + transport = CompletionServiceClient.get_transport_class() + available_transports = [ + transports.CompletionServiceGrpcTransport, + transports.CompletionServiceRestTransport, + ] + assert transport in available_transports + + transport = CompletionServiceClient.get_transport_class("grpc") + assert transport == transports.CompletionServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (CompletionServiceClient, transports.CompletionServiceRestTransport, "rest"), +]) +@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) +@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) +def test_completion_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(CompletionServiceClient, '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(CompletionServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "true"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "false"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (CompletionServiceClient, transports.CompletionServiceRestTransport, "rest", "true"), + (CompletionServiceClient, transports.CompletionServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) +@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_completion_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 + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + CompletionServiceClient, CompletionServiceAsyncClient +]) +@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) +@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) +def test_completion_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (CompletionServiceClient, transports.CompletionServiceRestTransport, "rest"), +]) +def test_completion_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, + 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", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (CompletionServiceClient, transports.CompletionServiceRestTransport, "rest", None), +]) +def test_completion_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, + scopes=None, + client_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_completion_service_client_client_options_from_dict(): + with mock.patch('google.cloud.discoveryengine_v1.services.completion_service.transports.CompletionServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = CompletionServiceClient( + 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", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_completion_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, + scopes=None, + client_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + completion_service.CompleteQueryRequest, + dict, +]) +def test_complete_query(request_type, transport: str = 'grpc'): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = completion_service.CompleteQueryResponse( + tail_match_triggered=True, + ) + response = client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == completion_service.CompleteQueryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, completion_service.CompleteQueryResponse) + assert response.tail_match_triggered is True + + +def test_complete_query_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + client.complete_query() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == completion_service.CompleteQueryRequest() + +@pytest.mark.asyncio +async def test_complete_query_async(transport: str = 'grpc_asyncio', request_type=completion_service.CompleteQueryRequest): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse( + tail_match_triggered=True, + )) + response = await client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == completion_service.CompleteQueryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, completion_service.CompleteQueryResponse) + assert response.tail_match_triggered is True + + +@pytest.mark.asyncio +async def test_complete_query_async_from_dict(): + await test_complete_query_async(request_type=dict) + + +def test_complete_query_field_headers(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = completion_service.CompleteQueryRequest() + + request.data_store = 'data_store_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + call.return_value = completion_service.CompleteQueryResponse() + client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'data_store=data_store_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_complete_query_field_headers_async(): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = completion_service.CompleteQueryRequest() + + request.data_store = 'data_store_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse()) + await client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'data_store=data_store_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + completion_service.CompleteQueryRequest, + dict, +]) +def test_complete_query_rest(request_type): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'data_store': 'projects/sample1/locations/sample2/dataStores/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 = completion_service.CompleteQueryResponse( + tail_match_triggered=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = completion_service.CompleteQueryResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.complete_query(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, completion_service.CompleteQueryResponse) + assert response.tail_match_triggered is True + + +def test_complete_query_rest_required_fields(request_type=completion_service.CompleteQueryRequest): + transport_class = transports.CompletionServiceRestTransport + + request_init = {} + request_init["data_store"] = "" + request_init["query"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "query" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).complete_query._get_unset_required_fields(jsonified_request) + 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["dataStore"] = 'data_store_value' + jsonified_request["query"] = 'query_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).complete_query._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("include_tail_suggestions", "query", "query_model", "user_pseudo_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "dataStore" in jsonified_request + assert jsonified_request["dataStore"] == 'data_store_value' + assert "query" in jsonified_request + assert jsonified_request["query"] == 'query_value' + + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = completion_service.CompleteQueryResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = completion_service.CompleteQueryResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.complete_query(request) + + expected_params = [ + ( + "query", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_complete_query_rest_unset_required_fields(): + transport = transports.CompletionServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.complete_query._get_unset_required_fields({}) + assert set(unset_fields) == (set(("includeTailSuggestions", "query", "queryModel", "userPseudoId", )) & set(("dataStore", "query", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_complete_query_rest_interceptors(null_interceptor): + transport = transports.CompletionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.CompletionServiceRestInterceptor(), + ) + client = CompletionServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.CompletionServiceRestInterceptor, "post_complete_query") as post, \ + mock.patch.object(transports.CompletionServiceRestInterceptor, "pre_complete_query") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = completion_service.CompleteQueryRequest.pb(completion_service.CompleteQueryRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = completion_service.CompleteQueryResponse.to_json(completion_service.CompleteQueryResponse()) + + request = completion_service.CompleteQueryRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = completion_service.CompleteQueryResponse() + + client.complete_query(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_complete_query_rest_bad_request(transport: str = 'rest', request_type=completion_service.CompleteQueryRequest): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'data_store': 'projects/sample1/locations/sample2/dataStores/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.complete_query(request) + + +def test_complete_query_rest_error(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CompletionServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CompletionServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, + transports.CompletionServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = CompletionServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CompletionServiceGrpcTransport, + ) + +def test_completion_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CompletionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_completion_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.discoveryengine_v1.services.completion_service.transports.CompletionServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.CompletionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'complete_query', + 'get_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_completion_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.discoveryengine_v1.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CompletionServiceTransport( + 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_completion_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.discoveryengine_v1.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CompletionServiceTransport() + adc.assert_called_once() + + +def test_completion_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) + CompletionServiceClient() + 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.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, + ], +) +def test_completion_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.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, + transports.CompletionServiceRestTransport, + ], +) +def test_completion_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.CompletionServiceGrpcTransport, grpc_helpers), + (transports.CompletionServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_completion_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) +def test_completion_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_completion_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.CompletionServiceRestTransport ( + 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_completion_service_host_no_port(transport_name): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_completion_service_host_with_port(transport_name): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_completion_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = CompletionServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = CompletionServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.complete_query._session + session2 = client2.transport.complete_query._session + assert session1 != session2 +def test_completion_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CompletionServiceGrpcTransport( + 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_completion_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CompletionServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) +def test_completion_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.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) +def test_completion_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_data_store_path(): + project = "squid" + location = "clam" + data_store = "whelk" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) + actual = CompletionServiceClient.data_store_path(project, location, data_store) + assert expected == actual + + +def test_parse_data_store_path(): + expected = { + "project": "octopus", + "location": "oyster", + "data_store": "nudibranch", + } + path = CompletionServiceClient.data_store_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_data_store_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = CompletionServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = CompletionServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = CompletionServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = CompletionServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = CompletionServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = CompletionServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = CompletionServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = CompletionServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = CompletionServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = CompletionServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.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.CompletionServiceTransport, '_prep_wrapped_messages') as prep: + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = CompletionServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/operations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = CompletionServiceClient( + 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(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_get_operation(transport: str = "grpc"): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc"): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = CompletionServiceClient( + 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 = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc"): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = CompletionServiceClient( + 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 = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = CompletionServiceClient( + 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", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_conversational_search_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_conversational_search_service.py new file mode 100644 index 000000000000..777c4fb62bce --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_conversational_search_service.py @@ -0,0 +1,4902 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.discoveryengine_v1.services.conversational_search_service import ConversationalSearchServiceAsyncClient +from google.cloud.discoveryengine_v1.services.conversational_search_service import ConversationalSearchServiceClient +from google.cloud.discoveryengine_v1.services.conversational_search_service import pagers +from google.cloud.discoveryengine_v1.services.conversational_search_service import transports +from google.cloud.discoveryengine_v1.types import conversation +from google.cloud.discoveryengine_v1.types import conversation as gcd_conversation +from google.cloud.discoveryengine_v1.types import conversational_search_service +from google.cloud.discoveryengine_v1.types import search_service +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ConversationalSearchServiceClient._get_default_mtls_endpoint(None) is None + assert ConversationalSearchServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ConversationalSearchServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ConversationalSearchServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ConversationalSearchServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ConversationalSearchServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ConversationalSearchServiceClient, "grpc"), + (ConversationalSearchServiceAsyncClient, "grpc_asyncio"), + (ConversationalSearchServiceClient, "rest"), +]) +def test_conversational_search_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ConversationalSearchServiceGrpcTransport, "grpc"), + (transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ConversationalSearchServiceRestTransport, "rest"), +]) +def test_conversational_search_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", [ + (ConversationalSearchServiceClient, "grpc"), + (ConversationalSearchServiceAsyncClient, "grpc_asyncio"), + (ConversationalSearchServiceClient, "rest"), +]) +def test_conversational_search_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +def test_conversational_search_service_client_get_transport_class(): + transport = ConversationalSearchServiceClient.get_transport_class() + available_transports = [ + transports.ConversationalSearchServiceGrpcTransport, + transports.ConversationalSearchServiceRestTransport, + ] + assert transport in available_transports + + transport = ConversationalSearchServiceClient.get_transport_class("grpc") + assert transport == transports.ConversationalSearchServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport, "grpc"), + (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (ConversationalSearchServiceClient, transports.ConversationalSearchServiceRestTransport, "rest"), +]) +@mock.patch.object(ConversationalSearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationalSearchServiceClient)) +@mock.patch.object(ConversationalSearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationalSearchServiceAsyncClient)) +def test_conversational_search_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(ConversationalSearchServiceClient, '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(ConversationalSearchServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport, "grpc", "true"), + (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport, "grpc", "false"), + (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (ConversationalSearchServiceClient, transports.ConversationalSearchServiceRestTransport, "rest", "true"), + (ConversationalSearchServiceClient, transports.ConversationalSearchServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(ConversationalSearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationalSearchServiceClient)) +@mock.patch.object(ConversationalSearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationalSearchServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_conversational_search_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 + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + ConversationalSearchServiceClient, ConversationalSearchServiceAsyncClient +]) +@mock.patch.object(ConversationalSearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationalSearchServiceClient)) +@mock.patch.object(ConversationalSearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationalSearchServiceAsyncClient)) +def test_conversational_search_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport, "grpc"), + (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (ConversationalSearchServiceClient, transports.ConversationalSearchServiceRestTransport, "rest"), +]) +def test_conversational_search_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, + 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", [ + (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport, "grpc", grpc_helpers), + (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (ConversationalSearchServiceClient, transports.ConversationalSearchServiceRestTransport, "rest", None), +]) +def test_conversational_search_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, + scopes=None, + client_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_conversational_search_service_client_client_options_from_dict(): + with mock.patch('google.cloud.discoveryengine_v1.services.conversational_search_service.transports.ConversationalSearchServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ConversationalSearchServiceClient( + 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", [ + (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport, "grpc", grpc_helpers), + (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_conversational_search_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, + scopes=None, + client_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + conversational_search_service.ConverseConversationRequest, + dict, +]) +def test_converse_conversation(request_type, transport: str = 'grpc'): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.converse_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversational_search_service.ConverseConversationResponse( + ) + response = client.converse_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] == conversational_search_service.ConverseConversationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, conversational_search_service.ConverseConversationResponse) + + +def test_converse_conversation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.converse_conversation), + '__call__') as call: + client.converse_conversation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversational_search_service.ConverseConversationRequest() + +@pytest.mark.asyncio +async def test_converse_conversation_async(transport: str = 'grpc_asyncio', request_type=conversational_search_service.ConverseConversationRequest): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.converse_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversational_search_service.ConverseConversationResponse( + )) + response = await client.converse_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == conversational_search_service.ConverseConversationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, conversational_search_service.ConverseConversationResponse) + + +@pytest.mark.asyncio +async def test_converse_conversation_async_from_dict(): + await test_converse_conversation_async(request_type=dict) + + +def test_converse_conversation_field_headers(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversational_search_service.ConverseConversationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.converse_conversation), + '__call__') as call: + call.return_value = conversational_search_service.ConverseConversationResponse() + client.converse_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', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_converse_conversation_field_headers_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversational_search_service.ConverseConversationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.converse_conversation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversational_search_service.ConverseConversationResponse()) + await client.converse_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', + 'name=name_value', + ) in kw['metadata'] + + +def test_converse_conversation_flattened(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.converse_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversational_search_service.ConverseConversationResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.converse_conversation( + name='name_value', + query=conversation.TextInput(input='input_value'), + ) + + # Establish that the 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].query + mock_val = conversation.TextInput(input='input_value') + assert arg == mock_val + + +def test_converse_conversation_flattened_error(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.converse_conversation( + conversational_search_service.ConverseConversationRequest(), + name='name_value', + query=conversation.TextInput(input='input_value'), + ) + +@pytest.mark.asyncio +async def test_converse_conversation_flattened_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.converse_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversational_search_service.ConverseConversationResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversational_search_service.ConverseConversationResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.converse_conversation( + name='name_value', + query=conversation.TextInput(input='input_value'), + ) + + # Establish that 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].query + mock_val = conversation.TextInput(input='input_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_converse_conversation_flattened_error_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.converse_conversation( + conversational_search_service.ConverseConversationRequest(), + name='name_value', + query=conversation.TextInput(input='input_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + conversational_search_service.CreateConversationRequest, + dict, +]) +def test_create_conversation(request_type, transport: str = 'grpc'): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_conversation.Conversation( + name='name_value', + state=gcd_conversation.Conversation.State.IN_PROGRESS, + user_pseudo_id='user_pseudo_id_value', + ) + response = client.create_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] == conversational_search_service.CreateConversationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_conversation.Conversation) + assert response.name == 'name_value' + assert response.state == gcd_conversation.Conversation.State.IN_PROGRESS + assert response.user_pseudo_id == 'user_pseudo_id_value' + + +def test_create_conversation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversation), + '__call__') as call: + client.create_conversation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversational_search_service.CreateConversationRequest() + +@pytest.mark.asyncio +async def test_create_conversation_async(transport: str = 'grpc_asyncio', request_type=conversational_search_service.CreateConversationRequest): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation.Conversation( + name='name_value', + state=gcd_conversation.Conversation.State.IN_PROGRESS, + user_pseudo_id='user_pseudo_id_value', + )) + response = await client.create_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == conversational_search_service.CreateConversationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_conversation.Conversation) + assert response.name == 'name_value' + assert response.state == gcd_conversation.Conversation.State.IN_PROGRESS + assert response.user_pseudo_id == 'user_pseudo_id_value' + + +@pytest.mark.asyncio +async def test_create_conversation_async_from_dict(): + await test_create_conversation_async(request_type=dict) + + +def test_create_conversation_field_headers(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversational_search_service.CreateConversationRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversation), + '__call__') as call: + call.return_value = gcd_conversation.Conversation() + client.create_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', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_conversation_field_headers_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversational_search_service.CreateConversationRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation.Conversation()) + await client.create_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', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_conversation_flattened(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_conversation.Conversation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_conversation( + parent='parent_value', + conversation=gcd_conversation.Conversation(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].conversation + mock_val = gcd_conversation.Conversation(name='name_value') + assert arg == mock_val + + +def test_create_conversation_flattened_error(): + client = ConversationalSearchServiceClient( + credentials=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_conversation( + conversational_search_service.CreateConversationRequest(), + parent='parent_value', + conversation=gcd_conversation.Conversation(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_conversation_flattened_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_conversation.Conversation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation.Conversation()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_conversation( + parent='parent_value', + conversation=gcd_conversation.Conversation(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].conversation + mock_val = gcd_conversation.Conversation(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_conversation_flattened_error_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_conversation( + conversational_search_service.CreateConversationRequest(), + parent='parent_value', + conversation=gcd_conversation.Conversation(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + conversational_search_service.DeleteConversationRequest, + dict, +]) +def test_delete_conversation(request_type, transport: str = 'grpc'): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_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] == conversational_search_service.DeleteConversationRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_conversation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversation), + '__call__') as call: + client.delete_conversation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversational_search_service.DeleteConversationRequest() + +@pytest.mark.asyncio +async def test_delete_conversation_async(transport: str = 'grpc_asyncio', request_type=conversational_search_service.DeleteConversationRequest): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == conversational_search_service.DeleteConversationRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_conversation_async_from_dict(): + await test_delete_conversation_async(request_type=dict) + + +def test_delete_conversation_field_headers(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversational_search_service.DeleteConversationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversation), + '__call__') as call: + call.return_value = None + client.delete_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', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_conversation_field_headers_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversational_search_service.DeleteConversationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_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', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_conversation_flattened(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, 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 = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_conversation( + 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_conversation_flattened_error(): + client = ConversationalSearchServiceClient( + credentials=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_conversation( + conversational_search_service.DeleteConversationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_conversation_flattened_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, 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 = 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_conversation( + 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_conversation_flattened_error_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_conversation( + conversational_search_service.DeleteConversationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + conversational_search_service.UpdateConversationRequest, + dict, +]) +def test_update_conversation(request_type, transport: str = 'grpc'): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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 = gcd_conversation.Conversation( + name='name_value', + state=gcd_conversation.Conversation.State.IN_PROGRESS, + user_pseudo_id='user_pseudo_id_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] + assert args[0] == conversational_search_service.UpdateConversationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_conversation.Conversation) + assert response.name == 'name_value' + assert response.state == gcd_conversation.Conversation.State.IN_PROGRESS + assert response.user_pseudo_id == 'user_pseudo_id_value' + + +def test_update_conversation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversation), + '__call__') as call: + client.update_conversation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversational_search_service.UpdateConversationRequest() + +@pytest.mark.asyncio +async def test_update_conversation_async(transport: str = 'grpc_asyncio', request_type=conversational_search_service.UpdateConversationRequest): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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(gcd_conversation.Conversation( + name='name_value', + state=gcd_conversation.Conversation.State.IN_PROGRESS, + user_pseudo_id='user_pseudo_id_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] + assert args[0] == conversational_search_service.UpdateConversationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_conversation.Conversation) + assert response.name == 'name_value' + assert response.state == gcd_conversation.Conversation.State.IN_PROGRESS + assert response.user_pseudo_id == 'user_pseudo_id_value' + + +@pytest.mark.asyncio +async def test_update_conversation_async_from_dict(): + await test_update_conversation_async(request_type=dict) + + +def test_update_conversation_field_headers(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversational_search_service.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 = gcd_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 = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversational_search_service.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(gcd_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 = ConversationalSearchServiceClient( + 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 = gcd_conversation.Conversation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_conversation( + conversation=gcd_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 = gcd_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 = ConversationalSearchServiceClient( + credentials=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( + conversational_search_service.UpdateConversationRequest(), + conversation=gcd_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 = ConversationalSearchServiceAsyncClient( + 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 = gcd_conversation.Conversation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_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=gcd_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 = gcd_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 = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_conversation( + conversational_search_service.UpdateConversationRequest(), + conversation=gcd_conversation.Conversation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + conversational_search_service.GetConversationRequest, + dict, +]) +def test_get_conversation(request_type, transport: str = 'grpc'): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.Conversation( + name='name_value', + state=conversation.Conversation.State.IN_PROGRESS, + user_pseudo_id='user_pseudo_id_value', + ) + response = client.get_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] == conversational_search_service.GetConversationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, conversation.Conversation) + assert response.name == 'name_value' + assert response.state == conversation.Conversation.State.IN_PROGRESS + assert response.user_pseudo_id == 'user_pseudo_id_value' + + +def test_get_conversation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversation), + '__call__') as call: + client.get_conversation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversational_search_service.GetConversationRequest() + +@pytest.mark.asyncio +async def test_get_conversation_async(transport: str = 'grpc_asyncio', request_type=conversational_search_service.GetConversationRequest): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation( + name='name_value', + state=conversation.Conversation.State.IN_PROGRESS, + user_pseudo_id='user_pseudo_id_value', + )) + response = await client.get_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == conversational_search_service.GetConversationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, conversation.Conversation) + assert response.name == 'name_value' + assert response.state == conversation.Conversation.State.IN_PROGRESS + assert response.user_pseudo_id == 'user_pseudo_id_value' + + +@pytest.mark.asyncio +async def test_get_conversation_async_from_dict(): + await test_get_conversation_async(request_type=dict) + + +def test_get_conversation_field_headers(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversational_search_service.GetConversationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversation), + '__call__') as call: + call.return_value = conversation.Conversation() + client.get_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', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_conversation_field_headers_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversational_search_service.GetConversationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation()) + await client.get_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', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_conversation_flattened(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.Conversation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_conversation( + 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_conversation_flattened_error(): + client = ConversationalSearchServiceClient( + credentials=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_conversation( + conversational_search_service.GetConversationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_conversation_flattened_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.Conversation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_conversation( + 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_conversation_flattened_error_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_conversation( + conversational_search_service.GetConversationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + conversational_search_service.ListConversationsRequest, + dict, +]) +def test_list_conversations(request_type, transport: str = 'grpc'): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversational_search_service.ListConversationsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_conversations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == conversational_search_service.ListConversationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConversationsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_conversations_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + '__call__') as call: + client.list_conversations() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversational_search_service.ListConversationsRequest() + +@pytest.mark.asyncio +async def test_list_conversations_async(transport: str = 'grpc_asyncio', request_type=conversational_search_service.ListConversationsRequest): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversational_search_service.ListConversationsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_conversations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == conversational_search_service.ListConversationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConversationsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_conversations_async_from_dict(): + await test_list_conversations_async(request_type=dict) + + +def test_list_conversations_field_headers(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversational_search_service.ListConversationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + '__call__') as call: + call.return_value = conversational_search_service.ListConversationsResponse() + client.list_conversations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_conversations_field_headers_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversational_search_service.ListConversationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversational_search_service.ListConversationsResponse()) + await client.list_conversations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_conversations_flattened(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversational_search_service.ListConversationsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_conversations( + 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_conversations_flattened_error(): + client = ConversationalSearchServiceClient( + credentials=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_conversations( + conversational_search_service.ListConversationsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_conversations_flattened_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversational_search_service.ListConversationsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversational_search_service.ListConversationsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_conversations( + 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_conversations_flattened_error_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_conversations( + conversational_search_service.ListConversationsRequest(), + parent='parent_value', + ) + + +def test_list_conversations_pager(transport_name: str = "grpc"): + client = ConversationalSearchServiceClient( + 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_conversations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + conversation.Conversation(), + ], + next_page_token='abc', + ), + conversational_search_service.ListConversationsResponse( + conversations=[], + next_page_token='def', + ), + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + ], + next_page_token='ghi', + ), + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_conversations(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, conversation.Conversation) + for i in results) +def test_list_conversations_pages(transport_name: str = "grpc"): + client = ConversationalSearchServiceClient( + 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_conversations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + conversation.Conversation(), + ], + next_page_token='abc', + ), + conversational_search_service.ListConversationsResponse( + conversations=[], + next_page_token='def', + ), + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + ], + next_page_token='ghi', + ), + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + ], + ), + RuntimeError, + ) + pages = list(client.list_conversations(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_conversations_async_pager(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + conversation.Conversation(), + ], + next_page_token='abc', + ), + conversational_search_service.ListConversationsResponse( + conversations=[], + next_page_token='def', + ), + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + ], + next_page_token='ghi', + ), + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_conversations(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, conversation.Conversation) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_conversations_async_pages(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + conversation.Conversation(), + ], + next_page_token='abc', + ), + conversational_search_service.ListConversationsResponse( + conversations=[], + next_page_token='def', + ), + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + ], + next_page_token='ghi', + ), + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_conversations(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", [ + conversational_search_service.ConverseConversationRequest, + dict, +]) +def test_converse_conversation_rest(request_type): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/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 = conversational_search_service.ConverseConversationResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = conversational_search_service.ConverseConversationResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.converse_conversation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, conversational_search_service.ConverseConversationResponse) + + +def test_converse_conversation_rest_required_fields(request_type=conversational_search_service.ConverseConversationRequest): + transport_class = transports.ConversationalSearchServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).converse_conversation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).converse_conversation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = conversational_search_service.ConverseConversationResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = conversational_search_service.ConverseConversationResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.converse_conversation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_converse_conversation_rest_unset_required_fields(): + transport = transports.ConversationalSearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.converse_conversation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "query", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_converse_conversation_rest_interceptors(null_interceptor): + transport = transports.ConversationalSearchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConversationalSearchServiceRestInterceptor(), + ) + client = ConversationalSearchServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "post_converse_conversation") as post, \ + mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "pre_converse_conversation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = conversational_search_service.ConverseConversationRequest.pb(conversational_search_service.ConverseConversationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = conversational_search_service.ConverseConversationResponse.to_json(conversational_search_service.ConverseConversationResponse()) + + request = conversational_search_service.ConverseConversationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = conversational_search_service.ConverseConversationResponse() + + client.converse_conversation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_converse_conversation_rest_bad_request(transport: str = 'rest', request_type=conversational_search_service.ConverseConversationRequest): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.converse_conversation(request) + + +def test_converse_conversation_rest_flattened(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = conversational_search_service.ConverseConversationResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + query=conversation.TextInput(input='input_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 = conversational_search_service.ConverseConversationResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.converse_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/{name=projects/*/locations/*/dataStores/*/conversations/*}:converse" % client.transport._host, args[1]) + + +def test_converse_conversation_rest_flattened_error(transport: str = 'rest'): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.converse_conversation( + conversational_search_service.ConverseConversationRequest(), + name='name_value', + query=conversation.TextInput(input='input_value'), + ) + + +def test_converse_conversation_rest_error(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + conversational_search_service.CreateConversationRequest, + dict, +]) +def test_create_conversation_rest(request_type): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + request_init["conversation"] = {'name': 'name_value', 'state': 1, 'user_pseudo_id': 'user_pseudo_id_value', 'messages': [{'user_input': {'input': 'input_value', 'context': {'context_documents': ['context_documents_value1', 'context_documents_value2'], 'active_document': 'active_document_value'}}, 'reply': {'summary': {'summary_text': 'summary_text_value', 'summary_skipped_reasons': [1], 'safety_attributes': {'categories': ['categories_value1', 'categories_value2'], 'scores': [0.656, 0.657]}}}, 'create_time': {'seconds': 751, 'nanos': 543}}], 'start_time': {}, 'end_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 = conversational_search_service.CreateConversationRequest.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 = gcd_conversation.Conversation( + name='name_value', + state=gcd_conversation.Conversation.State.IN_PROGRESS, + user_pseudo_id='user_pseudo_id_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 = gcd_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 + response = client.create_conversation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_conversation.Conversation) + assert response.name == 'name_value' + assert response.state == gcd_conversation.Conversation.State.IN_PROGRESS + assert response.user_pseudo_id == 'user_pseudo_id_value' + + +def test_create_conversation_rest_required_fields(request_type=conversational_search_service.CreateConversationRequest): + transport_class = transports.ConversationalSearchServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_conversation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_conversation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcd_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': "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 = gcd_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 + + response = client.create_conversation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_conversation_rest_unset_required_fields(): + transport = transports.ConversationalSearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_conversation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "conversation", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_conversation_rest_interceptors(null_interceptor): + transport = transports.ConversationalSearchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConversationalSearchServiceRestInterceptor(), + ) + client = ConversationalSearchServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "post_create_conversation") as post, \ + mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "pre_create_conversation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = conversational_search_service.CreateConversationRequest.pb(conversational_search_service.CreateConversationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcd_conversation.Conversation.to_json(gcd_conversation.Conversation()) + + request = conversational_search_service.CreateConversationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcd_conversation.Conversation() + + client.create_conversation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_conversation_rest_bad_request(transport: str = 'rest', request_type=conversational_search_service.CreateConversationRequest): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_conversation(request) + + +def test_create_conversation_rest_flattened(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcd_conversation.Conversation() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + conversation=gcd_conversation.Conversation(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 = gcd_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 + + client.create_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/{parent=projects/*/locations/*/dataStores/*}/conversations" % client.transport._host, args[1]) + + +def test_create_conversation_rest_flattened_error(transport: str = 'rest'): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.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_conversation( + conversational_search_service.CreateConversationRequest(), + parent='parent_value', + conversation=gcd_conversation.Conversation(name='name_value'), + ) + + +def test_create_conversation_rest_error(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + conversational_search_service.DeleteConversationRequest, + dict, +]) +def test_delete_conversation_rest(request_type): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_conversation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_conversation_rest_required_fields(request_type=conversational_search_service.DeleteConversationRequest): + transport_class = transports.ConversationalSearchServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_conversation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_conversation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = ConversationalSearchServiceClient( + 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 + + response = client.delete_conversation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_conversation_rest_unset_required_fields(): + transport = transports.ConversationalSearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_conversation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_conversation_rest_interceptors(null_interceptor): + transport = transports.ConversationalSearchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConversationalSearchServiceRestInterceptor(), + ) + client = ConversationalSearchServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "pre_delete_conversation") as pre: + pre.assert_not_called() + pb_message = conversational_search_service.DeleteConversationRequest.pb(conversational_search_service.DeleteConversationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = conversational_search_service.DeleteConversationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_conversation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_conversation_rest_bad_request(transport: str = 'rest', request_type=conversational_search_service.DeleteConversationRequest): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_conversation(request) + + +def test_delete_conversation_rest_flattened(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/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 = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_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/{name=projects/*/locations/*/dataStores/*/conversations/*}" % client.transport._host, args[1]) + + +def test_delete_conversation_rest_flattened_error(transport: str = 'rest'): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.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_conversation( + conversational_search_service.DeleteConversationRequest(), + name='name_value', + ) + + +def test_delete_conversation_rest_error(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + conversational_search_service.UpdateConversationRequest, + dict, +]) +def test_update_conversation_rest(request_type): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'conversation': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'}} + request_init["conversation"] = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4', 'state': 1, 'user_pseudo_id': 'user_pseudo_id_value', 'messages': [{'user_input': {'input': 'input_value', 'context': {'context_documents': ['context_documents_value1', 'context_documents_value2'], 'active_document': 'active_document_value'}}, 'reply': {'summary': {'summary_text': 'summary_text_value', 'summary_skipped_reasons': [1], 'safety_attributes': {'categories': ['categories_value1', 'categories_value2'], 'scores': [0.656, 0.657]}}}, 'create_time': {'seconds': 751, 'nanos': 543}}], 'start_time': {}, 'end_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 = conversational_search_service.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 = gcd_conversation.Conversation( + name='name_value', + state=gcd_conversation.Conversation.State.IN_PROGRESS, + user_pseudo_id='user_pseudo_id_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 = gcd_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 + response = client.update_conversation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_conversation.Conversation) + assert response.name == 'name_value' + assert response.state == gcd_conversation.Conversation.State.IN_PROGRESS + assert response.user_pseudo_id == 'user_pseudo_id_value' + + +def test_update_conversation_rest_required_fields(request_type=conversational_search_service.UpdateConversationRequest): + transport_class = transports.ConversationalSearchServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_conversation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_conversation._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcd_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 = gcd_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 + + response = client.update_conversation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_conversation_rest_unset_required_fields(): + transport = transports.ConversationalSearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_conversation._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("conversation", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_conversation_rest_interceptors(null_interceptor): + transport = transports.ConversationalSearchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConversationalSearchServiceRestInterceptor(), + ) + client = ConversationalSearchServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "post_update_conversation") as post, \ + mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "pre_update_conversation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = conversational_search_service.UpdateConversationRequest.pb(conversational_search_service.UpdateConversationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcd_conversation.Conversation.to_json(gcd_conversation.Conversation()) + + request = conversational_search_service.UpdateConversationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcd_conversation.Conversation() + + client.update_conversation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_conversation_rest_bad_request(transport: str = 'rest', request_type=conversational_search_service.UpdateConversationRequest): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'conversation': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_conversation(request) + + +def test_update_conversation_rest_flattened(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcd_conversation.Conversation() + + # get arguments that satisfy an http rule for this method + sample_request = {'conversation': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + conversation=gcd_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 = gcd_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 + + 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/*/dataStores/*/conversations/*}" % client.transport._host, args[1]) + + +def test_update_conversation_rest_flattened_error(transport: str = 'rest'): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.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( + conversational_search_service.UpdateConversationRequest(), + conversation=gcd_conversation.Conversation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_conversation_rest_error(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + conversational_search_service.GetConversationRequest, + dict, +]) +def test_get_conversation_rest(request_type): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/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 = conversation.Conversation( + name='name_value', + state=conversation.Conversation.State.IN_PROGRESS, + user_pseudo_id='user_pseudo_id_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 = 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 + response = client.get_conversation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, conversation.Conversation) + assert response.name == 'name_value' + assert response.state == conversation.Conversation.State.IN_PROGRESS + assert response.user_pseudo_id == 'user_pseudo_id_value' + + +def test_get_conversation_rest_required_fields(request_type=conversational_search_service.GetConversationRequest): + transport_class = transports.ConversationalSearchServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_conversation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_conversation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = 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': "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 = 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 + + response = client.get_conversation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_conversation_rest_unset_required_fields(): + transport = transports.ConversationalSearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_conversation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_conversation_rest_interceptors(null_interceptor): + transport = transports.ConversationalSearchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConversationalSearchServiceRestInterceptor(), + ) + client = ConversationalSearchServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "post_get_conversation") as post, \ + mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "pre_get_conversation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = conversational_search_service.GetConversationRequest.pb(conversational_search_service.GetConversationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = conversation.Conversation.to_json(conversation.Conversation()) + + request = conversational_search_service.GetConversationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = conversation.Conversation() + + client.get_conversation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_conversation_rest_bad_request(transport: str = 'rest', request_type=conversational_search_service.GetConversationRequest): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_conversation(request) + + +def test_get_conversation_rest_flattened(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = conversation.Conversation() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/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 = 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 + + client.get_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/{name=projects/*/locations/*/dataStores/*/conversations/*}" % client.transport._host, args[1]) + + +def test_get_conversation_rest_flattened_error(transport: str = 'rest'): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.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_conversation( + conversational_search_service.GetConversationRequest(), + name='name_value', + ) + + +def test_get_conversation_rest_error(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + conversational_search_service.ListConversationsRequest, + dict, +]) +def test_list_conversations_rest(request_type): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/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 = conversational_search_service.ListConversationsResponse( + next_page_token='next_page_token_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 = conversational_search_service.ListConversationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_conversations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConversationsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_conversations_rest_required_fields(request_type=conversational_search_service.ListConversationsRequest): + transport_class = transports.ConversationalSearchServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_conversations._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_conversations._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = conversational_search_service.ListConversationsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = conversational_search_service.ListConversationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_conversations(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_conversations_rest_unset_required_fields(): + transport = transports.ConversationalSearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_conversations._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_conversations_rest_interceptors(null_interceptor): + transport = transports.ConversationalSearchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConversationalSearchServiceRestInterceptor(), + ) + client = ConversationalSearchServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "post_list_conversations") as post, \ + mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "pre_list_conversations") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = conversational_search_service.ListConversationsRequest.pb(conversational_search_service.ListConversationsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = conversational_search_service.ListConversationsResponse.to_json(conversational_search_service.ListConversationsResponse()) + + request = conversational_search_service.ListConversationsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = conversational_search_service.ListConversationsResponse() + + client.list_conversations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_conversations_rest_bad_request(transport: str = 'rest', request_type=conversational_search_service.ListConversationsRequest): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_conversations(request) + + +def test_list_conversations_rest_flattened(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = conversational_search_service.ListConversationsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/dataStores/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 = conversational_search_service.ListConversationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_conversations(**mock_args) + + # Establish that the underlying call 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/*/dataStores/*}/conversations" % client.transport._host, args[1]) + + +def test_list_conversations_rest_flattened_error(transport: str = 'rest'): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.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_conversations( + conversational_search_service.ListConversationsRequest(), + parent='parent_value', + ) + + +def test_list_conversations_rest_pager(transport: str = 'rest'): + client = ConversationalSearchServiceClient( + 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 = ( + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + conversation.Conversation(), + ], + next_page_token='abc', + ), + conversational_search_service.ListConversationsResponse( + conversations=[], + next_page_token='def', + ), + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + ], + next_page_token='ghi', + ), + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(conversational_search_service.ListConversationsResponse.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/dataStores/sample3'} + + pager = client.list_conversations(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, conversation.Conversation) + for i in results) + + pages = list(client.list_conversations(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.ConversationalSearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ConversationalSearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ConversationalSearchServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ConversationalSearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ConversationalSearchServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ConversationalSearchServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ConversationalSearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ConversationalSearchServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ConversationalSearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ConversationalSearchServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ConversationalSearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ConversationalSearchServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ConversationalSearchServiceGrpcTransport, + transports.ConversationalSearchServiceGrpcAsyncIOTransport, + transports.ConversationalSearchServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = ConversationalSearchServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ConversationalSearchServiceGrpcTransport, + ) + +def test_conversational_search_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ConversationalSearchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_conversational_search_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.discoveryengine_v1.services.conversational_search_service.transports.ConversationalSearchServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ConversationalSearchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'converse_conversation', + 'create_conversation', + 'delete_conversation', + 'update_conversation', + 'get_conversation', + 'list_conversations', + 'get_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_conversational_search_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.discoveryengine_v1.services.conversational_search_service.transports.ConversationalSearchServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ConversationalSearchServiceTransport( + 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_conversational_search_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.discoveryengine_v1.services.conversational_search_service.transports.ConversationalSearchServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ConversationalSearchServiceTransport() + adc.assert_called_once() + + +def test_conversational_search_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) + ConversationalSearchServiceClient() + 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.ConversationalSearchServiceGrpcTransport, + transports.ConversationalSearchServiceGrpcAsyncIOTransport, + ], +) +def test_conversational_search_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.ConversationalSearchServiceGrpcTransport, + transports.ConversationalSearchServiceGrpcAsyncIOTransport, + transports.ConversationalSearchServiceRestTransport, + ], +) +def test_conversational_search_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.ConversationalSearchServiceGrpcTransport, grpc_helpers), + (transports.ConversationalSearchServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_conversational_search_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ConversationalSearchServiceGrpcTransport, transports.ConversationalSearchServiceGrpcAsyncIOTransport]) +def test_conversational_search_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_conversational_search_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.ConversationalSearchServiceRestTransport ( + 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_conversational_search_service_host_no_port(transport_name): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_conversational_search_service_host_with_port(transport_name): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_conversational_search_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ConversationalSearchServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ConversationalSearchServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.converse_conversation._session + session2 = client2.transport.converse_conversation._session + assert session1 != session2 + session1 = client1.transport.create_conversation._session + session2 = client2.transport.create_conversation._session + assert session1 != session2 + 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 + session1 = client1.transport.list_conversations._session + session2 = client2.transport.list_conversations._session + assert session1 != session2 +def test_conversational_search_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ConversationalSearchServiceGrpcTransport( + 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_conversational_search_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ConversationalSearchServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.ConversationalSearchServiceGrpcTransport, transports.ConversationalSearchServiceGrpcAsyncIOTransport]) +def test_conversational_search_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.ConversationalSearchServiceGrpcTransport, transports.ConversationalSearchServiceGrpcAsyncIOTransport]) +def test_conversational_search_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_conversation_path(): + project = "squid" + location = "clam" + data_store = "whelk" + conversation = "octopus" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/conversations/{conversation}".format(project=project, location=location, data_store=data_store, conversation=conversation, ) + actual = ConversationalSearchServiceClient.conversation_path(project, location, data_store, conversation) + assert expected == actual + + +def test_parse_conversation_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "data_store": "cuttlefish", + "conversation": "mussel", + } + path = ConversationalSearchServiceClient.conversation_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationalSearchServiceClient.parse_conversation_path(path) + assert expected == actual + +def test_data_store_path(): + project = "winkle" + location = "nautilus" + data_store = "scallop" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) + actual = ConversationalSearchServiceClient.data_store_path(project, location, data_store) + assert expected == actual + + +def test_parse_data_store_path(): + expected = { + "project": "abalone", + "location": "squid", + "data_store": "clam", + } + path = ConversationalSearchServiceClient.data_store_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationalSearchServiceClient.parse_data_store_path(path) + assert expected == actual + +def test_document_path(): + project = "whelk" + location = "octopus" + data_store = "oyster" + branch = "nudibranch" + document = "cuttlefish" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) + actual = ConversationalSearchServiceClient.document_path(project, location, data_store, branch, document) + assert expected == actual + + +def test_parse_document_path(): + expected = { + "project": "mussel", + "location": "winkle", + "data_store": "nautilus", + "branch": "scallop", + "document": "abalone", + } + path = ConversationalSearchServiceClient.document_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationalSearchServiceClient.parse_document_path(path) + assert expected == actual + +def test_serving_config_path(): + project = "squid" + location = "clam" + data_store = "whelk" + serving_config = "octopus" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/servingConfigs/{serving_config}".format(project=project, location=location, data_store=data_store, serving_config=serving_config, ) + actual = ConversationalSearchServiceClient.serving_config_path(project, location, data_store, serving_config) + assert expected == actual + + +def test_parse_serving_config_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "data_store": "cuttlefish", + "serving_config": "mussel", + } + path = ConversationalSearchServiceClient.serving_config_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationalSearchServiceClient.parse_serving_config_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ConversationalSearchServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = ConversationalSearchServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationalSearchServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format(folder=folder, ) + actual = ConversationalSearchServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = ConversationalSearchServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationalSearchServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ConversationalSearchServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = ConversationalSearchServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationalSearchServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format(project=project, ) + actual = ConversationalSearchServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = ConversationalSearchServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationalSearchServiceClient.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 = ConversationalSearchServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = ConversationalSearchServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationalSearchServiceClient.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.ConversationalSearchServiceTransport, '_prep_wrapped_messages') as prep: + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ConversationalSearchServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = ConversationalSearchServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/operations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = ConversationalSearchServiceClient( + 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(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_get_operation(transport: str = "grpc"): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc"): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = ConversationalSearchServiceClient( + 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 = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc"): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = ConversationalSearchServiceClient( + 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 = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = ConversationalSearchServiceClient( + 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", [ + (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport), + (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_document_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_document_service.py new file mode 100644 index 000000000000..293af0486221 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_document_service.py @@ -0,0 +1,4999 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.discoveryengine_v1.services.document_service import DocumentServiceAsyncClient +from google.cloud.discoveryengine_v1.services.document_service import DocumentServiceClient +from google.cloud.discoveryengine_v1.services.document_service import pagers +from google.cloud.discoveryengine_v1.services.document_service import transports +from google.cloud.discoveryengine_v1.types import document +from google.cloud.discoveryengine_v1.types import document as gcd_document +from google.cloud.discoveryengine_v1.types import document_service +from google.cloud.discoveryengine_v1.types import import_config +from google.cloud.discoveryengine_v1.types import purge_config +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import struct_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert DocumentServiceClient._get_default_mtls_endpoint(None) is None + assert DocumentServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert DocumentServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert DocumentServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert DocumentServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert DocumentServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (DocumentServiceClient, "grpc"), + (DocumentServiceAsyncClient, "grpc_asyncio"), + (DocumentServiceClient, "rest"), +]) +def test_document_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.DocumentServiceGrpcTransport, "grpc"), + (transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.DocumentServiceRestTransport, "rest"), +]) +def test_document_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", [ + (DocumentServiceClient, "grpc"), + (DocumentServiceAsyncClient, "grpc_asyncio"), + (DocumentServiceClient, "rest"), +]) +def test_document_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +def test_document_service_client_get_transport_class(): + transport = DocumentServiceClient.get_transport_class() + available_transports = [ + transports.DocumentServiceGrpcTransport, + transports.DocumentServiceRestTransport, + ] + assert transport in available_transports + + transport = DocumentServiceClient.get_transport_class("grpc") + assert transport == transports.DocumentServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc"), + (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (DocumentServiceClient, transports.DocumentServiceRestTransport, "rest"), +]) +@mock.patch.object(DocumentServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceClient)) +@mock.patch.object(DocumentServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceAsyncClient)) +def test_document_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(DocumentServiceClient, '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(DocumentServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc", "true"), + (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc", "false"), + (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (DocumentServiceClient, transports.DocumentServiceRestTransport, "rest", "true"), + (DocumentServiceClient, transports.DocumentServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(DocumentServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceClient)) +@mock.patch.object(DocumentServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_document_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 + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + DocumentServiceClient, DocumentServiceAsyncClient +]) +@mock.patch.object(DocumentServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceClient)) +@mock.patch.object(DocumentServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceAsyncClient)) +def test_document_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc"), + (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (DocumentServiceClient, transports.DocumentServiceRestTransport, "rest"), +]) +def test_document_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, + 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", [ + (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc", grpc_helpers), + (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (DocumentServiceClient, transports.DocumentServiceRestTransport, "rest", None), +]) +def test_document_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, + scopes=None, + client_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_document_service_client_client_options_from_dict(): + with mock.patch('google.cloud.discoveryengine_v1.services.document_service.transports.DocumentServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = DocumentServiceClient( + 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", [ + (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc", grpc_helpers), + (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_document_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, + scopes=None, + client_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + document_service.GetDocumentRequest, + dict, +]) +def test_get_document(request_type, transport: str = 'grpc'): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document.Document( + name='name_value', + id='id_value', + schema_id='schema_id_value', + parent_document_id='parent_document_id_value', + json_data='json_data_value', + ) + response = client.get_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.GetDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, document.Document) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.schema_id == 'schema_id_value' + assert response.parent_document_id == 'parent_document_id_value' + + +def test_get_document_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_document), + '__call__') as call: + client.get_document() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.GetDocumentRequest() + +@pytest.mark.asyncio +async def test_get_document_async(transport: str = 'grpc_asyncio', request_type=document_service.GetDocumentRequest): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document.Document( + name='name_value', + id='id_value', + schema_id='schema_id_value', + parent_document_id='parent_document_id_value', + )) + response = await client.get_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.GetDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, document.Document) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.schema_id == 'schema_id_value' + assert response.parent_document_id == 'parent_document_id_value' + + +@pytest.mark.asyncio +async def test_get_document_async_from_dict(): + await test_get_document_async(request_type=dict) + + +def test_get_document_field_headers(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_service.GetDocumentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_document), + '__call__') as call: + call.return_value = document.Document() + client.get_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_document_field_headers_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_service.GetDocumentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_document), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.Document()) + await client.get_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_document_flattened(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document.Document() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_document( + 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_document_flattened_error(): + client = DocumentServiceClient( + credentials=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_document( + document_service.GetDocumentRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_document_flattened_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document.Document() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.Document()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_document( + 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_document_flattened_error_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_document( + document_service.GetDocumentRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + document_service.ListDocumentsRequest, + dict, +]) +def test_list_documents(request_type, transport: str = 'grpc'): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_documents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_service.ListDocumentsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.ListDocumentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDocumentsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_documents_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_documents), + '__call__') as call: + client.list_documents() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.ListDocumentsRequest() + +@pytest.mark.asyncio +async def test_list_documents_async(transport: str = 'grpc_asyncio', request_type=document_service.ListDocumentsRequest): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_documents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document_service.ListDocumentsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.ListDocumentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDocumentsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_documents_async_from_dict(): + await test_list_documents_async(request_type=dict) + + +def test_list_documents_field_headers(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_service.ListDocumentsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_documents), + '__call__') as call: + call.return_value = document_service.ListDocumentsResponse() + client.list_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_documents_field_headers_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_service.ListDocumentsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_documents), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_service.ListDocumentsResponse()) + await client.list_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_documents_flattened(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_documents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_service.ListDocumentsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_documents( + 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_documents_flattened_error(): + client = DocumentServiceClient( + credentials=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_documents( + document_service.ListDocumentsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_documents_flattened_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_documents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_service.ListDocumentsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_service.ListDocumentsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_documents( + 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_documents_flattened_error_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_documents( + document_service.ListDocumentsRequest(), + parent='parent_value', + ) + + +def test_list_documents_pager(transport_name: str = "grpc"): + client = DocumentServiceClient( + 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_documents), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + document.Document(), + ], + next_page_token='abc', + ), + document_service.ListDocumentsResponse( + documents=[], + next_page_token='def', + ), + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + ], + next_page_token='ghi', + ), + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_documents(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, document.Document) + for i in results) +def test_list_documents_pages(transport_name: str = "grpc"): + client = DocumentServiceClient( + 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_documents), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + document.Document(), + ], + next_page_token='abc', + ), + document_service.ListDocumentsResponse( + documents=[], + next_page_token='def', + ), + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + ], + next_page_token='ghi', + ), + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + ], + ), + RuntimeError, + ) + pages = list(client.list_documents(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_documents_async_pager(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_documents), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + document.Document(), + ], + next_page_token='abc', + ), + document_service.ListDocumentsResponse( + documents=[], + next_page_token='def', + ), + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + ], + next_page_token='ghi', + ), + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_documents(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, document.Document) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_documents_async_pages(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_documents), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + document.Document(), + ], + next_page_token='abc', + ), + document_service.ListDocumentsResponse( + documents=[], + next_page_token='def', + ), + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + ], + next_page_token='ghi', + ), + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_documents(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", [ + document_service.CreateDocumentRequest, + dict, +]) +def test_create_document(request_type, transport: str = 'grpc'): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_document.Document( + name='name_value', + id='id_value', + schema_id='schema_id_value', + parent_document_id='parent_document_id_value', + json_data='json_data_value', + ) + response = client.create_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.CreateDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_document.Document) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.schema_id == 'schema_id_value' + assert response.parent_document_id == 'parent_document_id_value' + + +def test_create_document_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_document), + '__call__') as call: + client.create_document() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.CreateDocumentRequest() + +@pytest.mark.asyncio +async def test_create_document_async(transport: str = 'grpc_asyncio', request_type=document_service.CreateDocumentRequest): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_document.Document( + name='name_value', + id='id_value', + schema_id='schema_id_value', + parent_document_id='parent_document_id_value', + )) + response = await client.create_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.CreateDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_document.Document) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.schema_id == 'schema_id_value' + assert response.parent_document_id == 'parent_document_id_value' + + +@pytest.mark.asyncio +async def test_create_document_async_from_dict(): + await test_create_document_async(request_type=dict) + + +def test_create_document_field_headers(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_service.CreateDocumentRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_document), + '__call__') as call: + call.return_value = gcd_document.Document() + client.create_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_document_field_headers_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_service.CreateDocumentRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_document), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_document.Document()) + await client.create_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_document_flattened(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_document.Document() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_document( + parent='parent_value', + document=gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), + document_id='document_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].document + mock_val = gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})) + assert arg == mock_val + arg = args[0].document_id + mock_val = 'document_id_value' + assert arg == mock_val + + +def test_create_document_flattened_error(): + client = DocumentServiceClient( + credentials=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_document( + document_service.CreateDocumentRequest(), + parent='parent_value', + document=gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), + document_id='document_id_value', + ) + +@pytest.mark.asyncio +async def test_create_document_flattened_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_document.Document() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_document.Document()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_document( + parent='parent_value', + document=gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), + document_id='document_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].document + mock_val = gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})) + assert arg == mock_val + arg = args[0].document_id + mock_val = 'document_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_document_flattened_error_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_document( + document_service.CreateDocumentRequest(), + parent='parent_value', + document=gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), + document_id='document_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + document_service.UpdateDocumentRequest, + dict, +]) +def test_update_document(request_type, transport: str = 'grpc'): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document.Document( + name='name_value', + id='id_value', + schema_id='schema_id_value', + parent_document_id='parent_document_id_value', + json_data='json_data_value', + ) + response = client.update_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.UpdateDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, document.Document) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.schema_id == 'schema_id_value' + assert response.parent_document_id == 'parent_document_id_value' + + +def test_update_document_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_document), + '__call__') as call: + client.update_document() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.UpdateDocumentRequest() + +@pytest.mark.asyncio +async def test_update_document_async(transport: str = 'grpc_asyncio', request_type=document_service.UpdateDocumentRequest): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document.Document( + name='name_value', + id='id_value', + schema_id='schema_id_value', + parent_document_id='parent_document_id_value', + )) + response = await client.update_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.UpdateDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, document.Document) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.schema_id == 'schema_id_value' + assert response.parent_document_id == 'parent_document_id_value' + + +@pytest.mark.asyncio +async def test_update_document_async_from_dict(): + await test_update_document_async(request_type=dict) + + +def test_update_document_field_headers(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_service.UpdateDocumentRequest() + + request.document.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_document), + '__call__') as call: + call.return_value = document.Document() + client.update_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'document.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_document_field_headers_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_service.UpdateDocumentRequest() + + request.document.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_document), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.Document()) + await client.update_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'document.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + document_service.DeleteDocumentRequest, + dict, +]) +def test_delete_document(request_type, transport: str = 'grpc'): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.DeleteDocumentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_document_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_document), + '__call__') as call: + client.delete_document() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.DeleteDocumentRequest() + +@pytest.mark.asyncio +async def test_delete_document_async(transport: str = 'grpc_asyncio', request_type=document_service.DeleteDocumentRequest): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.DeleteDocumentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_document_async_from_dict(): + await test_delete_document_async(request_type=dict) + + +def test_delete_document_field_headers(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_service.DeleteDocumentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_document), + '__call__') as call: + call.return_value = None + client.delete_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_document_field_headers_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_service.DeleteDocumentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_document), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_document_flattened(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_document), + '__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_document( + 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_document_flattened_error(): + client = DocumentServiceClient( + credentials=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_document( + document_service.DeleteDocumentRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_document_flattened_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_document), + '__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_document( + 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_document_flattened_error_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_document( + document_service.DeleteDocumentRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportDocumentsRequest, + dict, +]) +def test_import_documents(request_type, transport: str = 'grpc'): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_documents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportDocumentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_documents_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_documents), + '__call__') as call: + client.import_documents() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportDocumentsRequest() + +@pytest.mark.asyncio +async def test_import_documents_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportDocumentsRequest): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_documents), + '__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_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportDocumentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_documents_async_from_dict(): + await test_import_documents_async(request_type=dict) + + +def test_import_documents_field_headers(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportDocumentsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_documents), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_import_documents_field_headers_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportDocumentsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_documents), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + purge_config.PurgeDocumentsRequest, + dict, +]) +def test_purge_documents(request_type, transport: str = 'grpc'): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_documents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.purge_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeDocumentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_purge_documents_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_documents), + '__call__') as call: + client.purge_documents() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeDocumentsRequest() + +@pytest.mark.asyncio +async def test_purge_documents_async(transport: str = 'grpc_asyncio', request_type=purge_config.PurgeDocumentsRequest): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_documents), + '__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.purge_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeDocumentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_purge_documents_async_from_dict(): + await test_purge_documents_async(request_type=dict) + + +def test_purge_documents_field_headers(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = purge_config.PurgeDocumentsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_documents), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.purge_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_purge_documents_field_headers_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = purge_config.PurgeDocumentsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_documents), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.purge_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + document_service.GetDocumentRequest, + dict, +]) +def test_get_document_rest(request_type): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = document.Document( + name='name_value', + id='id_value', + schema_id='schema_id_value', + parent_document_id='parent_document_id_value', + json_data='json_data_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 = document.Document.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_document(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, document.Document) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.schema_id == 'schema_id_value' + assert response.parent_document_id == 'parent_document_id_value' + + +def test_get_document_rest_required_fields(request_type=document_service.GetDocumentRequest): + transport_class = transports.DocumentServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_document._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_document._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = document.Document() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = document.Document.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_document(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_document_rest_unset_required_fields(): + transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_document._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_document_rest_interceptors(null_interceptor): + transport = transports.DocumentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), + ) + client = DocumentServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DocumentServiceRestInterceptor, "post_get_document") as post, \ + mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_get_document") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_service.GetDocumentRequest.pb(document_service.GetDocumentRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = document.Document.to_json(document.Document()) + + request = document_service.GetDocumentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = document.Document() + + client.get_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_document_rest_bad_request(transport: str = 'rest', request_type=document_service.GetDocumentRequest): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_document(request) + + +def test_get_document_rest_flattened(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = document.Document() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = document.Document.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_document(**mock_args) + + # Establish that the underlying call 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/*/dataStores/*/branches/*/documents/*}" % client.transport._host, args[1]) + + +def test_get_document_rest_flattened_error(transport: str = 'rest'): + client = DocumentServiceClient( + credentials=ga_credentials.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_document( + document_service.GetDocumentRequest(), + name='name_value', + ) + + +def test_get_document_rest_error(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_service.ListDocumentsRequest, + dict, +]) +def test_list_documents_rest(request_type): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/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 = document_service.ListDocumentsResponse( + next_page_token='next_page_token_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 = document_service.ListDocumentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_documents(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDocumentsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_documents_rest_required_fields(request_type=document_service.ListDocumentsRequest): + transport_class = transports.DocumentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_documents._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_documents._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = document_service.ListDocumentsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = document_service.ListDocumentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_documents(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_documents_rest_unset_required_fields(): + transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_documents._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_documents_rest_interceptors(null_interceptor): + transport = transports.DocumentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), + ) + client = DocumentServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DocumentServiceRestInterceptor, "post_list_documents") as post, \ + mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_list_documents") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_service.ListDocumentsRequest.pb(document_service.ListDocumentsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = document_service.ListDocumentsResponse.to_json(document_service.ListDocumentsResponse()) + + request = document_service.ListDocumentsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = document_service.ListDocumentsResponse() + + client.list_documents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_documents_rest_bad_request(transport: str = 'rest', request_type=document_service.ListDocumentsRequest): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_documents(request) + + +def test_list_documents_rest_flattened(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = document_service.ListDocumentsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = document_service.ListDocumentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_documents(**mock_args) + + # Establish that the underlying call 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/*/dataStores/*/branches/*}/documents" % client.transport._host, args[1]) + + +def test_list_documents_rest_flattened_error(transport: str = 'rest'): + client = DocumentServiceClient( + credentials=ga_credentials.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_documents( + document_service.ListDocumentsRequest(), + parent='parent_value', + ) + + +def test_list_documents_rest_pager(transport: str = 'rest'): + client = DocumentServiceClient( + 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 = ( + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + document.Document(), + ], + next_page_token='abc', + ), + document_service.ListDocumentsResponse( + documents=[], + next_page_token='def', + ), + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + ], + next_page_token='ghi', + ), + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(document_service.ListDocumentsResponse.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/dataStores/sample3/branches/sample4'} + + pager = client.list_documents(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, document.Document) + for i in results) + + pages = list(client.list_documents(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + document_service.CreateDocumentRequest, + dict, +]) +def test_create_document_rest(request_type): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} + request_init["document"] = {'struct_data': {'fields': {}}, 'json_data': 'json_data_value', 'name': 'name_value', 'id': 'id_value', 'schema_id': 'schema_id_value', 'content': {'raw_bytes': b'raw_bytes_blob', 'uri': 'uri_value', 'mime_type': 'mime_type_value'}, 'parent_document_id': 'parent_document_id_value', 'derived_struct_data': {}} + # 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 = document_service.CreateDocumentRequest.meta.fields["document"] + + 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["document"].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["document"][field])): + del request_init["document"][field][i][subfield] + else: + del request_init["document"][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 = gcd_document.Document( + name='name_value', + id='id_value', + schema_id='schema_id_value', + parent_document_id='parent_document_id_value', + json_data='json_data_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 = gcd_document.Document.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_document(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_document.Document) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.schema_id == 'schema_id_value' + assert response.parent_document_id == 'parent_document_id_value' + + +def test_create_document_rest_required_fields(request_type=document_service.CreateDocumentRequest): + transport_class = transports.DocumentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["document_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "documentId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_document._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "documentId" in jsonified_request + assert jsonified_request["documentId"] == request_init["document_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["documentId"] = 'document_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_document._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("document_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "documentId" in jsonified_request + assert jsonified_request["documentId"] == 'document_id_value' + + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcd_document.Document() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcd_document.Document.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_document(request) + + expected_params = [ + ( + "documentId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_document_rest_unset_required_fields(): + transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_document._get_unset_required_fields({}) + assert set(unset_fields) == (set(("documentId", )) & set(("parent", "document", "documentId", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_document_rest_interceptors(null_interceptor): + transport = transports.DocumentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), + ) + client = DocumentServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DocumentServiceRestInterceptor, "post_create_document") as post, \ + mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_create_document") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_service.CreateDocumentRequest.pb(document_service.CreateDocumentRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcd_document.Document.to_json(gcd_document.Document()) + + request = document_service.CreateDocumentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcd_document.Document() + + client.create_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_document_rest_bad_request(transport: str = 'rest', request_type=document_service.CreateDocumentRequest): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_document(request) + + +def test_create_document_rest_flattened(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcd_document.Document() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + document=gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), + document_id='document_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 = gcd_document.Document.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_document(**mock_args) + + # Establish that the underlying call 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/*/dataStores/*/branches/*}/documents" % client.transport._host, args[1]) + + +def test_create_document_rest_flattened_error(transport: str = 'rest'): + client = DocumentServiceClient( + credentials=ga_credentials.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_document( + document_service.CreateDocumentRequest(), + parent='parent_value', + document=gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), + document_id='document_id_value', + ) + + +def test_create_document_rest_error(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_service.UpdateDocumentRequest, + dict, +]) +def test_update_document_rest(request_type): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'document': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'}} + request_init["document"] = {'struct_data': {'fields': {}}, 'json_data': 'json_data_value', 'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5', 'id': 'id_value', 'schema_id': 'schema_id_value', 'content': {'raw_bytes': b'raw_bytes_blob', 'uri': 'uri_value', 'mime_type': 'mime_type_value'}, 'parent_document_id': 'parent_document_id_value', 'derived_struct_data': {}} + # 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 = document_service.UpdateDocumentRequest.meta.fields["document"] + + 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["document"].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["document"][field])): + del request_init["document"][field][i][subfield] + else: + del request_init["document"][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 = document.Document( + name='name_value', + id='id_value', + schema_id='schema_id_value', + parent_document_id='parent_document_id_value', + json_data='json_data_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 = document.Document.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_document(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, document.Document) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.schema_id == 'schema_id_value' + assert response.parent_document_id == 'parent_document_id_value' + + +def test_update_document_rest_required_fields(request_type=document_service.UpdateDocumentRequest): + transport_class = transports.DocumentServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_document._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_document._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = document.Document() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = document.Document.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_document(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_document_rest_unset_required_fields(): + transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_document._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", )) & set(("document", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_document_rest_interceptors(null_interceptor): + transport = transports.DocumentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), + ) + client = DocumentServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DocumentServiceRestInterceptor, "post_update_document") as post, \ + mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_update_document") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_service.UpdateDocumentRequest.pb(document_service.UpdateDocumentRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = document.Document.to_json(document.Document()) + + request = document_service.UpdateDocumentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = document.Document() + + client.update_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_document_rest_bad_request(transport: str = 'rest', request_type=document_service.UpdateDocumentRequest): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'document': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_document(request) + + +def test_update_document_rest_error(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_service.DeleteDocumentRequest, + dict, +]) +def test_delete_document_rest(request_type): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_document(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_document_rest_required_fields(request_type=document_service.DeleteDocumentRequest): + transport_class = transports.DocumentServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_document._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_document._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DocumentServiceClient( + 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 + + response = client.delete_document(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_document_rest_unset_required_fields(): + transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_document._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_document_rest_interceptors(null_interceptor): + transport = transports.DocumentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), + ) + client = DocumentServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_delete_document") as pre: + pre.assert_not_called() + pb_message = document_service.DeleteDocumentRequest.pb(document_service.DeleteDocumentRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = document_service.DeleteDocumentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_document_rest_bad_request(transport: str = 'rest', request_type=document_service.DeleteDocumentRequest): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_document(request) + + +def test_delete_document_rest_flattened(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_document(**mock_args) + + # Establish that the underlying call 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/*/dataStores/*/branches/*/documents/*}" % client.transport._host, args[1]) + + +def test_delete_document_rest_flattened_error(transport: str = 'rest'): + client = DocumentServiceClient( + credentials=ga_credentials.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_document( + document_service.DeleteDocumentRequest(), + name='name_value', + ) + + +def test_delete_document_rest_error(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportDocumentsRequest, + dict, +]) +def test_import_documents_rest(request_type): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.import_documents(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_import_documents_rest_required_fields(request_type=import_config.ImportDocumentsRequest): + transport_class = transports.DocumentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_documents._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_documents._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.import_documents(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_import_documents_rest_unset_required_fields(): + transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.import_documents._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_import_documents_rest_interceptors(null_interceptor): + transport = transports.DocumentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), + ) + client = DocumentServiceClient(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.DocumentServiceRestInterceptor, "post_import_documents") as post, \ + mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_import_documents") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = import_config.ImportDocumentsRequest.pb(import_config.ImportDocumentsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = import_config.ImportDocumentsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.import_documents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_import_documents_rest_bad_request(transport: str = 'rest', request_type=import_config.ImportDocumentsRequest): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.import_documents(request) + + +def test_import_documents_rest_error(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + purge_config.PurgeDocumentsRequest, + dict, +]) +def test_purge_documents_rest(request_type): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.purge_documents(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_purge_documents_rest_required_fields(request_type=purge_config.PurgeDocumentsRequest): + transport_class = transports.DocumentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["filter"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).purge_documents._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + jsonified_request["filter"] = 'filter_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).purge_documents._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "filter" in jsonified_request + assert jsonified_request["filter"] == 'filter_value' + + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.purge_documents(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_purge_documents_rest_unset_required_fields(): + transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.purge_documents._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "filter", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_purge_documents_rest_interceptors(null_interceptor): + transport = transports.DocumentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), + ) + client = DocumentServiceClient(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.DocumentServiceRestInterceptor, "post_purge_documents") as post, \ + mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_purge_documents") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = purge_config.PurgeDocumentsRequest.pb(purge_config.PurgeDocumentsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = purge_config.PurgeDocumentsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.purge_documents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_purge_documents_rest_bad_request(transport: str = 'rest', request_type=purge_config.PurgeDocumentsRequest): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.purge_documents(request) + + +def test_purge_documents_rest_error(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.DocumentServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.DocumentServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DocumentServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.DocumentServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DocumentServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DocumentServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.DocumentServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DocumentServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.DocumentServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = DocumentServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.DocumentServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.DocumentServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.DocumentServiceGrpcTransport, + transports.DocumentServiceGrpcAsyncIOTransport, + transports.DocumentServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = DocumentServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.DocumentServiceGrpcTransport, + ) + +def test_document_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.DocumentServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_document_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.discoveryengine_v1.services.document_service.transports.DocumentServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.DocumentServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_document', + 'list_documents', + 'create_document', + 'update_document', + 'delete_document', + 'import_documents', + 'purge_documents', + 'get_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_document_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.discoveryengine_v1.services.document_service.transports.DocumentServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DocumentServiceTransport( + 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_document_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.discoveryengine_v1.services.document_service.transports.DocumentServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DocumentServiceTransport() + adc.assert_called_once() + + +def test_document_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) + DocumentServiceClient() + 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.DocumentServiceGrpcTransport, + transports.DocumentServiceGrpcAsyncIOTransport, + ], +) +def test_document_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.DocumentServiceGrpcTransport, + transports.DocumentServiceGrpcAsyncIOTransport, + transports.DocumentServiceRestTransport, + ], +) +def test_document_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.DocumentServiceGrpcTransport, grpc_helpers), + (transports.DocumentServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_document_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.DocumentServiceGrpcTransport, transports.DocumentServiceGrpcAsyncIOTransport]) +def test_document_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_document_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.DocumentServiceRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_document_service_rest_lro_client(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_document_service_host_no_port(transport_name): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_document_service_host_with_port(transport_name): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_document_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = DocumentServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = DocumentServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_document._session + session2 = client2.transport.get_document._session + assert session1 != session2 + session1 = client1.transport.list_documents._session + session2 = client2.transport.list_documents._session + assert session1 != session2 + session1 = client1.transport.create_document._session + session2 = client2.transport.create_document._session + assert session1 != session2 + session1 = client1.transport.update_document._session + session2 = client2.transport.update_document._session + assert session1 != session2 + session1 = client1.transport.delete_document._session + session2 = client2.transport.delete_document._session + assert session1 != session2 + session1 = client1.transport.import_documents._session + session2 = client2.transport.import_documents._session + assert session1 != session2 + session1 = client1.transport.purge_documents._session + session2 = client2.transport.purge_documents._session + assert session1 != session2 +def test_document_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DocumentServiceGrpcTransport( + 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_document_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DocumentServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.DocumentServiceGrpcTransport, transports.DocumentServiceGrpcAsyncIOTransport]) +def test_document_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.DocumentServiceGrpcTransport, transports.DocumentServiceGrpcAsyncIOTransport]) +def test_document_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_document_service_grpc_lro_client(): + client = DocumentServiceClient( + 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_document_service_grpc_lro_async_client(): + client = DocumentServiceAsyncClient( + 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_branch_path(): + project = "squid" + location = "clam" + data_store = "whelk" + branch = "octopus" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}".format(project=project, location=location, data_store=data_store, branch=branch, ) + actual = DocumentServiceClient.branch_path(project, location, data_store, branch) + assert expected == actual + + +def test_parse_branch_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "data_store": "cuttlefish", + "branch": "mussel", + } + path = DocumentServiceClient.branch_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentServiceClient.parse_branch_path(path) + assert expected == actual + +def test_document_path(): + project = "winkle" + location = "nautilus" + data_store = "scallop" + branch = "abalone" + document = "squid" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) + actual = DocumentServiceClient.document_path(project, location, data_store, branch, document) + assert expected == actual + + +def test_parse_document_path(): + expected = { + "project": "clam", + "location": "whelk", + "data_store": "octopus", + "branch": "oyster", + "document": "nudibranch", + } + path = DocumentServiceClient.document_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentServiceClient.parse_document_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = DocumentServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = DocumentServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = DocumentServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = DocumentServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = DocumentServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = DocumentServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = DocumentServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = DocumentServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = DocumentServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = DocumentServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentServiceClient.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.DocumentServiceTransport, '_prep_wrapped_messages') as prep: + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.DocumentServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = DocumentServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/operations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = DocumentServiceClient( + 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(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_get_operation(transport: str = "grpc"): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc"): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DocumentServiceClient( + 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 = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc"): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DocumentServiceClient( + 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 = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = DocumentServiceClient( + 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", [ + (DocumentServiceClient, transports.DocumentServiceGrpcTransport), + (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_schema_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_schema_service.py new file mode 100644 index 000000000000..a0335d58b8cd --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_schema_service.py @@ -0,0 +1,4265 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.discoveryengine_v1.services.schema_service import SchemaServiceAsyncClient +from google.cloud.discoveryengine_v1.services.schema_service import SchemaServiceClient +from google.cloud.discoveryengine_v1.services.schema_service import pagers +from google.cloud.discoveryengine_v1.services.schema_service import transports +from google.cloud.discoveryengine_v1.types import schema +from google.cloud.discoveryengine_v1.types import schema as gcd_schema +from google.cloud.discoveryengine_v1.types import schema_service +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert SchemaServiceClient._get_default_mtls_endpoint(None) is None + assert SchemaServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert SchemaServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert SchemaServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert SchemaServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert SchemaServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (SchemaServiceClient, "grpc"), + (SchemaServiceAsyncClient, "grpc_asyncio"), + (SchemaServiceClient, "rest"), +]) +def test_schema_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.SchemaServiceGrpcTransport, "grpc"), + (transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.SchemaServiceRestTransport, "rest"), +]) +def test_schema_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", [ + (SchemaServiceClient, "grpc"), + (SchemaServiceAsyncClient, "grpc_asyncio"), + (SchemaServiceClient, "rest"), +]) +def test_schema_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +def test_schema_service_client_get_transport_class(): + transport = SchemaServiceClient.get_transport_class() + available_transports = [ + transports.SchemaServiceGrpcTransport, + transports.SchemaServiceRestTransport, + ] + assert transport in available_transports + + transport = SchemaServiceClient.get_transport_class("grpc") + assert transport == transports.SchemaServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc"), + (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (SchemaServiceClient, transports.SchemaServiceRestTransport, "rest"), +]) +@mock.patch.object(SchemaServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceClient)) +@mock.patch.object(SchemaServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceAsyncClient)) +def test_schema_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(SchemaServiceClient, '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(SchemaServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc", "true"), + (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc", "false"), + (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (SchemaServiceClient, transports.SchemaServiceRestTransport, "rest", "true"), + (SchemaServiceClient, transports.SchemaServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(SchemaServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceClient)) +@mock.patch.object(SchemaServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_schema_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 + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + SchemaServiceClient, SchemaServiceAsyncClient +]) +@mock.patch.object(SchemaServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceClient)) +@mock.patch.object(SchemaServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceAsyncClient)) +def test_schema_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc"), + (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (SchemaServiceClient, transports.SchemaServiceRestTransport, "rest"), +]) +def test_schema_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, + 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", [ + (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc", grpc_helpers), + (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (SchemaServiceClient, transports.SchemaServiceRestTransport, "rest", None), +]) +def test_schema_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, + scopes=None, + client_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_schema_service_client_client_options_from_dict(): + with mock.patch('google.cloud.discoveryengine_v1.services.schema_service.transports.SchemaServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = SchemaServiceClient( + 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", [ + (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc", grpc_helpers), + (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_schema_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, + scopes=None, + client_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + schema_service.GetSchemaRequest, + dict, +]) +def test_get_schema(request_type, transport: str = 'grpc'): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = schema.Schema( + name='name_value', + json_schema='json_schema_value', + ) + response = client.get_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.GetSchemaRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, schema.Schema) + assert response.name == 'name_value' + + +def test_get_schema_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_schema), + '__call__') as call: + client.get_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.GetSchemaRequest() + +@pytest.mark.asyncio +async def test_get_schema_async(transport: str = 'grpc_asyncio', request_type=schema_service.GetSchemaRequest): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(schema.Schema( + name='name_value', + )) + response = await client.get_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.GetSchemaRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, schema.Schema) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_schema_async_from_dict(): + await test_get_schema_async(request_type=dict) + + +def test_get_schema_field_headers(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema_service.GetSchemaRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_schema), + '__call__') as call: + call.return_value = schema.Schema() + client.get_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_schema_field_headers_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema_service.GetSchemaRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_schema), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.Schema()) + await client.get_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_schema_flattened(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = schema.Schema() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_schema( + 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_schema_flattened_error(): + client = SchemaServiceClient( + credentials=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_schema( + schema_service.GetSchemaRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_schema_flattened_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = schema.Schema() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.Schema()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_schema( + 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_schema_flattened_error_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_schema( + schema_service.GetSchemaRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + schema_service.ListSchemasRequest, + dict, +]) +def test_list_schemas(request_type, transport: str = 'grpc'): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_schemas), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = schema_service.ListSchemasResponse( + next_page_token='next_page_token_value', + ) + response = client.list_schemas(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.ListSchemasRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSchemasPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_schemas_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_schemas), + '__call__') as call: + client.list_schemas() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.ListSchemasRequest() + +@pytest.mark.asyncio +async def test_list_schemas_async(transport: str = 'grpc_asyncio', request_type=schema_service.ListSchemasRequest): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_schemas), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(schema_service.ListSchemasResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_schemas(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.ListSchemasRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSchemasAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_schemas_async_from_dict(): + await test_list_schemas_async(request_type=dict) + + +def test_list_schemas_field_headers(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema_service.ListSchemasRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_schemas), + '__call__') as call: + call.return_value = schema_service.ListSchemasResponse() + client.list_schemas(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_schemas_field_headers_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema_service.ListSchemasRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_schemas), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema_service.ListSchemasResponse()) + await client.list_schemas(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_schemas_flattened(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_schemas), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = schema_service.ListSchemasResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_schemas( + 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_schemas_flattened_error(): + client = SchemaServiceClient( + credentials=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_schemas( + schema_service.ListSchemasRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_schemas_flattened_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_schemas), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = schema_service.ListSchemasResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema_service.ListSchemasResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_schemas( + 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_schemas_flattened_error_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_schemas( + schema_service.ListSchemasRequest(), + parent='parent_value', + ) + + +def test_list_schemas_pager(transport_name: str = "grpc"): + client = SchemaServiceClient( + 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_schemas), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + schema.Schema(), + ], + next_page_token='abc', + ), + schema_service.ListSchemasResponse( + schemas=[], + next_page_token='def', + ), + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + ], + next_page_token='ghi', + ), + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_schemas(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, schema.Schema) + for i in results) +def test_list_schemas_pages(transport_name: str = "grpc"): + client = SchemaServiceClient( + 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_schemas), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + schema.Schema(), + ], + next_page_token='abc', + ), + schema_service.ListSchemasResponse( + schemas=[], + next_page_token='def', + ), + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + ], + next_page_token='ghi', + ), + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + ], + ), + RuntimeError, + ) + pages = list(client.list_schemas(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_schemas_async_pager(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_schemas), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + schema.Schema(), + ], + next_page_token='abc', + ), + schema_service.ListSchemasResponse( + schemas=[], + next_page_token='def', + ), + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + ], + next_page_token='ghi', + ), + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_schemas(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, schema.Schema) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_schemas_async_pages(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_schemas), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + schema.Schema(), + ], + next_page_token='abc', + ), + schema_service.ListSchemasResponse( + schemas=[], + next_page_token='def', + ), + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + ], + next_page_token='ghi', + ), + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_schemas(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", [ + schema_service.CreateSchemaRequest, + dict, +]) +def test_create_schema(request_type, transport: str = 'grpc'): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.CreateSchemaRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_schema_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_schema), + '__call__') as call: + client.create_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.CreateSchemaRequest() + +@pytest.mark.asyncio +async def test_create_schema_async(transport: str = 'grpc_asyncio', request_type=schema_service.CreateSchemaRequest): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_schema), + '__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_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.CreateSchemaRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_schema_async_from_dict(): + await test_create_schema_async(request_type=dict) + + +def test_create_schema_field_headers(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema_service.CreateSchemaRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_schema), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_schema_field_headers_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema_service.CreateSchemaRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_schema), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_schema_flattened(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_schema), + '__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_schema( + parent='parent_value', + schema=gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), + schema_id='schema_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].schema + mock_val = gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})) + assert arg == mock_val + arg = args[0].schema_id + mock_val = 'schema_id_value' + assert arg == mock_val + + +def test_create_schema_flattened_error(): + client = SchemaServiceClient( + credentials=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_schema( + schema_service.CreateSchemaRequest(), + parent='parent_value', + schema=gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), + schema_id='schema_id_value', + ) + +@pytest.mark.asyncio +async def test_create_schema_flattened_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_schema), + '__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_schema( + parent='parent_value', + schema=gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), + schema_id='schema_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].schema + mock_val = gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})) + assert arg == mock_val + arg = args[0].schema_id + mock_val = 'schema_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_schema_flattened_error_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_schema( + schema_service.CreateSchemaRequest(), + parent='parent_value', + schema=gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), + schema_id='schema_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + schema_service.UpdateSchemaRequest, + dict, +]) +def test_update_schema(request_type, transport: str = 'grpc'): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.UpdateSchemaRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_schema_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_schema), + '__call__') as call: + client.update_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.UpdateSchemaRequest() + +@pytest.mark.asyncio +async def test_update_schema_async(transport: str = 'grpc_asyncio', request_type=schema_service.UpdateSchemaRequest): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_schema), + '__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_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.UpdateSchemaRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_schema_async_from_dict(): + await test_update_schema_async(request_type=dict) + + +def test_update_schema_field_headers(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema_service.UpdateSchemaRequest() + + request.schema.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_schema), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'schema.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_schema_field_headers_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema_service.UpdateSchemaRequest() + + request.schema.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_schema), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'schema.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + schema_service.DeleteSchemaRequest, + dict, +]) +def test_delete_schema(request_type, transport: str = 'grpc'): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.DeleteSchemaRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_schema_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_schema), + '__call__') as call: + client.delete_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.DeleteSchemaRequest() + +@pytest.mark.asyncio +async def test_delete_schema_async(transport: str = 'grpc_asyncio', request_type=schema_service.DeleteSchemaRequest): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_schema), + '__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_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.DeleteSchemaRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_schema_async_from_dict(): + await test_delete_schema_async(request_type=dict) + + +def test_delete_schema_field_headers(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema_service.DeleteSchemaRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_schema), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_schema_field_headers_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema_service.DeleteSchemaRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_schema), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_schema_flattened(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_schema), + '__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_schema( + 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_schema_flattened_error(): + client = SchemaServiceClient( + credentials=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_schema( + schema_service.DeleteSchemaRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_schema_flattened_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_schema), + '__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_schema( + 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_schema_flattened_error_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_schema( + schema_service.DeleteSchemaRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + schema_service.GetSchemaRequest, + dict, +]) +def test_get_schema_rest(request_type): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/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 = schema.Schema( + name='name_value', + json_schema='json_schema_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 = schema.Schema.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_schema(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, schema.Schema) + assert response.name == 'name_value' + + +def test_get_schema_rest_required_fields(request_type=schema_service.GetSchemaRequest): + transport_class = transports.SchemaServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = schema.Schema() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = schema.Schema.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_schema(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_schema_rest_unset_required_fields(): + transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_schema._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_schema_rest_interceptors(null_interceptor): + transport = transports.SchemaServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), + ) + client = SchemaServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SchemaServiceRestInterceptor, "post_get_schema") as post, \ + mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_get_schema") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = schema_service.GetSchemaRequest.pb(schema_service.GetSchemaRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = schema.Schema.to_json(schema.Schema()) + + request = schema_service.GetSchemaRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = schema.Schema() + + client.get_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_schema_rest_bad_request(transport: str = 'rest', request_type=schema_service.GetSchemaRequest): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_schema(request) + + +def test_get_schema_rest_flattened(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = schema.Schema() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/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 = schema.Schema.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_schema(**mock_args) + + # Establish that the underlying call 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/*/dataStores/*/schemas/*}" % client.transport._host, args[1]) + + +def test_get_schema_rest_flattened_error(transport: str = 'rest'): + client = SchemaServiceClient( + credentials=ga_credentials.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_schema( + schema_service.GetSchemaRequest(), + name='name_value', + ) + + +def test_get_schema_rest_error(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + schema_service.ListSchemasRequest, + dict, +]) +def test_list_schemas_rest(request_type): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/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 = schema_service.ListSchemasResponse( + next_page_token='next_page_token_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 = schema_service.ListSchemasResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_schemas(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSchemasPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_schemas_rest_required_fields(request_type=schema_service.ListSchemasRequest): + transport_class = transports.SchemaServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_schemas._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_schemas._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = schema_service.ListSchemasResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = schema_service.ListSchemasResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_schemas(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_schemas_rest_unset_required_fields(): + transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_schemas._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_schemas_rest_interceptors(null_interceptor): + transport = transports.SchemaServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), + ) + client = SchemaServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SchemaServiceRestInterceptor, "post_list_schemas") as post, \ + mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_list_schemas") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = schema_service.ListSchemasRequest.pb(schema_service.ListSchemasRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = schema_service.ListSchemasResponse.to_json(schema_service.ListSchemasResponse()) + + request = schema_service.ListSchemasRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = schema_service.ListSchemasResponse() + + client.list_schemas(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_schemas_rest_bad_request(transport: str = 'rest', request_type=schema_service.ListSchemasRequest): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_schemas(request) + + +def test_list_schemas_rest_flattened(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = schema_service.ListSchemasResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/dataStores/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 = schema_service.ListSchemasResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_schemas(**mock_args) + + # Establish that the underlying call 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/*/dataStores/*}/schemas" % client.transport._host, args[1]) + + +def test_list_schemas_rest_flattened_error(transport: str = 'rest'): + client = SchemaServiceClient( + credentials=ga_credentials.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_schemas( + schema_service.ListSchemasRequest(), + parent='parent_value', + ) + + +def test_list_schemas_rest_pager(transport: str = 'rest'): + client = SchemaServiceClient( + 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 = ( + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + schema.Schema(), + ], + next_page_token='abc', + ), + schema_service.ListSchemasResponse( + schemas=[], + next_page_token='def', + ), + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + ], + next_page_token='ghi', + ), + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(schema_service.ListSchemasResponse.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/dataStores/sample3'} + + pager = client.list_schemas(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, schema.Schema) + for i in results) + + pages = list(client.list_schemas(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + schema_service.CreateSchemaRequest, + dict, +]) +def test_create_schema_rest(request_type): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + request_init["schema"] = {'struct_schema': {'fields': {}}, 'json_schema': 'json_schema_value', 'name': 'name_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 = schema_service.CreateSchemaRequest.meta.fields["schema"] + + 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["schema"].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["schema"][field])): + del request_init["schema"][field][i][subfield] + else: + del request_init["schema"][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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_schema(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_schema_rest_required_fields(request_type=schema_service.CreateSchemaRequest): + transport_class = transports.SchemaServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["schema_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "schemaId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "schemaId" in jsonified_request + assert jsonified_request["schemaId"] == request_init["schema_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["schemaId"] = 'schema_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_schema._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("schema_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "schemaId" in jsonified_request + assert jsonified_request["schemaId"] == 'schema_id_value' + + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_schema(request) + + expected_params = [ + ( + "schemaId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_schema_rest_unset_required_fields(): + transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_schema._get_unset_required_fields({}) + assert set(unset_fields) == (set(("schemaId", )) & set(("parent", "schema", "schemaId", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_schema_rest_interceptors(null_interceptor): + transport = transports.SchemaServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), + ) + client = SchemaServiceClient(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.SchemaServiceRestInterceptor, "post_create_schema") as post, \ + mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_create_schema") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = schema_service.CreateSchemaRequest.pb(schema_service.CreateSchemaRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = schema_service.CreateSchemaRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_schema_rest_bad_request(transport: str = 'rest', request_type=schema_service.CreateSchemaRequest): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_schema(request) + + +def test_create_schema_rest_flattened(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.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/dataStores/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + schema=gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), + schema_id='schema_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_schema(**mock_args) + + # Establish that the underlying call 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/*/dataStores/*}/schemas" % client.transport._host, args[1]) + + +def test_create_schema_rest_flattened_error(transport: str = 'rest'): + client = SchemaServiceClient( + credentials=ga_credentials.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_schema( + schema_service.CreateSchemaRequest(), + parent='parent_value', + schema=gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), + schema_id='schema_id_value', + ) + + +def test_create_schema_rest_error(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + schema_service.UpdateSchemaRequest, + dict, +]) +def test_update_schema_rest(request_type): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'schema': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/sample4'}} + request_init["schema"] = {'struct_schema': {'fields': {}}, 'json_schema': 'json_schema_value', 'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/sample4'} + # 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 = schema_service.UpdateSchemaRequest.meta.fields["schema"] + + 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["schema"].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["schema"][field])): + del request_init["schema"][field][i][subfield] + else: + del request_init["schema"][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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_schema(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_schema_rest_required_fields(request_type=schema_service.UpdateSchemaRequest): + transport_class = transports.SchemaServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_schema._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_schema(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_schema_rest_unset_required_fields(): + transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_schema._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", )) & set(("schema", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_schema_rest_interceptors(null_interceptor): + transport = transports.SchemaServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), + ) + client = SchemaServiceClient(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.SchemaServiceRestInterceptor, "post_update_schema") as post, \ + mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_update_schema") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = schema_service.UpdateSchemaRequest.pb(schema_service.UpdateSchemaRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = schema_service.UpdateSchemaRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_schema_rest_bad_request(transport: str = 'rest', request_type=schema_service.UpdateSchemaRequest): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'schema': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/sample4'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_schema(request) + + +def test_update_schema_rest_error(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + schema_service.DeleteSchemaRequest, + dict, +]) +def test_delete_schema_rest(request_type): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_schema(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_schema_rest_required_fields(request_type=schema_service.DeleteSchemaRequest): + transport_class = transports.SchemaServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_schema(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_schema_rest_unset_required_fields(): + transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_schema._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_schema_rest_interceptors(null_interceptor): + transport = transports.SchemaServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), + ) + client = SchemaServiceClient(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.SchemaServiceRestInterceptor, "post_delete_schema") as post, \ + mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_delete_schema") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = schema_service.DeleteSchemaRequest.pb(schema_service.DeleteSchemaRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = schema_service.DeleteSchemaRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_schema_rest_bad_request(transport: str = 'rest', request_type=schema_service.DeleteSchemaRequest): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_schema(request) + + +def test_delete_schema_rest_flattened(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.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/dataStores/sample3/schemas/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_schema(**mock_args) + + # Establish that the underlying call 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/*/dataStores/*/schemas/*}" % client.transport._host, args[1]) + + +def test_delete_schema_rest_flattened_error(transport: str = 'rest'): + client = SchemaServiceClient( + credentials=ga_credentials.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_schema( + schema_service.DeleteSchemaRequest(), + name='name_value', + ) + + +def test_delete_schema_rest_error(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SchemaServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SchemaServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SchemaServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SchemaServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SchemaServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SchemaServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SchemaServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SchemaServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SchemaServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SchemaServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SchemaServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SchemaServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.SchemaServiceGrpcTransport, + transports.SchemaServiceGrpcAsyncIOTransport, + transports.SchemaServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = SchemaServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SchemaServiceGrpcTransport, + ) + +def test_schema_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SchemaServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_schema_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.discoveryengine_v1.services.schema_service.transports.SchemaServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.SchemaServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_schema', + 'list_schemas', + 'create_schema', + 'update_schema', + 'delete_schema', + 'get_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_schema_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.discoveryengine_v1.services.schema_service.transports.SchemaServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SchemaServiceTransport( + 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_schema_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.discoveryengine_v1.services.schema_service.transports.SchemaServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SchemaServiceTransport() + adc.assert_called_once() + + +def test_schema_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) + SchemaServiceClient() + 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.SchemaServiceGrpcTransport, + transports.SchemaServiceGrpcAsyncIOTransport, + ], +) +def test_schema_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.SchemaServiceGrpcTransport, + transports.SchemaServiceGrpcAsyncIOTransport, + transports.SchemaServiceRestTransport, + ], +) +def test_schema_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.SchemaServiceGrpcTransport, grpc_helpers), + (transports.SchemaServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_schema_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.SchemaServiceGrpcTransport, transports.SchemaServiceGrpcAsyncIOTransport]) +def test_schema_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_schema_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.SchemaServiceRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_schema_service_rest_lro_client(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_schema_service_host_no_port(transport_name): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_schema_service_host_with_port(transport_name): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_schema_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = SchemaServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = SchemaServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_schema._session + session2 = client2.transport.get_schema._session + assert session1 != session2 + session1 = client1.transport.list_schemas._session + session2 = client2.transport.list_schemas._session + assert session1 != session2 + session1 = client1.transport.create_schema._session + session2 = client2.transport.create_schema._session + assert session1 != session2 + session1 = client1.transport.update_schema._session + session2 = client2.transport.update_schema._session + assert session1 != session2 + session1 = client1.transport.delete_schema._session + session2 = client2.transport.delete_schema._session + assert session1 != session2 +def test_schema_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SchemaServiceGrpcTransport( + 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_schema_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SchemaServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.SchemaServiceGrpcTransport, transports.SchemaServiceGrpcAsyncIOTransport]) +def test_schema_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.SchemaServiceGrpcTransport, transports.SchemaServiceGrpcAsyncIOTransport]) +def test_schema_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_schema_service_grpc_lro_client(): + client = SchemaServiceClient( + 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_schema_service_grpc_lro_async_client(): + client = SchemaServiceAsyncClient( + 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_data_store_path(): + project = "squid" + location = "clam" + data_store = "whelk" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) + actual = SchemaServiceClient.data_store_path(project, location, data_store) + assert expected == actual + + +def test_parse_data_store_path(): + expected = { + "project": "octopus", + "location": "oyster", + "data_store": "nudibranch", + } + path = SchemaServiceClient.data_store_path(**expected) + + # Check that the path construction is reversible. + actual = SchemaServiceClient.parse_data_store_path(path) + assert expected == actual + +def test_schema_path(): + project = "cuttlefish" + location = "mussel" + data_store = "winkle" + schema = "nautilus" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/schemas/{schema}".format(project=project, location=location, data_store=data_store, schema=schema, ) + actual = SchemaServiceClient.schema_path(project, location, data_store, schema) + assert expected == actual + + +def test_parse_schema_path(): + expected = { + "project": "scallop", + "location": "abalone", + "data_store": "squid", + "schema": "clam", + } + path = SchemaServiceClient.schema_path(**expected) + + # Check that the path construction is reversible. + actual = SchemaServiceClient.parse_schema_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = SchemaServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = SchemaServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SchemaServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = SchemaServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = SchemaServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SchemaServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SchemaServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = SchemaServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SchemaServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = SchemaServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = SchemaServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SchemaServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = SchemaServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = SchemaServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SchemaServiceClient.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.SchemaServiceTransport, '_prep_wrapped_messages') as prep: + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.SchemaServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = SchemaServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/operations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = SchemaServiceClient( + 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(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_get_operation(transport: str = "grpc"): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc"): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SchemaServiceClient( + 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 = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc"): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SchemaServiceClient( + 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 = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = SchemaServiceClient( + 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", [ + (SchemaServiceClient, transports.SchemaServiceGrpcTransport), + (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_search_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_search_service.py new file mode 100644 index 000000000000..27c324f3c01e --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_search_service.py @@ -0,0 +1,2233 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.discoveryengine_v1.services.search_service import SearchServiceAsyncClient +from google.cloud.discoveryengine_v1.services.search_service import SearchServiceClient +from google.cloud.discoveryengine_v1.services.search_service import pagers +from google.cloud.discoveryengine_v1.services.search_service import transports +from google.cloud.discoveryengine_v1.types import common +from google.cloud.discoveryengine_v1.types import search_service +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import struct_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert SearchServiceClient._get_default_mtls_endpoint(None) is None + assert SearchServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (SearchServiceClient, "grpc"), + (SearchServiceAsyncClient, "grpc_asyncio"), + (SearchServiceClient, "rest"), +]) +def test_search_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.SearchServiceGrpcTransport, "grpc"), + (transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.SearchServiceRestTransport, "rest"), +]) +def test_search_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", [ + (SearchServiceClient, "grpc"), + (SearchServiceAsyncClient, "grpc_asyncio"), + (SearchServiceClient, "rest"), +]) +def test_search_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +def test_search_service_client_get_transport_class(): + transport = SearchServiceClient.get_transport_class() + available_transports = [ + transports.SearchServiceGrpcTransport, + transports.SearchServiceRestTransport, + ] + assert transport in available_transports + + transport = SearchServiceClient.get_transport_class("grpc") + assert transport == transports.SearchServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (SearchServiceClient, transports.SearchServiceRestTransport, "rest"), +]) +@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) +@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) +def test_search_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(SearchServiceClient, '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(SearchServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "true"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "false"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (SearchServiceClient, transports.SearchServiceRestTransport, "rest", "true"), + (SearchServiceClient, transports.SearchServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) +@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_search_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 + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + SearchServiceClient, SearchServiceAsyncClient +]) +@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) +@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) +def test_search_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (SearchServiceClient, transports.SearchServiceRestTransport, "rest"), +]) +def test_search_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, + 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", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (SearchServiceClient, transports.SearchServiceRestTransport, "rest", None), +]) +def test_search_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, + scopes=None, + client_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_search_service_client_client_options_from_dict(): + with mock.patch('google.cloud.discoveryengine_v1.services.search_service.transports.SearchServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = SearchServiceClient( + 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", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_search_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, + scopes=None, + client_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + search_service.SearchRequest, + dict, +]) +def test_search(request_type, transport: str = 'grpc'): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = search_service.SearchResponse( + total_size=1086, + attribution_token='attribution_token_value', + redirect_uri='redirect_uri_value', + next_page_token='next_page_token_value', + corrected_query='corrected_query_value', + ) + response = client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == search_service.SearchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchPager) + assert response.total_size == 1086 + assert response.attribution_token == 'attribution_token_value' + assert response.redirect_uri == 'redirect_uri_value' + assert response.next_page_token == 'next_page_token_value' + assert response.corrected_query == 'corrected_query_value' + + +def test_search_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + client.search() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == search_service.SearchRequest() + +@pytest.mark.asyncio +async def test_search_async(transport: str = 'grpc_asyncio', request_type=search_service.SearchRequest): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse( + total_size=1086, + attribution_token='attribution_token_value', + redirect_uri='redirect_uri_value', + next_page_token='next_page_token_value', + corrected_query='corrected_query_value', + )) + response = await client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == search_service.SearchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAsyncPager) + assert response.total_size == 1086 + assert response.attribution_token == 'attribution_token_value' + assert response.redirect_uri == 'redirect_uri_value' + assert response.next_page_token == 'next_page_token_value' + assert response.corrected_query == 'corrected_query_value' + + +@pytest.mark.asyncio +async def test_search_async_from_dict(): + await test_search_async(request_type=dict) + + +def test_search_field_headers(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = search_service.SearchRequest() + + request.serving_config = 'serving_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + call.return_value = search_service.SearchResponse() + client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config=serving_config_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_search_field_headers_async(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = search_service.SearchRequest() + + request.serving_config = 'serving_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse()) + await client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config=serving_config_value', + ) in kw['metadata'] + + +def test_search_pager(transport_name: str = "grpc"): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('serving_config', ''), + )), + ) + pager = client.search(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, search_service.SearchResponse.SearchResult) + for i in results) +def test_search_pages(transport_name: str = "grpc"): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + pages = list(client.search(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_search_async_pager(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.search(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, search_service.SearchResponse.SearchResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_search_async_pages(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.search(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", [ + search_service.SearchRequest, + dict, +]) +def test_search_rest(request_type): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'serving_config': 'projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/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 = search_service.SearchResponse( + total_size=1086, + attribution_token='attribution_token_value', + redirect_uri='redirect_uri_value', + next_page_token='next_page_token_value', + corrected_query='corrected_query_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 = search_service.SearchResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.search(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchPager) + assert response.total_size == 1086 + assert response.attribution_token == 'attribution_token_value' + assert response.redirect_uri == 'redirect_uri_value' + assert response.next_page_token == 'next_page_token_value' + assert response.corrected_query == 'corrected_query_value' + + +def test_search_rest_required_fields(request_type=search_service.SearchRequest): + transport_class = transports.SearchServiceRestTransport + + request_init = {} + request_init["serving_config"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["servingConfig"] = 'serving_config_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "servingConfig" in jsonified_request + assert jsonified_request["servingConfig"] == 'serving_config_value' + + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = search_service.SearchResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = search_service.SearchResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.search(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_search_rest_unset_required_fields(): + transport = transports.SearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.search._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("servingConfig", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_rest_interceptors(null_interceptor): + transport = transports.SearchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SearchServiceRestInterceptor(), + ) + client = SearchServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SearchServiceRestInterceptor, "post_search") as post, \ + mock.patch.object(transports.SearchServiceRestInterceptor, "pre_search") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = search_service.SearchRequest.pb(search_service.SearchRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = search_service.SearchResponse.to_json(search_service.SearchResponse()) + + request = search_service.SearchRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = search_service.SearchResponse() + + client.search(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_search_rest_bad_request(transport: str = 'rest', request_type=search_service.SearchRequest): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'serving_config': 'projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.search(request) + + +def test_search_rest_pager(transport: str = 'rest'): + client = SearchServiceClient( + 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 = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(search_service.SearchResponse.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 = {'serving_config': 'projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/sample4'} + + pager = client.search(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, search_service.SearchResponse.SearchResult) + for i in results) + + pages = list(client.search(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.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SearchServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SearchServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.SearchServiceGrpcTransport, + transports.SearchServiceGrpcAsyncIOTransport, + transports.SearchServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = SearchServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SearchServiceGrpcTransport, + ) + +def test_search_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SearchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_search_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.discoveryengine_v1.services.search_service.transports.SearchServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.SearchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'search', + 'get_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_search_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.discoveryengine_v1.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SearchServiceTransport( + 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_search_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.discoveryengine_v1.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SearchServiceTransport() + adc.assert_called_once() + + +def test_search_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) + SearchServiceClient() + 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.SearchServiceGrpcTransport, + transports.SearchServiceGrpcAsyncIOTransport, + ], +) +def test_search_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.SearchServiceGrpcTransport, + transports.SearchServiceGrpcAsyncIOTransport, + transports.SearchServiceRestTransport, + ], +) +def test_search_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.SearchServiceGrpcTransport, grpc_helpers), + (transports.SearchServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_search_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) +def test_search_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_search_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.SearchServiceRestTransport ( + 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_search_service_host_no_port(transport_name): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_search_service_host_with_port(transport_name): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_search_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = SearchServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = SearchServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.search._session + session2 = client2.transport.search._session + assert session1 != session2 +def test_search_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SearchServiceGrpcTransport( + 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_search_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SearchServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) +def test_search_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.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) +def test_search_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_branch_path(): + project = "squid" + location = "clam" + data_store = "whelk" + branch = "octopus" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}".format(project=project, location=location, data_store=data_store, branch=branch, ) + actual = SearchServiceClient.branch_path(project, location, data_store, branch) + assert expected == actual + + +def test_parse_branch_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "data_store": "cuttlefish", + "branch": "mussel", + } + path = SearchServiceClient.branch_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_branch_path(path) + assert expected == actual + +def test_document_path(): + project = "winkle" + location = "nautilus" + data_store = "scallop" + branch = "abalone" + document = "squid" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) + actual = SearchServiceClient.document_path(project, location, data_store, branch, document) + assert expected == actual + + +def test_parse_document_path(): + expected = { + "project": "clam", + "location": "whelk", + "data_store": "octopus", + "branch": "oyster", + "document": "nudibranch", + } + path = SearchServiceClient.document_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_document_path(path) + assert expected == actual + +def test_serving_config_path(): + project = "cuttlefish" + location = "mussel" + data_store = "winkle" + serving_config = "nautilus" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/servingConfigs/{serving_config}".format(project=project, location=location, data_store=data_store, serving_config=serving_config, ) + actual = SearchServiceClient.serving_config_path(project, location, data_store, serving_config) + assert expected == actual + + +def test_parse_serving_config_path(): + expected = { + "project": "scallop", + "location": "abalone", + "data_store": "squid", + "serving_config": "clam", + } + path = SearchServiceClient.serving_config_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_serving_config_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = SearchServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = SearchServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = SearchServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = SearchServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SearchServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = SearchServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = SearchServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = SearchServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = SearchServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = SearchServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.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.SearchServiceTransport, '_prep_wrapped_messages') as prep: + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = SearchServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/operations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = SearchServiceClient( + 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(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_get_operation(transport: str = "grpc"): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc"): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SearchServiceClient( + 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 = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc"): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SearchServiceClient( + 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 = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = SearchServiceClient( + 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", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_user_event_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_user_event_service.py new file mode 100644 index 000000000000..7ff0ea1d704a --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_user_event_service.py @@ -0,0 +1,2786 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.discoveryengine_v1.services.user_event_service import UserEventServiceAsyncClient +from google.cloud.discoveryengine_v1.services.user_event_service import UserEventServiceClient +from google.cloud.discoveryengine_v1.services.user_event_service import transports +from google.cloud.discoveryengine_v1.types import common +from google.cloud.discoveryengine_v1.types import import_config +from google.cloud.discoveryengine_v1.types import user_event +from google.cloud.discoveryengine_v1.types import user_event_service +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert UserEventServiceClient._get_default_mtls_endpoint(None) is None + assert UserEventServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (UserEventServiceClient, "grpc"), + (UserEventServiceAsyncClient, "grpc_asyncio"), + (UserEventServiceClient, "rest"), +]) +def test_user_event_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.UserEventServiceGrpcTransport, "grpc"), + (transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.UserEventServiceRestTransport, "rest"), +]) +def test_user_event_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", [ + (UserEventServiceClient, "grpc"), + (UserEventServiceAsyncClient, "grpc_asyncio"), + (UserEventServiceClient, "rest"), +]) +def test_user_event_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +def test_user_event_service_client_get_transport_class(): + transport = UserEventServiceClient.get_transport_class() + available_transports = [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceRestTransport, + ] + assert transport in available_transports + + transport = UserEventServiceClient.get_transport_class("grpc") + assert transport == transports.UserEventServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (UserEventServiceClient, transports.UserEventServiceRestTransport, "rest"), +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +def test_user_event_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(UserEventServiceClient, '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(UserEventServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "true"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "false"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (UserEventServiceClient, transports.UserEventServiceRestTransport, "rest", "true"), + (UserEventServiceClient, transports.UserEventServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_user_event_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 + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + UserEventServiceClient, UserEventServiceAsyncClient +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +def test_user_event_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (UserEventServiceClient, transports.UserEventServiceRestTransport, "rest"), +]) +def test_user_event_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, + 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", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (UserEventServiceClient, transports.UserEventServiceRestTransport, "rest", None), +]) +def test_user_event_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, + scopes=None, + client_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_user_event_service_client_client_options_from_dict(): + with mock.patch('google.cloud.discoveryengine_v1.services.user_event_service.transports.UserEventServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = UserEventServiceClient( + 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", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_user_event_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, + scopes=None, + client_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + user_event_service.WriteUserEventRequest, + dict, +]) +def test_write_user_event(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = user_event.UserEvent( + event_type='event_type_value', + user_pseudo_id='user_pseudo_id_value', + direct_user_request=True, + session_id='session_id_value', + attribution_token='attribution_token_value', + filter='filter_value', + tag_ids=['tag_ids_value'], + promotion_ids=['promotion_ids_value'], + ) + response = client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, user_event.UserEvent) + assert response.event_type == 'event_type_value' + assert response.user_pseudo_id == 'user_pseudo_id_value' + assert response.direct_user_request is True + assert response.session_id == 'session_id_value' + assert response.attribution_token == 'attribution_token_value' + assert response.filter == 'filter_value' + assert response.tag_ids == ['tag_ids_value'] + assert response.promotion_ids == ['promotion_ids_value'] + + +def test_write_user_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + client.write_user_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + +@pytest.mark.asyncio +async def test_write_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.WriteUserEventRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent( + event_type='event_type_value', + user_pseudo_id='user_pseudo_id_value', + direct_user_request=True, + session_id='session_id_value', + attribution_token='attribution_token_value', + filter='filter_value', + tag_ids=['tag_ids_value'], + promotion_ids=['promotion_ids_value'], + )) + response = await client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, user_event.UserEvent) + assert response.event_type == 'event_type_value' + assert response.user_pseudo_id == 'user_pseudo_id_value' + assert response.direct_user_request is True + assert response.session_id == 'session_id_value' + assert response.attribution_token == 'attribution_token_value' + assert response.filter == 'filter_value' + assert response.tag_ids == ['tag_ids_value'] + assert response.promotion_ids == ['promotion_ids_value'] + + +@pytest.mark.asyncio +async def test_write_user_event_async_from_dict(): + await test_write_user_event_async(request_type=dict) + + +def test_write_user_event_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.WriteUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + call.return_value = user_event.UserEvent() + client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_write_user_event_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.WriteUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent()) + await client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + user_event_service.CollectUserEventRequest, + dict, +]) +def test_collect_user_event(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + ) + response = client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +def test_collect_user_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + client.collect_user_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + +@pytest.mark.asyncio +async def test_collect_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.CollectUserEventRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + )) + response = await client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +@pytest.mark.asyncio +async def test_collect_user_event_async_from_dict(): + await test_collect_user_event_async(request_type=dict) + + +def test_collect_user_event_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.CollectUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + call.return_value = httpbody_pb2.HttpBody() + client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_collect_user_event_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.CollectUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody()) + await client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportUserEventsRequest, + dict, +]) +def test_import_user_events(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_user_events_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + client.import_user_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportUserEventsRequest() + +@pytest.mark.asyncio +async def test_import_user_events_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportUserEventsRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__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_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_user_events_async_from_dict(): + await test_import_user_events_async(request_type=dict) + + +def test_import_user_events_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_import_user_events_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + user_event_service.WriteUserEventRequest, + dict, +]) +def test_write_user_event_rest(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + request_init["user_event"] = {'event_type': 'event_type_value', 'user_pseudo_id': 'user_pseudo_id_value', 'event_time': {'seconds': 751, 'nanos': 543}, 'user_info': {'user_id': 'user_id_value', 'user_agent': 'user_agent_value'}, 'direct_user_request': True, 'session_id': 'session_id_value', 'page_info': {'pageview_id': 'pageview_id_value', 'page_category': 'page_category_value', 'uri': 'uri_value', 'referrer_uri': 'referrer_uri_value'}, 'attribution_token': 'attribution_token_value', 'filter': 'filter_value', 'documents': [{'id': 'id_value', 'name': 'name_value', 'uri': 'uri_value', 'quantity': 895, 'promotion_ids': ['promotion_ids_value1', 'promotion_ids_value2']}], 'panel': {'panel_id': 'panel_id_value', 'display_name': 'display_name_value', 'panel_position': 1508, 'total_panels': 1286}, 'search_info': {'search_query': 'search_query_value', 'order_by': 'order_by_value', 'offset': 647}, 'completion_info': {'selected_suggestion': 'selected_suggestion_value', 'selected_position': 1821}, 'transaction_info': {'value': 0.541, 'currency': 'currency_value', 'transaction_id': 'transaction_id_value', 'tax': 0.333, 'cost': 0.441, 'discount_value': 0.1509}, 'tag_ids': ['tag_ids_value1', 'tag_ids_value2'], 'promotion_ids': ['promotion_ids_value1', 'promotion_ids_value2'], 'attributes': {}, 'media_info': {'media_progress_duration': {'seconds': 751, 'nanos': 543}, 'media_progress_percentage': 0.2641}} + # 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 = user_event_service.WriteUserEventRequest.meta.fields["user_event"] + + 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_event"].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_event"][field])): + del request_init["user_event"][field][i][subfield] + else: + del request_init["user_event"][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 = user_event.UserEvent( + event_type='event_type_value', + user_pseudo_id='user_pseudo_id_value', + direct_user_request=True, + session_id='session_id_value', + attribution_token='attribution_token_value', + filter='filter_value', + tag_ids=['tag_ids_value'], + promotion_ids=['promotion_ids_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 = user_event.UserEvent.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.write_user_event(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, user_event.UserEvent) + assert response.event_type == 'event_type_value' + assert response.user_pseudo_id == 'user_pseudo_id_value' + assert response.direct_user_request is True + assert response.session_id == 'session_id_value' + assert response.attribution_token == 'attribution_token_value' + assert response.filter == 'filter_value' + assert response.tag_ids == ['tag_ids_value'] + assert response.promotion_ids == ['promotion_ids_value'] + + +def test_write_user_event_rest_required_fields(request_type=user_event_service.WriteUserEventRequest): + transport_class = transports.UserEventServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).write_user_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).write_user_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = user_event.UserEvent() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = user_event.UserEvent.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.write_user_event(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_write_user_event_rest_unset_required_fields(): + transport = transports.UserEventServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.write_user_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "userEvent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_write_user_event_rest_interceptors(null_interceptor): + transport = transports.UserEventServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.UserEventServiceRestInterceptor(), + ) + client = UserEventServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.UserEventServiceRestInterceptor, "post_write_user_event") as post, \ + mock.patch.object(transports.UserEventServiceRestInterceptor, "pre_write_user_event") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = user_event_service.WriteUserEventRequest.pb(user_event_service.WriteUserEventRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = user_event.UserEvent.to_json(user_event.UserEvent()) + + request = user_event_service.WriteUserEventRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = user_event.UserEvent() + + client.write_user_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_write_user_event_rest_bad_request(transport: str = 'rest', request_type=user_event_service.WriteUserEventRequest): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.write_user_event(request) + + +def test_write_user_event_rest_error(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + user_event_service.CollectUserEventRequest, + dict, +]) +def test_collect_user_event_rest(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/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 = httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.collect_user_event(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +def test_collect_user_event_rest_required_fields(request_type=user_event_service.CollectUserEventRequest): + transport_class = transports.UserEventServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["user_event"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "userEvent" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).collect_user_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "userEvent" in jsonified_request + assert jsonified_request["userEvent"] == request_init["user_event"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["userEvent"] = 'user_event_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).collect_user_event._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("ets", "uri", "user_event", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "userEvent" in jsonified_request + assert jsonified_request["userEvent"] == 'user_event_value' + + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = httpbody_pb2.HttpBody() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 + + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.collect_user_event(request) + + expected_params = [ + ( + "userEvent", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_collect_user_event_rest_unset_required_fields(): + transport = transports.UserEventServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.collect_user_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(("ets", "uri", "userEvent", )) & set(("parent", "userEvent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_collect_user_event_rest_interceptors(null_interceptor): + transport = transports.UserEventServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.UserEventServiceRestInterceptor(), + ) + client = UserEventServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.UserEventServiceRestInterceptor, "post_collect_user_event") as post, \ + mock.patch.object(transports.UserEventServiceRestInterceptor, "pre_collect_user_event") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = user_event_service.CollectUserEventRequest.pb(user_event_service.CollectUserEventRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(httpbody_pb2.HttpBody()) + + request = user_event_service.CollectUserEventRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = httpbody_pb2.HttpBody() + + client.collect_user_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_collect_user_event_rest_bad_request(transport: str = 'rest', request_type=user_event_service.CollectUserEventRequest): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.collect_user_event(request) + + +def test_collect_user_event_rest_error(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportUserEventsRequest, + dict, +]) +def test_import_user_events_rest(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.import_user_events(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_import_user_events_rest_required_fields(request_type=import_config.ImportUserEventsRequest): + transport_class = transports.UserEventServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_user_events._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_user_events._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.import_user_events(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_import_user_events_rest_unset_required_fields(): + transport = transports.UserEventServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.import_user_events._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_import_user_events_rest_interceptors(null_interceptor): + transport = transports.UserEventServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.UserEventServiceRestInterceptor(), + ) + client = UserEventServiceClient(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.UserEventServiceRestInterceptor, "post_import_user_events") as post, \ + mock.patch.object(transports.UserEventServiceRestInterceptor, "pre_import_user_events") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = import_config.ImportUserEventsRequest.pb(import_config.ImportUserEventsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = import_config.ImportUserEventsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.import_user_events(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_import_user_events_rest_bad_request(transport: str = 'rest', request_type=import_config.ImportUserEventsRequest): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.import_user_events(request) + + +def test_import_user_events_rest_error(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = UserEventServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.UserEventServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, + transports.UserEventServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = UserEventServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.UserEventServiceGrpcTransport, + ) + +def test_user_event_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.UserEventServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_user_event_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.discoveryengine_v1.services.user_event_service.transports.UserEventServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.UserEventServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'write_user_event', + 'collect_user_event', + 'import_user_events', + 'get_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_user_event_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.discoveryengine_v1.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.UserEventServiceTransport( + 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_user_event_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.discoveryengine_v1.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.UserEventServiceTransport() + adc.assert_called_once() + + +def test_user_event_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) + UserEventServiceClient() + 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.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, + ], +) +def test_user_event_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.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, + transports.UserEventServiceRestTransport, + ], +) +def test_user_event_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.UserEventServiceGrpcTransport, grpc_helpers), + (transports.UserEventServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_user_event_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_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_user_event_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.UserEventServiceRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_user_event_service_rest_lro_client(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_user_event_service_host_no_port(transport_name): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_user_event_service_host_with_port(transport_name): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_user_event_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = UserEventServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = UserEventServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.write_user_event._session + session2 = client2.transport.write_user_event._session + assert session1 != session2 + session1 = client1.transport.collect_user_event._session + session2 = client2.transport.collect_user_event._session + assert session1 != session2 + session1 = client1.transport.import_user_events._session + session2 = client2.transport.import_user_events._session + assert session1 != session2 +def test_user_event_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.UserEventServiceGrpcTransport( + 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_user_event_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.UserEventServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_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.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_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_user_event_service_grpc_lro_client(): + client = UserEventServiceClient( + 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_user_event_service_grpc_lro_async_client(): + client = UserEventServiceAsyncClient( + 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_data_store_path(): + project = "squid" + location = "clam" + data_store = "whelk" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) + actual = UserEventServiceClient.data_store_path(project, location, data_store) + assert expected == actual + + +def test_parse_data_store_path(): + expected = { + "project": "octopus", + "location": "oyster", + "data_store": "nudibranch", + } + path = UserEventServiceClient.data_store_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_data_store_path(path) + assert expected == actual + +def test_document_path(): + project = "cuttlefish" + location = "mussel" + data_store = "winkle" + branch = "nautilus" + document = "scallop" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) + actual = UserEventServiceClient.document_path(project, location, data_store, branch, document) + assert expected == actual + + +def test_parse_document_path(): + expected = { + "project": "abalone", + "location": "squid", + "data_store": "clam", + "branch": "whelk", + "document": "octopus", + } + path = UserEventServiceClient.document_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_document_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = UserEventServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = UserEventServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = UserEventServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = UserEventServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = UserEventServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = UserEventServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = UserEventServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = UserEventServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = UserEventServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = UserEventServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.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.UserEventServiceTransport, '_prep_wrapped_messages') as prep: + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = UserEventServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/operations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = UserEventServiceClient( + 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(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_get_operation(transport: str = "grpc"): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc"): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = UserEventServiceClient( + 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 = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc"): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = UserEventServiceClient( + 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 = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = UserEventServiceClient( + 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", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/.coveragerc b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/.coveragerc new file mode 100644 index 000000000000..f2c9bc595be9 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/discoveryengine/__init__.py + google/cloud/discoveryengine/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/.flake8 b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/MANIFEST.in b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/MANIFEST.in new file mode 100644 index 000000000000..f798e554c570 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/discoveryengine *.py +recursive-include google/cloud/discoveryengine_v1alpha *.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/README.rst b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/README.rst new file mode 100644 index 000000000000..25f579284266 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Discoveryengine API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Cloud Discoveryengine API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/_static/custom.css b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/conf.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/conf.py new file mode 100644 index 000000000000..9852ef988546 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-discoveryengine documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-cloud-discoveryengine" +copyright = u"2023, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = 'en' + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-discoveryengine-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-cloud-discoveryengine.tex", + u"google-cloud-discoveryengine Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + root_doc, + "google-cloud-discoveryengine", + u"Google Cloud Discoveryengine Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-cloud-discoveryengine", + u"google-cloud-discoveryengine Documentation", + author, + "google-cloud-discoveryengine", + "GAPIC library for Google Cloud Discoveryengine API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/completion_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/completion_service.rst new file mode 100644 index 000000000000..8f4c72412f68 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/completion_service.rst @@ -0,0 +1,6 @@ +CompletionService +----------------------------------- + +.. automodule:: google.cloud.discoveryengine_v1alpha.services.completion_service + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/conversational_search_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/conversational_search_service.rst new file mode 100644 index 000000000000..50123289725d --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/conversational_search_service.rst @@ -0,0 +1,10 @@ +ConversationalSearchService +--------------------------------------------- + +.. automodule:: google.cloud.discoveryengine_v1alpha.services.conversational_search_service + :members: + :inherited-members: + +.. automodule:: google.cloud.discoveryengine_v1alpha.services.conversational_search_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/data_store_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/data_store_service.rst new file mode 100644 index 000000000000..c1dd5b746d82 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/data_store_service.rst @@ -0,0 +1,10 @@ +DataStoreService +---------------------------------- + +.. automodule:: google.cloud.discoveryengine_v1alpha.services.data_store_service + :members: + :inherited-members: + +.. automodule:: google.cloud.discoveryengine_v1alpha.services.data_store_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/document_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/document_service.rst new file mode 100644 index 000000000000..295c3e8a2875 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/document_service.rst @@ -0,0 +1,10 @@ +DocumentService +--------------------------------- + +.. automodule:: google.cloud.discoveryengine_v1alpha.services.document_service + :members: + :inherited-members: + +.. automodule:: google.cloud.discoveryengine_v1alpha.services.document_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/engine_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/engine_service.rst new file mode 100644 index 000000000000..9830662477b5 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/engine_service.rst @@ -0,0 +1,10 @@ +EngineService +------------------------------- + +.. automodule:: google.cloud.discoveryengine_v1alpha.services.engine_service + :members: + :inherited-members: + +.. automodule:: google.cloud.discoveryengine_v1alpha.services.engine_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/recommendation_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/recommendation_service.rst new file mode 100644 index 000000000000..440ff0398fd3 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/recommendation_service.rst @@ -0,0 +1,6 @@ +RecommendationService +--------------------------------------- + +.. automodule:: google.cloud.discoveryengine_v1alpha.services.recommendation_service + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/schema_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/schema_service.rst new file mode 100644 index 000000000000..73d40c3718e6 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/schema_service.rst @@ -0,0 +1,10 @@ +SchemaService +------------------------------- + +.. automodule:: google.cloud.discoveryengine_v1alpha.services.schema_service + :members: + :inherited-members: + +.. automodule:: google.cloud.discoveryengine_v1alpha.services.schema_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/search_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/search_service.rst new file mode 100644 index 000000000000..fa744f4a4ae9 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/search_service.rst @@ -0,0 +1,10 @@ +SearchService +------------------------------- + +.. automodule:: google.cloud.discoveryengine_v1alpha.services.search_service + :members: + :inherited-members: + +.. automodule:: google.cloud.discoveryengine_v1alpha.services.search_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/services_.rst b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/services_.rst new file mode 100644 index 000000000000..0177e984c5cc --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/services_.rst @@ -0,0 +1,15 @@ +Services for Google Cloud Discoveryengine v1alpha API +===================================================== +.. toctree:: + :maxdepth: 2 + + completion_service + conversational_search_service + data_store_service + document_service + engine_service + recommendation_service + schema_service + search_service + site_search_engine_service + user_event_service diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/site_search_engine_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/site_search_engine_service.rst new file mode 100644 index 000000000000..438309914a4a --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/site_search_engine_service.rst @@ -0,0 +1,6 @@ +SiteSearchEngineService +----------------------------------------- + +.. automodule:: google.cloud.discoveryengine_v1alpha.services.site_search_engine_service + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/types_.rst b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/types_.rst new file mode 100644 index 000000000000..8d74074a2c19 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Discoveryengine v1alpha API +================================================== + +.. automodule:: google.cloud.discoveryengine_v1alpha.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/user_event_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/user_event_service.rst new file mode 100644 index 000000000000..3b383e9c7d16 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/user_event_service.rst @@ -0,0 +1,6 @@ +UserEventService +---------------------------------- + +.. automodule:: google.cloud.discoveryengine_v1alpha.services.user_event_service + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/index.rst b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/index.rst new file mode 100644 index 000000000000..d45fecf9bdd5 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + discoveryengine_v1alpha/services + discoveryengine_v1alpha/types diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine/__init__.py new file mode 100644 index 000000000000..c5d2e50633bd --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine/__init__.py @@ -0,0 +1,255 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.discoveryengine import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.discoveryengine_v1alpha.services.completion_service.client import CompletionServiceClient +from google.cloud.discoveryengine_v1alpha.services.completion_service.async_client import CompletionServiceAsyncClient +from google.cloud.discoveryengine_v1alpha.services.conversational_search_service.client import ConversationalSearchServiceClient +from google.cloud.discoveryengine_v1alpha.services.conversational_search_service.async_client import ConversationalSearchServiceAsyncClient +from google.cloud.discoveryengine_v1alpha.services.data_store_service.client import DataStoreServiceClient +from google.cloud.discoveryengine_v1alpha.services.data_store_service.async_client import DataStoreServiceAsyncClient +from google.cloud.discoveryengine_v1alpha.services.document_service.client import DocumentServiceClient +from google.cloud.discoveryengine_v1alpha.services.document_service.async_client import DocumentServiceAsyncClient +from google.cloud.discoveryengine_v1alpha.services.engine_service.client import EngineServiceClient +from google.cloud.discoveryengine_v1alpha.services.engine_service.async_client import EngineServiceAsyncClient +from google.cloud.discoveryengine_v1alpha.services.recommendation_service.client import RecommendationServiceClient +from google.cloud.discoveryengine_v1alpha.services.recommendation_service.async_client import RecommendationServiceAsyncClient +from google.cloud.discoveryengine_v1alpha.services.schema_service.client import SchemaServiceClient +from google.cloud.discoveryengine_v1alpha.services.schema_service.async_client import SchemaServiceAsyncClient +from google.cloud.discoveryengine_v1alpha.services.search_service.client import SearchServiceClient +from google.cloud.discoveryengine_v1alpha.services.search_service.async_client import SearchServiceAsyncClient +from google.cloud.discoveryengine_v1alpha.services.site_search_engine_service.client import SiteSearchEngineServiceClient +from google.cloud.discoveryengine_v1alpha.services.site_search_engine_service.async_client import SiteSearchEngineServiceAsyncClient +from google.cloud.discoveryengine_v1alpha.services.user_event_service.client import UserEventServiceClient +from google.cloud.discoveryengine_v1alpha.services.user_event_service.async_client import UserEventServiceAsyncClient + +from google.cloud.discoveryengine_v1alpha.types.common import CustomAttribute +from google.cloud.discoveryengine_v1alpha.types.common import DoubleList +from google.cloud.discoveryengine_v1alpha.types.common import Interval +from google.cloud.discoveryengine_v1alpha.types.common import UserInfo +from google.cloud.discoveryengine_v1alpha.types.common import IndustryVertical +from google.cloud.discoveryengine_v1alpha.types.common import SearchAddOn +from google.cloud.discoveryengine_v1alpha.types.common import SearchTier +from google.cloud.discoveryengine_v1alpha.types.common import SolutionType +from google.cloud.discoveryengine_v1alpha.types.completion_service import CompleteQueryRequest +from google.cloud.discoveryengine_v1alpha.types.completion_service import CompleteQueryResponse +from google.cloud.discoveryengine_v1alpha.types.conversation import Conversation +from google.cloud.discoveryengine_v1alpha.types.conversation import ConversationContext +from google.cloud.discoveryengine_v1alpha.types.conversation import ConversationMessage +from google.cloud.discoveryengine_v1alpha.types.conversation import Reply +from google.cloud.discoveryengine_v1alpha.types.conversation import TextInput +from google.cloud.discoveryengine_v1alpha.types.conversational_search_service import ConverseConversationRequest +from google.cloud.discoveryengine_v1alpha.types.conversational_search_service import ConverseConversationResponse +from google.cloud.discoveryengine_v1alpha.types.conversational_search_service import CreateConversationRequest +from google.cloud.discoveryengine_v1alpha.types.conversational_search_service import DeleteConversationRequest +from google.cloud.discoveryengine_v1alpha.types.conversational_search_service import GetConversationRequest +from google.cloud.discoveryengine_v1alpha.types.conversational_search_service import ListConversationsRequest +from google.cloud.discoveryengine_v1alpha.types.conversational_search_service import ListConversationsResponse +from google.cloud.discoveryengine_v1alpha.types.conversational_search_service import UpdateConversationRequest +from google.cloud.discoveryengine_v1alpha.types.data_store import DataStore +from google.cloud.discoveryengine_v1alpha.types.data_store_service import CreateDataStoreMetadata +from google.cloud.discoveryengine_v1alpha.types.data_store_service import CreateDataStoreRequest +from google.cloud.discoveryengine_v1alpha.types.data_store_service import DeleteDataStoreMetadata +from google.cloud.discoveryengine_v1alpha.types.data_store_service import DeleteDataStoreRequest +from google.cloud.discoveryengine_v1alpha.types.data_store_service import GetDataStoreRequest +from google.cloud.discoveryengine_v1alpha.types.data_store_service import ListDataStoresRequest +from google.cloud.discoveryengine_v1alpha.types.data_store_service import ListDataStoresResponse +from google.cloud.discoveryengine_v1alpha.types.data_store_service import UpdateDataStoreRequest +from google.cloud.discoveryengine_v1alpha.types.document import Document +from google.cloud.discoveryengine_v1alpha.types.document_service import CreateDocumentRequest +from google.cloud.discoveryengine_v1alpha.types.document_service import DeleteDocumentRequest +from google.cloud.discoveryengine_v1alpha.types.document_service import GetDocumentRequest +from google.cloud.discoveryengine_v1alpha.types.document_service import ListDocumentsRequest +from google.cloud.discoveryengine_v1alpha.types.document_service import ListDocumentsResponse +from google.cloud.discoveryengine_v1alpha.types.document_service import UpdateDocumentRequest +from google.cloud.discoveryengine_v1alpha.types.engine import Engine +from google.cloud.discoveryengine_v1alpha.types.engine_service import CreateEngineMetadata +from google.cloud.discoveryengine_v1alpha.types.engine_service import CreateEngineRequest +from google.cloud.discoveryengine_v1alpha.types.engine_service import DeleteEngineMetadata +from google.cloud.discoveryengine_v1alpha.types.engine_service import DeleteEngineRequest +from google.cloud.discoveryengine_v1alpha.types.engine_service import GetEngineRequest +from google.cloud.discoveryengine_v1alpha.types.engine_service import ListEnginesRequest +from google.cloud.discoveryengine_v1alpha.types.engine_service import ListEnginesResponse +from google.cloud.discoveryengine_v1alpha.types.engine_service import PauseEngineRequest +from google.cloud.discoveryengine_v1alpha.types.engine_service import ResumeEngineRequest +from google.cloud.discoveryengine_v1alpha.types.engine_service import TuneEngineMetadata +from google.cloud.discoveryengine_v1alpha.types.engine_service import TuneEngineRequest +from google.cloud.discoveryengine_v1alpha.types.engine_service import TuneEngineResponse +from google.cloud.discoveryengine_v1alpha.types.engine_service import UpdateEngineRequest +from google.cloud.discoveryengine_v1alpha.types.import_config import BigQuerySource +from google.cloud.discoveryengine_v1alpha.types.import_config import GcsSource +from google.cloud.discoveryengine_v1alpha.types.import_config import ImportDocumentsMetadata +from google.cloud.discoveryengine_v1alpha.types.import_config import ImportDocumentsRequest +from google.cloud.discoveryengine_v1alpha.types.import_config import ImportDocumentsResponse +from google.cloud.discoveryengine_v1alpha.types.import_config import ImportErrorConfig +from google.cloud.discoveryengine_v1alpha.types.import_config import ImportUserEventsMetadata +from google.cloud.discoveryengine_v1alpha.types.import_config import ImportUserEventsRequest +from google.cloud.discoveryengine_v1alpha.types.import_config import ImportUserEventsResponse +from google.cloud.discoveryengine_v1alpha.types.purge_config import PurgeDocumentsMetadata +from google.cloud.discoveryengine_v1alpha.types.purge_config import PurgeDocumentsRequest +from google.cloud.discoveryengine_v1alpha.types.purge_config import PurgeDocumentsResponse +from google.cloud.discoveryengine_v1alpha.types.purge_config import PurgeUserEventsMetadata +from google.cloud.discoveryengine_v1alpha.types.purge_config import PurgeUserEventsRequest +from google.cloud.discoveryengine_v1alpha.types.purge_config import PurgeUserEventsResponse +from google.cloud.discoveryengine_v1alpha.types.recommendation_service import RecommendRequest +from google.cloud.discoveryengine_v1alpha.types.recommendation_service import RecommendResponse +from google.cloud.discoveryengine_v1alpha.types.schema import FieldConfig +from google.cloud.discoveryengine_v1alpha.types.schema import Schema +from google.cloud.discoveryengine_v1alpha.types.schema_service import CreateSchemaMetadata +from google.cloud.discoveryengine_v1alpha.types.schema_service import CreateSchemaRequest +from google.cloud.discoveryengine_v1alpha.types.schema_service import DeleteSchemaMetadata +from google.cloud.discoveryengine_v1alpha.types.schema_service import DeleteSchemaRequest +from google.cloud.discoveryengine_v1alpha.types.schema_service import GetSchemaRequest +from google.cloud.discoveryengine_v1alpha.types.schema_service import ListSchemasRequest +from google.cloud.discoveryengine_v1alpha.types.schema_service import ListSchemasResponse +from google.cloud.discoveryengine_v1alpha.types.schema_service import UpdateSchemaMetadata +from google.cloud.discoveryengine_v1alpha.types.schema_service import UpdateSchemaRequest +from google.cloud.discoveryengine_v1alpha.types.search_service import SearchRequest +from google.cloud.discoveryengine_v1alpha.types.search_service import SearchResponse +from google.cloud.discoveryengine_v1alpha.types.site_search_engine_service import RecrawlUrisMetadata +from google.cloud.discoveryengine_v1alpha.types.site_search_engine_service import RecrawlUrisRequest +from google.cloud.discoveryengine_v1alpha.types.site_search_engine_service import RecrawlUrisResponse +from google.cloud.discoveryengine_v1alpha.types.user_event import CompletionInfo +from google.cloud.discoveryengine_v1alpha.types.user_event import DocumentInfo +from google.cloud.discoveryengine_v1alpha.types.user_event import MediaInfo +from google.cloud.discoveryengine_v1alpha.types.user_event import PageInfo +from google.cloud.discoveryengine_v1alpha.types.user_event import PanelInfo +from google.cloud.discoveryengine_v1alpha.types.user_event import SearchInfo +from google.cloud.discoveryengine_v1alpha.types.user_event import TransactionInfo +from google.cloud.discoveryengine_v1alpha.types.user_event import UserEvent +from google.cloud.discoveryengine_v1alpha.types.user_event_service import CollectUserEventRequest +from google.cloud.discoveryengine_v1alpha.types.user_event_service import WriteUserEventRequest + +__all__ = ('CompletionServiceClient', + 'CompletionServiceAsyncClient', + 'ConversationalSearchServiceClient', + 'ConversationalSearchServiceAsyncClient', + 'DataStoreServiceClient', + 'DataStoreServiceAsyncClient', + 'DocumentServiceClient', + 'DocumentServiceAsyncClient', + 'EngineServiceClient', + 'EngineServiceAsyncClient', + 'RecommendationServiceClient', + 'RecommendationServiceAsyncClient', + 'SchemaServiceClient', + 'SchemaServiceAsyncClient', + 'SearchServiceClient', + 'SearchServiceAsyncClient', + 'SiteSearchEngineServiceClient', + 'SiteSearchEngineServiceAsyncClient', + 'UserEventServiceClient', + 'UserEventServiceAsyncClient', + 'CustomAttribute', + 'DoubleList', + 'Interval', + 'UserInfo', + 'IndustryVertical', + 'SearchAddOn', + 'SearchTier', + 'SolutionType', + 'CompleteQueryRequest', + 'CompleteQueryResponse', + 'Conversation', + 'ConversationContext', + 'ConversationMessage', + 'Reply', + 'TextInput', + 'ConverseConversationRequest', + 'ConverseConversationResponse', + 'CreateConversationRequest', + 'DeleteConversationRequest', + 'GetConversationRequest', + 'ListConversationsRequest', + 'ListConversationsResponse', + 'UpdateConversationRequest', + 'DataStore', + 'CreateDataStoreMetadata', + 'CreateDataStoreRequest', + 'DeleteDataStoreMetadata', + 'DeleteDataStoreRequest', + 'GetDataStoreRequest', + 'ListDataStoresRequest', + 'ListDataStoresResponse', + 'UpdateDataStoreRequest', + 'Document', + 'CreateDocumentRequest', + 'DeleteDocumentRequest', + 'GetDocumentRequest', + 'ListDocumentsRequest', + 'ListDocumentsResponse', + 'UpdateDocumentRequest', + 'Engine', + 'CreateEngineMetadata', + 'CreateEngineRequest', + 'DeleteEngineMetadata', + 'DeleteEngineRequest', + 'GetEngineRequest', + 'ListEnginesRequest', + 'ListEnginesResponse', + 'PauseEngineRequest', + 'ResumeEngineRequest', + 'TuneEngineMetadata', + 'TuneEngineRequest', + 'TuneEngineResponse', + 'UpdateEngineRequest', + 'BigQuerySource', + 'GcsSource', + 'ImportDocumentsMetadata', + 'ImportDocumentsRequest', + 'ImportDocumentsResponse', + 'ImportErrorConfig', + 'ImportUserEventsMetadata', + 'ImportUserEventsRequest', + 'ImportUserEventsResponse', + 'PurgeDocumentsMetadata', + 'PurgeDocumentsRequest', + 'PurgeDocumentsResponse', + 'PurgeUserEventsMetadata', + 'PurgeUserEventsRequest', + 'PurgeUserEventsResponse', + 'RecommendRequest', + 'RecommendResponse', + 'FieldConfig', + 'Schema', + 'CreateSchemaMetadata', + 'CreateSchemaRequest', + 'DeleteSchemaMetadata', + 'DeleteSchemaRequest', + 'GetSchemaRequest', + 'ListSchemasRequest', + 'ListSchemasResponse', + 'UpdateSchemaMetadata', + 'UpdateSchemaRequest', + 'SearchRequest', + 'SearchResponse', + 'RecrawlUrisMetadata', + 'RecrawlUrisRequest', + 'RecrawlUrisResponse', + 'CompletionInfo', + 'DocumentInfo', + 'MediaInfo', + 'PageInfo', + 'PanelInfo', + 'SearchInfo', + 'TransactionInfo', + 'UserEvent', + 'CollectUserEventRequest', + 'WriteUserEventRequest', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine/gapic_version.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine/gapic_version.py new file mode 100644 index 000000000000..360a0d13ebdd --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine/py.typed b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine/py.typed new file mode 100644 index 000000000000..2ff6437cf473 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-discoveryengine package uses inline types. diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/__init__.py new file mode 100644 index 000000000000..06627ea8bf76 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/__init__.py @@ -0,0 +1,256 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.completion_service import CompletionServiceClient +from .services.completion_service import CompletionServiceAsyncClient +from .services.conversational_search_service import ConversationalSearchServiceClient +from .services.conversational_search_service import ConversationalSearchServiceAsyncClient +from .services.data_store_service import DataStoreServiceClient +from .services.data_store_service import DataStoreServiceAsyncClient +from .services.document_service import DocumentServiceClient +from .services.document_service import DocumentServiceAsyncClient +from .services.engine_service import EngineServiceClient +from .services.engine_service import EngineServiceAsyncClient +from .services.recommendation_service import RecommendationServiceClient +from .services.recommendation_service import RecommendationServiceAsyncClient +from .services.schema_service import SchemaServiceClient +from .services.schema_service import SchemaServiceAsyncClient +from .services.search_service import SearchServiceClient +from .services.search_service import SearchServiceAsyncClient +from .services.site_search_engine_service import SiteSearchEngineServiceClient +from .services.site_search_engine_service import SiteSearchEngineServiceAsyncClient +from .services.user_event_service import UserEventServiceClient +from .services.user_event_service import UserEventServiceAsyncClient + +from .types.common import CustomAttribute +from .types.common import DoubleList +from .types.common import Interval +from .types.common import UserInfo +from .types.common import IndustryVertical +from .types.common import SearchAddOn +from .types.common import SearchTier +from .types.common import SolutionType +from .types.completion_service import CompleteQueryRequest +from .types.completion_service import CompleteQueryResponse +from .types.conversation import Conversation +from .types.conversation import ConversationContext +from .types.conversation import ConversationMessage +from .types.conversation import Reply +from .types.conversation import TextInput +from .types.conversational_search_service import ConverseConversationRequest +from .types.conversational_search_service import ConverseConversationResponse +from .types.conversational_search_service import CreateConversationRequest +from .types.conversational_search_service import DeleteConversationRequest +from .types.conversational_search_service import GetConversationRequest +from .types.conversational_search_service import ListConversationsRequest +from .types.conversational_search_service import ListConversationsResponse +from .types.conversational_search_service import UpdateConversationRequest +from .types.data_store import DataStore +from .types.data_store_service import CreateDataStoreMetadata +from .types.data_store_service import CreateDataStoreRequest +from .types.data_store_service import DeleteDataStoreMetadata +from .types.data_store_service import DeleteDataStoreRequest +from .types.data_store_service import GetDataStoreRequest +from .types.data_store_service import ListDataStoresRequest +from .types.data_store_service import ListDataStoresResponse +from .types.data_store_service import UpdateDataStoreRequest +from .types.document import Document +from .types.document_service import CreateDocumentRequest +from .types.document_service import DeleteDocumentRequest +from .types.document_service import GetDocumentRequest +from .types.document_service import ListDocumentsRequest +from .types.document_service import ListDocumentsResponse +from .types.document_service import UpdateDocumentRequest +from .types.engine import Engine +from .types.engine_service import CreateEngineMetadata +from .types.engine_service import CreateEngineRequest +from .types.engine_service import DeleteEngineMetadata +from .types.engine_service import DeleteEngineRequest +from .types.engine_service import GetEngineRequest +from .types.engine_service import ListEnginesRequest +from .types.engine_service import ListEnginesResponse +from .types.engine_service import PauseEngineRequest +from .types.engine_service import ResumeEngineRequest +from .types.engine_service import TuneEngineMetadata +from .types.engine_service import TuneEngineRequest +from .types.engine_service import TuneEngineResponse +from .types.engine_service import UpdateEngineRequest +from .types.import_config import BigQuerySource +from .types.import_config import GcsSource +from .types.import_config import ImportDocumentsMetadata +from .types.import_config import ImportDocumentsRequest +from .types.import_config import ImportDocumentsResponse +from .types.import_config import ImportErrorConfig +from .types.import_config import ImportUserEventsMetadata +from .types.import_config import ImportUserEventsRequest +from .types.import_config import ImportUserEventsResponse +from .types.purge_config import PurgeDocumentsMetadata +from .types.purge_config import PurgeDocumentsRequest +from .types.purge_config import PurgeDocumentsResponse +from .types.purge_config import PurgeUserEventsMetadata +from .types.purge_config import PurgeUserEventsRequest +from .types.purge_config import PurgeUserEventsResponse +from .types.recommendation_service import RecommendRequest +from .types.recommendation_service import RecommendResponse +from .types.schema import FieldConfig +from .types.schema import Schema +from .types.schema_service import CreateSchemaMetadata +from .types.schema_service import CreateSchemaRequest +from .types.schema_service import DeleteSchemaMetadata +from .types.schema_service import DeleteSchemaRequest +from .types.schema_service import GetSchemaRequest +from .types.schema_service import ListSchemasRequest +from .types.schema_service import ListSchemasResponse +from .types.schema_service import UpdateSchemaMetadata +from .types.schema_service import UpdateSchemaRequest +from .types.search_service import SearchRequest +from .types.search_service import SearchResponse +from .types.site_search_engine_service import RecrawlUrisMetadata +from .types.site_search_engine_service import RecrawlUrisRequest +from .types.site_search_engine_service import RecrawlUrisResponse +from .types.user_event import CompletionInfo +from .types.user_event import DocumentInfo +from .types.user_event import MediaInfo +from .types.user_event import PageInfo +from .types.user_event import PanelInfo +from .types.user_event import SearchInfo +from .types.user_event import TransactionInfo +from .types.user_event import UserEvent +from .types.user_event_service import CollectUserEventRequest +from .types.user_event_service import WriteUserEventRequest + +__all__ = ( + 'CompletionServiceAsyncClient', + 'ConversationalSearchServiceAsyncClient', + 'DataStoreServiceAsyncClient', + 'DocumentServiceAsyncClient', + 'EngineServiceAsyncClient', + 'RecommendationServiceAsyncClient', + 'SchemaServiceAsyncClient', + 'SearchServiceAsyncClient', + 'SiteSearchEngineServiceAsyncClient', + 'UserEventServiceAsyncClient', +'BigQuerySource', +'CollectUserEventRequest', +'CompleteQueryRequest', +'CompleteQueryResponse', +'CompletionInfo', +'CompletionServiceClient', +'Conversation', +'ConversationContext', +'ConversationMessage', +'ConversationalSearchServiceClient', +'ConverseConversationRequest', +'ConverseConversationResponse', +'CreateConversationRequest', +'CreateDataStoreMetadata', +'CreateDataStoreRequest', +'CreateDocumentRequest', +'CreateEngineMetadata', +'CreateEngineRequest', +'CreateSchemaMetadata', +'CreateSchemaRequest', +'CustomAttribute', +'DataStore', +'DataStoreServiceClient', +'DeleteConversationRequest', +'DeleteDataStoreMetadata', +'DeleteDataStoreRequest', +'DeleteDocumentRequest', +'DeleteEngineMetadata', +'DeleteEngineRequest', +'DeleteSchemaMetadata', +'DeleteSchemaRequest', +'Document', +'DocumentInfo', +'DocumentServiceClient', +'DoubleList', +'Engine', +'EngineServiceClient', +'FieldConfig', +'GcsSource', +'GetConversationRequest', +'GetDataStoreRequest', +'GetDocumentRequest', +'GetEngineRequest', +'GetSchemaRequest', +'ImportDocumentsMetadata', +'ImportDocumentsRequest', +'ImportDocumentsResponse', +'ImportErrorConfig', +'ImportUserEventsMetadata', +'ImportUserEventsRequest', +'ImportUserEventsResponse', +'IndustryVertical', +'Interval', +'ListConversationsRequest', +'ListConversationsResponse', +'ListDataStoresRequest', +'ListDataStoresResponse', +'ListDocumentsRequest', +'ListDocumentsResponse', +'ListEnginesRequest', +'ListEnginesResponse', +'ListSchemasRequest', +'ListSchemasResponse', +'MediaInfo', +'PageInfo', +'PanelInfo', +'PauseEngineRequest', +'PurgeDocumentsMetadata', +'PurgeDocumentsRequest', +'PurgeDocumentsResponse', +'PurgeUserEventsMetadata', +'PurgeUserEventsRequest', +'PurgeUserEventsResponse', +'RecommendRequest', +'RecommendResponse', +'RecommendationServiceClient', +'RecrawlUrisMetadata', +'RecrawlUrisRequest', +'RecrawlUrisResponse', +'Reply', +'ResumeEngineRequest', +'Schema', +'SchemaServiceClient', +'SearchAddOn', +'SearchInfo', +'SearchRequest', +'SearchResponse', +'SearchServiceClient', +'SearchTier', +'SiteSearchEngineServiceClient', +'SolutionType', +'TextInput', +'TransactionInfo', +'TuneEngineMetadata', +'TuneEngineRequest', +'TuneEngineResponse', +'UpdateConversationRequest', +'UpdateDataStoreRequest', +'UpdateDocumentRequest', +'UpdateEngineRequest', +'UpdateSchemaMetadata', +'UpdateSchemaRequest', +'UserEvent', +'UserEventServiceClient', +'UserInfo', +'WriteUserEventRequest', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/gapic_metadata.json b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/gapic_metadata.json new file mode 100644 index 000000000000..6d78899820ae --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/gapic_metadata.json @@ -0,0 +1,784 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.discoveryengine_v1alpha", + "protoPackage": "google.cloud.discoveryengine.v1alpha", + "schema": "1.0", + "services": { + "CompletionService": { + "clients": { + "grpc": { + "libraryClient": "CompletionServiceClient", + "rpcs": { + "CompleteQuery": { + "methods": [ + "complete_query" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CompletionServiceAsyncClient", + "rpcs": { + "CompleteQuery": { + "methods": [ + "complete_query" + ] + } + } + }, + "rest": { + "libraryClient": "CompletionServiceClient", + "rpcs": { + "CompleteQuery": { + "methods": [ + "complete_query" + ] + } + } + } + } + }, + "ConversationalSearchService": { + "clients": { + "grpc": { + "libraryClient": "ConversationalSearchServiceClient", + "rpcs": { + "ConverseConversation": { + "methods": [ + "converse_conversation" + ] + }, + "CreateConversation": { + "methods": [ + "create_conversation" + ] + }, + "DeleteConversation": { + "methods": [ + "delete_conversation" + ] + }, + "GetConversation": { + "methods": [ + "get_conversation" + ] + }, + "ListConversations": { + "methods": [ + "list_conversations" + ] + }, + "UpdateConversation": { + "methods": [ + "update_conversation" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ConversationalSearchServiceAsyncClient", + "rpcs": { + "ConverseConversation": { + "methods": [ + "converse_conversation" + ] + }, + "CreateConversation": { + "methods": [ + "create_conversation" + ] + }, + "DeleteConversation": { + "methods": [ + "delete_conversation" + ] + }, + "GetConversation": { + "methods": [ + "get_conversation" + ] + }, + "ListConversations": { + "methods": [ + "list_conversations" + ] + }, + "UpdateConversation": { + "methods": [ + "update_conversation" + ] + } + } + }, + "rest": { + "libraryClient": "ConversationalSearchServiceClient", + "rpcs": { + "ConverseConversation": { + "methods": [ + "converse_conversation" + ] + }, + "CreateConversation": { + "methods": [ + "create_conversation" + ] + }, + "DeleteConversation": { + "methods": [ + "delete_conversation" + ] + }, + "GetConversation": { + "methods": [ + "get_conversation" + ] + }, + "ListConversations": { + "methods": [ + "list_conversations" + ] + }, + "UpdateConversation": { + "methods": [ + "update_conversation" + ] + } + } + } + } + }, + "DataStoreService": { + "clients": { + "grpc": { + "libraryClient": "DataStoreServiceClient", + "rpcs": { + "CreateDataStore": { + "methods": [ + "create_data_store" + ] + }, + "DeleteDataStore": { + "methods": [ + "delete_data_store" + ] + }, + "GetDataStore": { + "methods": [ + "get_data_store" + ] + }, + "ListDataStores": { + "methods": [ + "list_data_stores" + ] + }, + "UpdateDataStore": { + "methods": [ + "update_data_store" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DataStoreServiceAsyncClient", + "rpcs": { + "CreateDataStore": { + "methods": [ + "create_data_store" + ] + }, + "DeleteDataStore": { + "methods": [ + "delete_data_store" + ] + }, + "GetDataStore": { + "methods": [ + "get_data_store" + ] + }, + "ListDataStores": { + "methods": [ + "list_data_stores" + ] + }, + "UpdateDataStore": { + "methods": [ + "update_data_store" + ] + } + } + }, + "rest": { + "libraryClient": "DataStoreServiceClient", + "rpcs": { + "CreateDataStore": { + "methods": [ + "create_data_store" + ] + }, + "DeleteDataStore": { + "methods": [ + "delete_data_store" + ] + }, + "GetDataStore": { + "methods": [ + "get_data_store" + ] + }, + "ListDataStores": { + "methods": [ + "list_data_stores" + ] + }, + "UpdateDataStore": { + "methods": [ + "update_data_store" + ] + } + } + } + } + }, + "DocumentService": { + "clients": { + "grpc": { + "libraryClient": "DocumentServiceClient", + "rpcs": { + "CreateDocument": { + "methods": [ + "create_document" + ] + }, + "DeleteDocument": { + "methods": [ + "delete_document" + ] + }, + "GetDocument": { + "methods": [ + "get_document" + ] + }, + "ImportDocuments": { + "methods": [ + "import_documents" + ] + }, + "ListDocuments": { + "methods": [ + "list_documents" + ] + }, + "PurgeDocuments": { + "methods": [ + "purge_documents" + ] + }, + "UpdateDocument": { + "methods": [ + "update_document" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DocumentServiceAsyncClient", + "rpcs": { + "CreateDocument": { + "methods": [ + "create_document" + ] + }, + "DeleteDocument": { + "methods": [ + "delete_document" + ] + }, + "GetDocument": { + "methods": [ + "get_document" + ] + }, + "ImportDocuments": { + "methods": [ + "import_documents" + ] + }, + "ListDocuments": { + "methods": [ + "list_documents" + ] + }, + "PurgeDocuments": { + "methods": [ + "purge_documents" + ] + }, + "UpdateDocument": { + "methods": [ + "update_document" + ] + } + } + }, + "rest": { + "libraryClient": "DocumentServiceClient", + "rpcs": { + "CreateDocument": { + "methods": [ + "create_document" + ] + }, + "DeleteDocument": { + "methods": [ + "delete_document" + ] + }, + "GetDocument": { + "methods": [ + "get_document" + ] + }, + "ImportDocuments": { + "methods": [ + "import_documents" + ] + }, + "ListDocuments": { + "methods": [ + "list_documents" + ] + }, + "PurgeDocuments": { + "methods": [ + "purge_documents" + ] + }, + "UpdateDocument": { + "methods": [ + "update_document" + ] + } + } + } + } + }, + "EngineService": { + "clients": { + "grpc": { + "libraryClient": "EngineServiceClient", + "rpcs": { + "CreateEngine": { + "methods": [ + "create_engine" + ] + }, + "DeleteEngine": { + "methods": [ + "delete_engine" + ] + }, + "GetEngine": { + "methods": [ + "get_engine" + ] + }, + "ListEngines": { + "methods": [ + "list_engines" + ] + }, + "PauseEngine": { + "methods": [ + "pause_engine" + ] + }, + "ResumeEngine": { + "methods": [ + "resume_engine" + ] + }, + "TuneEngine": { + "methods": [ + "tune_engine" + ] + }, + "UpdateEngine": { + "methods": [ + "update_engine" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EngineServiceAsyncClient", + "rpcs": { + "CreateEngine": { + "methods": [ + "create_engine" + ] + }, + "DeleteEngine": { + "methods": [ + "delete_engine" + ] + }, + "GetEngine": { + "methods": [ + "get_engine" + ] + }, + "ListEngines": { + "methods": [ + "list_engines" + ] + }, + "PauseEngine": { + "methods": [ + "pause_engine" + ] + }, + "ResumeEngine": { + "methods": [ + "resume_engine" + ] + }, + "TuneEngine": { + "methods": [ + "tune_engine" + ] + }, + "UpdateEngine": { + "methods": [ + "update_engine" + ] + } + } + }, + "rest": { + "libraryClient": "EngineServiceClient", + "rpcs": { + "CreateEngine": { + "methods": [ + "create_engine" + ] + }, + "DeleteEngine": { + "methods": [ + "delete_engine" + ] + }, + "GetEngine": { + "methods": [ + "get_engine" + ] + }, + "ListEngines": { + "methods": [ + "list_engines" + ] + }, + "PauseEngine": { + "methods": [ + "pause_engine" + ] + }, + "ResumeEngine": { + "methods": [ + "resume_engine" + ] + }, + "TuneEngine": { + "methods": [ + "tune_engine" + ] + }, + "UpdateEngine": { + "methods": [ + "update_engine" + ] + } + } + } + } + }, + "RecommendationService": { + "clients": { + "grpc": { + "libraryClient": "RecommendationServiceClient", + "rpcs": { + "Recommend": { + "methods": [ + "recommend" + ] + } + } + }, + "grpc-async": { + "libraryClient": "RecommendationServiceAsyncClient", + "rpcs": { + "Recommend": { + "methods": [ + "recommend" + ] + } + } + }, + "rest": { + "libraryClient": "RecommendationServiceClient", + "rpcs": { + "Recommend": { + "methods": [ + "recommend" + ] + } + } + } + } + }, + "SchemaService": { + "clients": { + "grpc": { + "libraryClient": "SchemaServiceClient", + "rpcs": { + "CreateSchema": { + "methods": [ + "create_schema" + ] + }, + "DeleteSchema": { + "methods": [ + "delete_schema" + ] + }, + "GetSchema": { + "methods": [ + "get_schema" + ] + }, + "ListSchemas": { + "methods": [ + "list_schemas" + ] + }, + "UpdateSchema": { + "methods": [ + "update_schema" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SchemaServiceAsyncClient", + "rpcs": { + "CreateSchema": { + "methods": [ + "create_schema" + ] + }, + "DeleteSchema": { + "methods": [ + "delete_schema" + ] + }, + "GetSchema": { + "methods": [ + "get_schema" + ] + }, + "ListSchemas": { + "methods": [ + "list_schemas" + ] + }, + "UpdateSchema": { + "methods": [ + "update_schema" + ] + } + } + }, + "rest": { + "libraryClient": "SchemaServiceClient", + "rpcs": { + "CreateSchema": { + "methods": [ + "create_schema" + ] + }, + "DeleteSchema": { + "methods": [ + "delete_schema" + ] + }, + "GetSchema": { + "methods": [ + "get_schema" + ] + }, + "ListSchemas": { + "methods": [ + "list_schemas" + ] + }, + "UpdateSchema": { + "methods": [ + "update_schema" + ] + } + } + } + } + }, + "SearchService": { + "clients": { + "grpc": { + "libraryClient": "SearchServiceClient", + "rpcs": { + "Search": { + "methods": [ + "search" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SearchServiceAsyncClient", + "rpcs": { + "Search": { + "methods": [ + "search" + ] + } + } + }, + "rest": { + "libraryClient": "SearchServiceClient", + "rpcs": { + "Search": { + "methods": [ + "search" + ] + } + } + } + } + }, + "SiteSearchEngineService": { + "clients": { + "grpc": { + "libraryClient": "SiteSearchEngineServiceClient", + "rpcs": { + "RecrawlUris": { + "methods": [ + "recrawl_uris" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SiteSearchEngineServiceAsyncClient", + "rpcs": { + "RecrawlUris": { + "methods": [ + "recrawl_uris" + ] + } + } + }, + "rest": { + "libraryClient": "SiteSearchEngineServiceClient", + "rpcs": { + "RecrawlUris": { + "methods": [ + "recrawl_uris" + ] + } + } + } + } + }, + "UserEventService": { + "clients": { + "grpc": { + "libraryClient": "UserEventServiceClient", + "rpcs": { + "CollectUserEvent": { + "methods": [ + "collect_user_event" + ] + }, + "ImportUserEvents": { + "methods": [ + "import_user_events" + ] + }, + "PurgeUserEvents": { + "methods": [ + "purge_user_events" + ] + }, + "WriteUserEvent": { + "methods": [ + "write_user_event" + ] + } + } + }, + "grpc-async": { + "libraryClient": "UserEventServiceAsyncClient", + "rpcs": { + "CollectUserEvent": { + "methods": [ + "collect_user_event" + ] + }, + "ImportUserEvents": { + "methods": [ + "import_user_events" + ] + }, + "PurgeUserEvents": { + "methods": [ + "purge_user_events" + ] + }, + "WriteUserEvent": { + "methods": [ + "write_user_event" + ] + } + } + }, + "rest": { + "libraryClient": "UserEventServiceClient", + "rpcs": { + "CollectUserEvent": { + "methods": [ + "collect_user_event" + ] + }, + "ImportUserEvents": { + "methods": [ + "import_user_events" + ] + }, + "PurgeUserEvents": { + "methods": [ + "purge_user_events" + ] + }, + "WriteUserEvent": { + "methods": [ + "write_user_event" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/gapic_version.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/gapic_version.py new file mode 100644 index 000000000000..360a0d13ebdd --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/py.typed b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/py.typed new file mode 100644 index 000000000000..2ff6437cf473 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-discoveryengine package uses inline types. diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/__init__.py new file mode 100644 index 000000000000..89a37dc92c5a --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/__init__.py new file mode 100644 index 000000000000..440cbfb40963 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import CompletionServiceClient +from .async_client import CompletionServiceAsyncClient + +__all__ = ( + 'CompletionServiceClient', + 'CompletionServiceAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/async_client.py new file mode 100644 index 000000000000..fc3be4cb3409 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/async_client.py @@ -0,0 +1,386 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import completion_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport +from .client import CompletionServiceClient + + +class CompletionServiceAsyncClient: + """Service for Auto-Completion.""" + + _client: CompletionServiceClient + + DEFAULT_ENDPOINT = CompletionServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = CompletionServiceClient.DEFAULT_MTLS_ENDPOINT + + data_store_path = staticmethod(CompletionServiceClient.data_store_path) + parse_data_store_path = staticmethod(CompletionServiceClient.parse_data_store_path) + common_billing_account_path = staticmethod(CompletionServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(CompletionServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(CompletionServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(CompletionServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(CompletionServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(CompletionServiceClient.parse_common_organization_path) + common_project_path = staticmethod(CompletionServiceClient.common_project_path) + parse_common_project_path = staticmethod(CompletionServiceClient.parse_common_project_path) + common_location_path = staticmethod(CompletionServiceClient.common_location_path) + parse_common_location_path = staticmethod(CompletionServiceClient.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: + CompletionServiceAsyncClient: The constructed client. + """ + return CompletionServiceClient.from_service_account_info.__func__(CompletionServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceAsyncClient: The constructed client. + """ + return CompletionServiceClient.from_service_account_file.__func__(CompletionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return CompletionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> CompletionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CompletionServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(CompletionServiceClient).get_transport_class, type(CompletionServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, CompletionServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the completion 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 (Union[str, ~.CompletionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = CompletionServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def complete_query(self, + request: Optional[Union[completion_service.CompleteQueryRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> completion_service.CompleteQueryResponse: + r"""Completes the specified user input with keyword + suggestions. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_complete_query(): + # Create a client + client = discoveryengine_v1alpha.CompletionServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.CompleteQueryRequest( + data_store="data_store_value", + query="query_value", + ) + + # Make the request + response = await client.complete_query(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.CompleteQueryRequest, dict]]): + The request object. Request message for + [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1alpha.CompletionService.CompleteQuery] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.CompleteQueryResponse: + Response message for + [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1alpha.CompletionService.CompleteQuery] + method. + + """ + # Create or coerce a protobuf request object. + request = completion_service.CompleteQueryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.complete_query, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("data_store", request.data_store), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "CompletionServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "CompletionServiceAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/client.py new file mode 100644 index 000000000000..0a1d4409407e --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/client.py @@ -0,0 +1,594 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import completion_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import CompletionServiceGrpcTransport +from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport +from .transports.rest import CompletionServiceRestTransport + + +class CompletionServiceClientMeta(type): + """Metaclass for the CompletionService 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[CompletionServiceTransport]] + _transport_registry["grpc"] = CompletionServiceGrpcTransport + _transport_registry["grpc_asyncio"] = CompletionServiceGrpcAsyncIOTransport + _transport_registry["rest"] = CompletionServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[CompletionServiceTransport]: + """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 CompletionServiceClient(metaclass=CompletionServiceClientMeta): + """Service for Auto-Completion.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceClient: 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: + CompletionServiceClient: 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) -> CompletionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CompletionServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def data_store_path(project: str,location: str,data_store: str,) -> str: + """Returns a fully-qualified data_store string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) + + @staticmethod + def parse_data_store_path(path: str) -> Dict[str,str]: + """Parses a data_store path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, CompletionServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the completion 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 (Union[str, CompletionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, CompletionServiceTransport): + # transport is a CompletionServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def complete_query(self, + request: Optional[Union[completion_service.CompleteQueryRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> completion_service.CompleteQueryResponse: + r"""Completes the specified user input with keyword + suggestions. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_complete_query(): + # Create a client + client = discoveryengine_v1alpha.CompletionServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.CompleteQueryRequest( + data_store="data_store_value", + query="query_value", + ) + + # Make the request + response = client.complete_query(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.CompleteQueryRequest, dict]): + The request object. Request message for + [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1alpha.CompletionService.CompleteQuery] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.CompleteQueryResponse: + Response message for + [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1alpha.CompletionService.CompleteQuery] + method. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a completion_service.CompleteQueryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, completion_service.CompleteQueryRequest): + request = completion_service.CompleteQueryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.complete_query] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("data_store", request.data_store), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "CompletionServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "CompletionServiceClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/__init__.py new file mode 100644 index 000000000000..f32ad4419b13 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import CompletionServiceTransport +from .grpc import CompletionServiceGrpcTransport +from .grpc_asyncio import CompletionServiceGrpcAsyncIOTransport +from .rest import CompletionServiceRestTransport +from .rest import CompletionServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] +_transport_registry['grpc'] = CompletionServiceGrpcTransport +_transport_registry['grpc_asyncio'] = CompletionServiceGrpcAsyncIOTransport +_transport_registry['rest'] = CompletionServiceRestTransport + +__all__ = ( + 'CompletionServiceTransport', + 'CompletionServiceGrpcTransport', + 'CompletionServiceGrpcAsyncIOTransport', + 'CompletionServiceRestTransport', + 'CompletionServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/base.py new file mode 100644 index 000000000000..e4f66cbdc4d3 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/base.py @@ -0,0 +1,168 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import completion_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class CompletionServiceTransport(abc.ABC): + """Abstract transport class for CompletionService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'discoveryengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.complete_query: gapic_v1.method.wrap_method( + self.complete_query, + 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 complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + Union[ + completion_service.CompleteQueryResponse, + Awaitable[completion_service.CompleteQueryResponse] + ]]: + 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 kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'CompletionServiceTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/grpc.py new file mode 100644 index 000000000000..01af23230592 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/grpc.py @@ -0,0 +1,303 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import completion_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO + + +class CompletionServiceGrpcTransport(CompletionServiceTransport): + """gRPC backend transport for CompletionService. + + Service for Auto-Completion. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + completion_service.CompleteQueryResponse]: + r"""Return a callable for the complete query method over gRPC. + + Completes the specified user input with keyword + suggestions. + + Returns: + Callable[[~.CompleteQueryRequest], + ~.CompleteQueryResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'complete_query' not in self._stubs: + self._stubs['complete_query'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.CompletionService/CompleteQuery', + request_serializer=completion_service.CompleteQueryRequest.serialize, + response_deserializer=completion_service.CompleteQueryResponse.deserialize, + ) + return self._stubs['complete_query'] + + def close(self): + self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'CompletionServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..2b7eea04ea61 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/grpc_asyncio.py @@ -0,0 +1,302 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import completion_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import CompletionServiceGrpcTransport + + +class CompletionServiceGrpcAsyncIOTransport(CompletionServiceTransport): + """gRPC AsyncIO backend transport for CompletionService. + + Service for Auto-Completion. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + Awaitable[completion_service.CompleteQueryResponse]]: + r"""Return a callable for the complete query method over gRPC. + + Completes the specified user input with keyword + suggestions. + + Returns: + Callable[[~.CompleteQueryRequest], + Awaitable[~.CompleteQueryResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'complete_query' not in self._stubs: + self._stubs['complete_query'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.CompletionService/CompleteQuery', + request_serializer=completion_service.CompleteQueryRequest.serialize, + response_deserializer=completion_service.CompleteQueryResponse.deserialize, + ) + return self._stubs['complete_query'] + + def close(self): + return self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ( + 'CompletionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/rest.py new file mode 100644 index 000000000000..70ffa099b61f --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/rest.py @@ -0,0 +1,566 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.cloud.location import locations_pb2 # type: ignore +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.discoveryengine_v1alpha.types import completion_service +from google.longrunning import operations_pb2 # type: ignore + +from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class CompletionServiceRestInterceptor: + """Interceptor for CompletionService. + + 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 CompletionServiceRestTransport. + + .. code-block:: python + class MyCustomCompletionServiceInterceptor(CompletionServiceRestInterceptor): + def pre_complete_query(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_complete_query(self, response): + logging.log(f"Received response: {response}") + return response + + transport = CompletionServiceRestTransport(interceptor=MyCustomCompletionServiceInterceptor()) + client = CompletionServiceClient(transport=transport) + + + """ + def pre_complete_query(self, request: completion_service.CompleteQueryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[completion_service.CompleteQueryRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for complete_query + + Override in a subclass to manipulate the request or metadata + before they are sent to the CompletionService server. + """ + return request, metadata + + def post_complete_query(self, response: completion_service.CompleteQueryResponse) -> completion_service.CompleteQueryResponse: + """Post-rpc interceptor for complete_query + + Override in a subclass to manipulate the response + after it is returned by the CompletionService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the CompletionService 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 CompletionService server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the CompletionService 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 CompletionService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class CompletionServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: CompletionServiceRestInterceptor + + +class CompletionServiceRestTransport(CompletionServiceTransport): + """REST backend transport for CompletionService. + + Service for Auto-Completion. + + 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 = 'discoveryengine.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[CompletionServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or CompletionServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CompleteQuery(CompletionServiceRestStub): + def __hash__(self): + return hash("CompleteQuery") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "query" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: completion_service.CompleteQueryRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> completion_service.CompleteQueryResponse: + r"""Call the complete query method over HTTP. + + Args: + request (~.completion_service.CompleteQueryRequest): + The request object. Request message for + [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1alpha.CompletionService.CompleteQuery] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.completion_service.CompleteQueryResponse: + Response message for + [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1alpha.CompletionService.CompleteQuery] + method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{data_store=projects/*/locations/*/dataStores/*}:completeQuery', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{data_store=projects/*/locations/*/collections/*/dataStores/*}:completeQuery', + }, + ] + request, metadata = self._interceptor.pre_complete_query(request, metadata) + pb_request = completion_service.CompleteQueryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = completion_service.CompleteQueryResponse() + pb_resp = completion_service.CompleteQueryResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_complete_query(resp) + return resp + + @property + def complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + completion_service.CompleteQueryResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CompleteQuery(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(CompletionServiceRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(CompletionServiceRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'CompletionServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/__init__.py new file mode 100644 index 000000000000..4bf42b241a8b --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import ConversationalSearchServiceClient +from .async_client import ConversationalSearchServiceAsyncClient + +__all__ = ( + 'ConversationalSearchServiceClient', + 'ConversationalSearchServiceAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/async_client.py new file mode 100644 index 000000000000..f0be82ed1b20 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/async_client.py @@ -0,0 +1,971 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.discoveryengine_v1alpha.services.conversational_search_service import pagers +from google.cloud.discoveryengine_v1alpha.types import conversation +from google.cloud.discoveryengine_v1alpha.types import conversation as gcd_conversation +from google.cloud.discoveryengine_v1alpha.types import conversational_search_service +from google.cloud.discoveryengine_v1alpha.types import search_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ConversationalSearchServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ConversationalSearchServiceGrpcAsyncIOTransport +from .client import ConversationalSearchServiceClient + + +class ConversationalSearchServiceAsyncClient: + """Service for conversational search.""" + + _client: ConversationalSearchServiceClient + + DEFAULT_ENDPOINT = ConversationalSearchServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ConversationalSearchServiceClient.DEFAULT_MTLS_ENDPOINT + + conversation_path = staticmethod(ConversationalSearchServiceClient.conversation_path) + parse_conversation_path = staticmethod(ConversationalSearchServiceClient.parse_conversation_path) + data_store_path = staticmethod(ConversationalSearchServiceClient.data_store_path) + parse_data_store_path = staticmethod(ConversationalSearchServiceClient.parse_data_store_path) + document_path = staticmethod(ConversationalSearchServiceClient.document_path) + parse_document_path = staticmethod(ConversationalSearchServiceClient.parse_document_path) + serving_config_path = staticmethod(ConversationalSearchServiceClient.serving_config_path) + parse_serving_config_path = staticmethod(ConversationalSearchServiceClient.parse_serving_config_path) + common_billing_account_path = staticmethod(ConversationalSearchServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ConversationalSearchServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ConversationalSearchServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(ConversationalSearchServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(ConversationalSearchServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(ConversationalSearchServiceClient.parse_common_organization_path) + common_project_path = staticmethod(ConversationalSearchServiceClient.common_project_path) + parse_common_project_path = staticmethod(ConversationalSearchServiceClient.parse_common_project_path) + common_location_path = staticmethod(ConversationalSearchServiceClient.common_location_path) + parse_common_location_path = staticmethod(ConversationalSearchServiceClient.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: + ConversationalSearchServiceAsyncClient: The constructed client. + """ + return ConversationalSearchServiceClient.from_service_account_info.__func__(ConversationalSearchServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ConversationalSearchServiceAsyncClient: The constructed client. + """ + return ConversationalSearchServiceClient.from_service_account_file.__func__(ConversationalSearchServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return ConversationalSearchServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ConversationalSearchServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ConversationalSearchServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ConversationalSearchServiceClient).get_transport_class, type(ConversationalSearchServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ConversationalSearchServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the conversational search 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 (Union[str, ~.ConversationalSearchServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ConversationalSearchServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def converse_conversation(self, + request: Optional[Union[conversational_search_service.ConverseConversationRequest, dict]] = None, + *, + name: Optional[str] = None, + query: Optional[conversation.TextInput] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversational_search_service.ConverseConversationResponse: + r"""Converses 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 discoveryengine_v1alpha + + async def sample_converse_conversation(): + # Create a client + client = discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ConverseConversationRequest( + name="name_value", + ) + + # Make the request + response = await client.converse_conversation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.ConverseConversationRequest, dict]]): + The request object. Request message for + [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1alpha.ConversationalSearchService.ConverseConversation] + method. + name (:class:`str`): + Required. The resource name of the Conversation to get. + Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}``. + Use + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/-`` + to activate auto session mode, which automatically + creates a new conversation inside a ConverseConversation + session. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + query (:class:`google.cloud.discoveryengine_v1alpha.types.TextInput`): + Required. Current user input. + This corresponds to the ``query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.ConverseConversationResponse: + Response message for + [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1alpha.ConversationalSearchService.ConverseConversation] + method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, query]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = conversational_search_service.ConverseConversationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if query is not None: + request.query = query + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.converse_conversation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_conversation(self, + request: Optional[Union[conversational_search_service.CreateConversationRequest, dict]] = None, + *, + parent: Optional[str] = None, + conversation: Optional[gcd_conversation.Conversation] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_conversation.Conversation: + r"""Creates a Conversation. + + If the + [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] + to create already exists, an ALREADY_EXISTS error is returned. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_create_conversation(): + # Create a client + client = discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.CreateConversationRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_conversation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.CreateConversationRequest, dict]]): + The request object. Request for CreateConversation + method. + parent (:class:`str`): + Required. Full resource name of parent data store. + Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + conversation (:class:`google.cloud.discoveryengine_v1alpha.types.Conversation`): + Required. The conversation to create. + This corresponds to the ``conversation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.Conversation: + External conversation proto + definition. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, conversation]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = conversational_search_service.CreateConversationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if conversation is not None: + request.conversation = conversation + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_conversation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_conversation(self, + request: Optional[Union[conversational_search_service.DeleteConversationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a Conversation. + + If the + [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] + to delete does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_delete_conversation(): + # Create a client + client = discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.DeleteConversationRequest( + name="name_value", + ) + + # Make the request + await client.delete_conversation(request=request) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.DeleteConversationRequest, dict]]): + The request object. Request for DeleteConversation + method. + name (:class:`str`): + Required. The resource name of the Conversation to + delete. Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = conversational_search_service.DeleteConversationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_conversation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def update_conversation(self, + request: Optional[Union[conversational_search_service.UpdateConversationRequest, dict]] = None, + *, + conversation: Optional[gcd_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, str]] = (), + ) -> gcd_conversation.Conversation: + r"""Updates a Conversation. + + [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] + action type cannot be changed. If the + [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] + to update does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_update_conversation(): + # Create a client + client = discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.UpdateConversationRequest( + ) + + # Make the request + response = await client.update_conversation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.UpdateConversationRequest, dict]]): + The request object. Request for UpdateConversation + method. + conversation (:class:`google.cloud.discoveryengine_v1alpha.types.Conversation`): + Required. The Conversation to update. + 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`): + Indicates which fields in the provided + [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] + to update. The following are NOT supported: + + - [conversation.name][] + + If not set or empty, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.Conversation: + External conversation proto + definition. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([conversation, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = conversational_search_service.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 = gapic_v1.method_async.wrap_method( + self._client._transport.update_conversation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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), + )), + ) + + # 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[conversational_search_service.GetConversationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversation.Conversation: + r"""Gets 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 discoveryengine_v1alpha + + async def sample_get_conversation(): + # Create a client + client = discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.GetConversationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_conversation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.GetConversationRequest, dict]]): + The request object. Request for GetConversation method. + name (:class:`str`): + Required. The resource name of the Conversation to get. + Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.Conversation: + External conversation proto + definition. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = conversational_search_service.GetConversationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_conversation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_conversations(self, + request: Optional[Union[conversational_search_service.ListConversationsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListConversationsAsyncPager: + r"""Lists all Conversations by their parent + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_list_conversations(): + # Create a client + client = discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ListConversationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_conversations(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.ListConversationsRequest, dict]]): + The request object. Request for ListConversations method. + parent (:class:`str`): + Required. The data store resource name. Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.services.conversational_search_service.pagers.ListConversationsAsyncPager: + Response for ListConversations + method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = conversational_search_service.ListConversationsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_conversations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListConversationsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "ConversationalSearchServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "ConversationalSearchServiceAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/client.py new file mode 100644 index 000000000000..ede7ea5403a0 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/client.py @@ -0,0 +1,1205 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.discoveryengine_v1alpha.services.conversational_search_service import pagers +from google.cloud.discoveryengine_v1alpha.types import conversation +from google.cloud.discoveryengine_v1alpha.types import conversation as gcd_conversation +from google.cloud.discoveryengine_v1alpha.types import conversational_search_service +from google.cloud.discoveryengine_v1alpha.types import search_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ConversationalSearchServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ConversationalSearchServiceGrpcTransport +from .transports.grpc_asyncio import ConversationalSearchServiceGrpcAsyncIOTransport +from .transports.rest import ConversationalSearchServiceRestTransport + + +class ConversationalSearchServiceClientMeta(type): + """Metaclass for the ConversationalSearchService 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[ConversationalSearchServiceTransport]] + _transport_registry["grpc"] = ConversationalSearchServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ConversationalSearchServiceGrpcAsyncIOTransport + _transport_registry["rest"] = ConversationalSearchServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[ConversationalSearchServiceTransport]: + """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 ConversationalSearchServiceClient(metaclass=ConversationalSearchServiceClientMeta): + """Service for conversational search.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ConversationalSearchServiceClient: 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: + ConversationalSearchServiceClient: 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) -> ConversationalSearchServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ConversationalSearchServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def conversation_path(project: str,location: str,data_store: str,conversation: str,) -> str: + """Returns a fully-qualified conversation string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/conversations/{conversation}".format(project=project, location=location, data_store=data_store, conversation=conversation, ) + + @staticmethod + def parse_conversation_path(path: str) -> Dict[str,str]: + """Parses a conversation path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/conversations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def data_store_path(project: str,location: str,data_store: str,) -> str: + """Returns a fully-qualified data_store string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) + + @staticmethod + def parse_data_store_path(path: str) -> Dict[str,str]: + """Parses a data_store path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def document_path(project: str,location: str,data_store: str,branch: str,document: str,) -> str: + """Returns a fully-qualified document string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) + + @staticmethod + def parse_document_path(path: str) -> Dict[str,str]: + """Parses a document path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)/documents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def serving_config_path(project: str,location: str,data_store: str,serving_config: str,) -> str: + """Returns a fully-qualified serving_config string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/servingConfigs/{serving_config}".format(project=project, location=location, data_store=data_store, serving_config=serving_config, ) + + @staticmethod + def parse_serving_config_path(path: str) -> Dict[str,str]: + """Parses a serving_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/servingConfigs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ConversationalSearchServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the conversational search 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 (Union[str, ConversationalSearchServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ConversationalSearchServiceTransport): + # transport is a ConversationalSearchServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def converse_conversation(self, + request: Optional[Union[conversational_search_service.ConverseConversationRequest, dict]] = None, + *, + name: Optional[str] = None, + query: Optional[conversation.TextInput] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversational_search_service.ConverseConversationResponse: + r"""Converses 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 discoveryengine_v1alpha + + def sample_converse_conversation(): + # Create a client + client = discoveryengine_v1alpha.ConversationalSearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ConverseConversationRequest( + name="name_value", + ) + + # Make the request + response = client.converse_conversation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.ConverseConversationRequest, dict]): + The request object. Request message for + [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1alpha.ConversationalSearchService.ConverseConversation] + method. + name (str): + Required. The resource name of the Conversation to get. + Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}``. + Use + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/-`` + to activate auto session mode, which automatically + creates a new conversation inside a ConverseConversation + session. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + query (google.cloud.discoveryengine_v1alpha.types.TextInput): + Required. Current user input. + This corresponds to the ``query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.ConverseConversationResponse: + Response message for + [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1alpha.ConversationalSearchService.ConverseConversation] + method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, query]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a conversational_search_service.ConverseConversationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, conversational_search_service.ConverseConversationRequest): + request = conversational_search_service.ConverseConversationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if query is not None: + request.query = query + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.converse_conversation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_conversation(self, + request: Optional[Union[conversational_search_service.CreateConversationRequest, dict]] = None, + *, + parent: Optional[str] = None, + conversation: Optional[gcd_conversation.Conversation] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_conversation.Conversation: + r"""Creates a Conversation. + + If the + [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] + to create already exists, an ALREADY_EXISTS error is returned. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_create_conversation(): + # Create a client + client = discoveryengine_v1alpha.ConversationalSearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.CreateConversationRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_conversation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.CreateConversationRequest, dict]): + The request object. Request for CreateConversation + method. + parent (str): + Required. Full resource name of parent data store. + Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + conversation (google.cloud.discoveryengine_v1alpha.types.Conversation): + Required. The conversation to create. + This corresponds to the ``conversation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.Conversation: + External conversation proto + definition. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, conversation]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a conversational_search_service.CreateConversationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, conversational_search_service.CreateConversationRequest): + request = conversational_search_service.CreateConversationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if conversation is not None: + request.conversation = conversation + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_conversation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_conversation(self, + request: Optional[Union[conversational_search_service.DeleteConversationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a Conversation. + + If the + [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] + to delete does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_delete_conversation(): + # Create a client + client = discoveryengine_v1alpha.ConversationalSearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.DeleteConversationRequest( + name="name_value", + ) + + # Make the request + client.delete_conversation(request=request) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.DeleteConversationRequest, dict]): + The request object. Request for DeleteConversation + method. + name (str): + Required. The resource name of the Conversation to + delete. Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a conversational_search_service.DeleteConversationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, conversational_search_service.DeleteConversationRequest): + request = conversational_search_service.DeleteConversationRequest(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_conversation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def update_conversation(self, + request: Optional[Union[conversational_search_service.UpdateConversationRequest, dict]] = None, + *, + conversation: Optional[gcd_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, str]] = (), + ) -> gcd_conversation.Conversation: + r"""Updates a Conversation. + + [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] + action type cannot be changed. If the + [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] + to update does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_update_conversation(): + # Create a client + client = discoveryengine_v1alpha.ConversationalSearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.UpdateConversationRequest( + ) + + # Make the request + response = client.update_conversation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.UpdateConversationRequest, dict]): + The request object. Request for UpdateConversation + method. + conversation (google.cloud.discoveryengine_v1alpha.types.Conversation): + Required. The Conversation to update. + 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): + Indicates which fields in the provided + [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] + to update. The following are NOT supported: + + - [conversation.name][] + + If not set or empty, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.Conversation: + External conversation proto + definition. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([conversation, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a conversational_search_service.UpdateConversationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, conversational_search_service.UpdateConversationRequest): + request = conversational_search_service.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), + )), + ) + + # 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[conversational_search_service.GetConversationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversation.Conversation: + r"""Gets 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 discoveryengine_v1alpha + + def sample_get_conversation(): + # Create a client + client = discoveryengine_v1alpha.ConversationalSearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.GetConversationRequest( + name="name_value", + ) + + # Make the request + response = client.get_conversation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.GetConversationRequest, dict]): + The request object. Request for GetConversation method. + name (str): + Required. The resource name of the Conversation to get. + Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.Conversation: + External conversation proto + definition. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a conversational_search_service.GetConversationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, conversational_search_service.GetConversationRequest): + request = conversational_search_service.GetConversationRequest(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_conversation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_conversations(self, + request: Optional[Union[conversational_search_service.ListConversationsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListConversationsPager: + r"""Lists all Conversations by their parent + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_list_conversations(): + # Create a client + client = discoveryengine_v1alpha.ConversationalSearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ListConversationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_conversations(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.ListConversationsRequest, dict]): + The request object. Request for ListConversations method. + parent (str): + Required. The data store resource name. Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.services.conversational_search_service.pagers.ListConversationsPager: + Response for ListConversations + method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a conversational_search_service.ListConversationsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, conversational_search_service.ListConversationsRequest): + request = conversational_search_service.ListConversationsRequest(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_conversations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListConversationsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "ConversationalSearchServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "ConversationalSearchServiceClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/pagers.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/pagers.py new file mode 100644 index 000000000000..f67122114630 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.discoveryengine_v1alpha.types import conversation +from google.cloud.discoveryengine_v1alpha.types import conversational_search_service + + +class ListConversationsPager: + """A pager for iterating through ``list_conversations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1alpha.types.ListConversationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``conversations`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListConversations`` requests and continue to iterate + through the ``conversations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1alpha.types.ListConversationsResponse` + 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[..., conversational_search_service.ListConversationsResponse], + request: conversational_search_service.ListConversationsRequest, + response: conversational_search_service.ListConversationsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.discoveryengine_v1alpha.types.ListConversationsRequest): + The initial request object. + response (google.cloud.discoveryengine_v1alpha.types.ListConversationsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = conversational_search_service.ListConversationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[conversational_search_service.ListConversationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[conversation.Conversation]: + for page in self.pages: + yield from page.conversations + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListConversationsAsyncPager: + """A pager for iterating through ``list_conversations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1alpha.types.ListConversationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``conversations`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListConversations`` requests and continue to iterate + through the ``conversations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1alpha.types.ListConversationsResponse` + 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[conversational_search_service.ListConversationsResponse]], + request: conversational_search_service.ListConversationsRequest, + response: conversational_search_service.ListConversationsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.discoveryengine_v1alpha.types.ListConversationsRequest): + The initial request object. + response (google.cloud.discoveryengine_v1alpha.types.ListConversationsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = conversational_search_service.ListConversationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[conversational_search_service.ListConversationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[conversation.Conversation]: + async def async_generator(): + async for page in self.pages: + for response in page.conversations: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/__init__.py new file mode 100644 index 000000000000..f49b63e4b6cd --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import ConversationalSearchServiceTransport +from .grpc import ConversationalSearchServiceGrpcTransport +from .grpc_asyncio import ConversationalSearchServiceGrpcAsyncIOTransport +from .rest import ConversationalSearchServiceRestTransport +from .rest import ConversationalSearchServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ConversationalSearchServiceTransport]] +_transport_registry['grpc'] = ConversationalSearchServiceGrpcTransport +_transport_registry['grpc_asyncio'] = ConversationalSearchServiceGrpcAsyncIOTransport +_transport_registry['rest'] = ConversationalSearchServiceRestTransport + +__all__ = ( + 'ConversationalSearchServiceTransport', + 'ConversationalSearchServiceGrpcTransport', + 'ConversationalSearchServiceGrpcAsyncIOTransport', + 'ConversationalSearchServiceRestTransport', + 'ConversationalSearchServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/base.py new file mode 100644 index 000000000000..6de3058bf8e2 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/base.py @@ -0,0 +1,241 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import conversation +from google.cloud.discoveryengine_v1alpha.types import conversation as gcd_conversation +from google.cloud.discoveryengine_v1alpha.types import conversational_search_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class ConversationalSearchServiceTransport(abc.ABC): + """Abstract transport class for ConversationalSearchService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'discoveryengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.converse_conversation: gapic_v1.method.wrap_method( + self.converse_conversation, + default_timeout=None, + client_info=client_info, + ), + self.create_conversation: gapic_v1.method.wrap_method( + self.create_conversation, + default_timeout=None, + client_info=client_info, + ), + self.delete_conversation: gapic_v1.method.wrap_method( + self.delete_conversation, + 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, + client_info=client_info, + ), + self.list_conversations: gapic_v1.method.wrap_method( + self.list_conversations, + 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 converse_conversation(self) -> Callable[ + [conversational_search_service.ConverseConversationRequest], + Union[ + conversational_search_service.ConverseConversationResponse, + Awaitable[conversational_search_service.ConverseConversationResponse] + ]]: + raise NotImplementedError() + + @property + def create_conversation(self) -> Callable[ + [conversational_search_service.CreateConversationRequest], + Union[ + gcd_conversation.Conversation, + Awaitable[gcd_conversation.Conversation] + ]]: + raise NotImplementedError() + + @property + def delete_conversation(self) -> Callable[ + [conversational_search_service.DeleteConversationRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_conversation(self) -> Callable[ + [conversational_search_service.UpdateConversationRequest], + Union[ + gcd_conversation.Conversation, + Awaitable[gcd_conversation.Conversation] + ]]: + raise NotImplementedError() + + @property + def get_conversation(self) -> Callable[ + [conversational_search_service.GetConversationRequest], + Union[ + conversation.Conversation, + Awaitable[conversation.Conversation] + ]]: + raise NotImplementedError() + + @property + def list_conversations(self) -> Callable[ + [conversational_search_service.ListConversationsRequest], + Union[ + conversational_search_service.ListConversationsResponse, + Awaitable[conversational_search_service.ListConversationsResponse] + ]]: + 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 kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ConversationalSearchServiceTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/grpc.py new file mode 100644 index 000000000000..ac7ac7baaceb --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/grpc.py @@ -0,0 +1,449 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import conversation +from google.cloud.discoveryengine_v1alpha.types import conversation as gcd_conversation +from google.cloud.discoveryengine_v1alpha.types import conversational_search_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import ConversationalSearchServiceTransport, DEFAULT_CLIENT_INFO + + +class ConversationalSearchServiceGrpcTransport(ConversationalSearchServiceTransport): + """gRPC backend transport for ConversationalSearchService. + + Service for conversational search. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def converse_conversation(self) -> Callable[ + [conversational_search_service.ConverseConversationRequest], + conversational_search_service.ConverseConversationResponse]: + r"""Return a callable for the converse conversation method over gRPC. + + Converses a conversation. + + Returns: + Callable[[~.ConverseConversationRequest], + ~.ConverseConversationResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'converse_conversation' not in self._stubs: + self._stubs['converse_conversation'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.ConversationalSearchService/ConverseConversation', + request_serializer=conversational_search_service.ConverseConversationRequest.serialize, + response_deserializer=conversational_search_service.ConverseConversationResponse.deserialize, + ) + return self._stubs['converse_conversation'] + + @property + def create_conversation(self) -> Callable[ + [conversational_search_service.CreateConversationRequest], + gcd_conversation.Conversation]: + r"""Return a callable for the create conversation method over gRPC. + + Creates a Conversation. + + If the + [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] + to create already exists, an ALREADY_EXISTS error is returned. + + Returns: + Callable[[~.CreateConversationRequest], + ~.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 'create_conversation' not in self._stubs: + self._stubs['create_conversation'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.ConversationalSearchService/CreateConversation', + request_serializer=conversational_search_service.CreateConversationRequest.serialize, + response_deserializer=gcd_conversation.Conversation.deserialize, + ) + return self._stubs['create_conversation'] + + @property + def delete_conversation(self) -> Callable[ + [conversational_search_service.DeleteConversationRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete conversation method over gRPC. + + Deletes a Conversation. + + If the + [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] + to delete does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.DeleteConversationRequest], + ~.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_conversation' not in self._stubs: + self._stubs['delete_conversation'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.ConversationalSearchService/DeleteConversation', + request_serializer=conversational_search_service.DeleteConversationRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_conversation'] + + @property + def update_conversation(self) -> Callable[ + [conversational_search_service.UpdateConversationRequest], + gcd_conversation.Conversation]: + r"""Return a callable for the update conversation method over gRPC. + + Updates a Conversation. + + [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] + action type cannot be changed. If the + [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] + to update does not exist, a NOT_FOUND error is returned. + + 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.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.ConversationalSearchService/UpdateConversation', + request_serializer=conversational_search_service.UpdateConversationRequest.serialize, + response_deserializer=gcd_conversation.Conversation.deserialize, + ) + return self._stubs['update_conversation'] + + @property + def get_conversation(self) -> Callable[ + [conversational_search_service.GetConversationRequest], + conversation.Conversation]: + r"""Return a callable for the get conversation method over gRPC. + + Gets a Conversation. + + Returns: + Callable[[~.GetConversationRequest], + ~.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 'get_conversation' not in self._stubs: + self._stubs['get_conversation'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.ConversationalSearchService/GetConversation', + request_serializer=conversational_search_service.GetConversationRequest.serialize, + response_deserializer=conversation.Conversation.deserialize, + ) + return self._stubs['get_conversation'] + + @property + def list_conversations(self) -> Callable[ + [conversational_search_service.ListConversationsRequest], + conversational_search_service.ListConversationsResponse]: + r"""Return a callable for the list conversations method over gRPC. + + Lists all Conversations by their parent + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]. + + Returns: + Callable[[~.ListConversationsRequest], + ~.ListConversationsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversations' not in self._stubs: + self._stubs['list_conversations'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.ConversationalSearchService/ListConversations', + request_serializer=conversational_search_service.ListConversationsRequest.serialize, + response_deserializer=conversational_search_service.ListConversationsResponse.deserialize, + ) + return self._stubs['list_conversations'] + + def close(self): + self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ConversationalSearchServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..5e84d9e5019c --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/grpc_asyncio.py @@ -0,0 +1,448 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import conversation +from google.cloud.discoveryengine_v1alpha.types import conversation as gcd_conversation +from google.cloud.discoveryengine_v1alpha.types import conversational_search_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import ConversationalSearchServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import ConversationalSearchServiceGrpcTransport + + +class ConversationalSearchServiceGrpcAsyncIOTransport(ConversationalSearchServiceTransport): + """gRPC AsyncIO backend transport for ConversationalSearchService. + + Service for conversational search. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def converse_conversation(self) -> Callable[ + [conversational_search_service.ConverseConversationRequest], + Awaitable[conversational_search_service.ConverseConversationResponse]]: + r"""Return a callable for the converse conversation method over gRPC. + + Converses a conversation. + + Returns: + Callable[[~.ConverseConversationRequest], + Awaitable[~.ConverseConversationResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'converse_conversation' not in self._stubs: + self._stubs['converse_conversation'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.ConversationalSearchService/ConverseConversation', + request_serializer=conversational_search_service.ConverseConversationRequest.serialize, + response_deserializer=conversational_search_service.ConverseConversationResponse.deserialize, + ) + return self._stubs['converse_conversation'] + + @property + def create_conversation(self) -> Callable[ + [conversational_search_service.CreateConversationRequest], + Awaitable[gcd_conversation.Conversation]]: + r"""Return a callable for the create conversation method over gRPC. + + Creates a Conversation. + + If the + [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] + to create already exists, an ALREADY_EXISTS error is returned. + + Returns: + Callable[[~.CreateConversationRequest], + 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 'create_conversation' not in self._stubs: + self._stubs['create_conversation'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.ConversationalSearchService/CreateConversation', + request_serializer=conversational_search_service.CreateConversationRequest.serialize, + response_deserializer=gcd_conversation.Conversation.deserialize, + ) + return self._stubs['create_conversation'] + + @property + def delete_conversation(self) -> Callable[ + [conversational_search_service.DeleteConversationRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete conversation method over gRPC. + + Deletes a Conversation. + + If the + [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] + to delete does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.DeleteConversationRequest], + 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_conversation' not in self._stubs: + self._stubs['delete_conversation'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.ConversationalSearchService/DeleteConversation', + request_serializer=conversational_search_service.DeleteConversationRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_conversation'] + + @property + def update_conversation(self) -> Callable[ + [conversational_search_service.UpdateConversationRequest], + Awaitable[gcd_conversation.Conversation]]: + r"""Return a callable for the update conversation method over gRPC. + + Updates a Conversation. + + [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] + action type cannot be changed. If the + [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] + to update does not exist, a NOT_FOUND error is returned. + + 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.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.ConversationalSearchService/UpdateConversation', + request_serializer=conversational_search_service.UpdateConversationRequest.serialize, + response_deserializer=gcd_conversation.Conversation.deserialize, + ) + return self._stubs['update_conversation'] + + @property + def get_conversation(self) -> Callable[ + [conversational_search_service.GetConversationRequest], + Awaitable[conversation.Conversation]]: + r"""Return a callable for the get conversation method over gRPC. + + Gets a Conversation. + + Returns: + Callable[[~.GetConversationRequest], + 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 'get_conversation' not in self._stubs: + self._stubs['get_conversation'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.ConversationalSearchService/GetConversation', + request_serializer=conversational_search_service.GetConversationRequest.serialize, + response_deserializer=conversation.Conversation.deserialize, + ) + return self._stubs['get_conversation'] + + @property + def list_conversations(self) -> Callable[ + [conversational_search_service.ListConversationsRequest], + Awaitable[conversational_search_service.ListConversationsResponse]]: + r"""Return a callable for the list conversations method over gRPC. + + Lists all Conversations by their parent + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]. + + Returns: + Callable[[~.ListConversationsRequest], + Awaitable[~.ListConversationsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversations' not in self._stubs: + self._stubs['list_conversations'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.ConversationalSearchService/ListConversations', + request_serializer=conversational_search_service.ListConversationsRequest.serialize, + response_deserializer=conversational_search_service.ListConversationsResponse.deserialize, + ) + return self._stubs['list_conversations'] + + def close(self): + return self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ( + 'ConversationalSearchServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/rest.py new file mode 100644 index 000000000000..5aae353bd084 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/rest.py @@ -0,0 +1,1156 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.cloud.location import locations_pb2 # type: ignore +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.discoveryengine_v1alpha.types import conversation +from google.cloud.discoveryengine_v1alpha.types import conversation as gcd_conversation +from google.cloud.discoveryengine_v1alpha.types import conversational_search_service +from google.protobuf import empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from .base import ConversationalSearchServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class ConversationalSearchServiceRestInterceptor: + """Interceptor for ConversationalSearchService. + + 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 ConversationalSearchServiceRestTransport. + + .. code-block:: python + class MyCustomConversationalSearchServiceInterceptor(ConversationalSearchServiceRestInterceptor): + def pre_converse_conversation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_converse_conversation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_conversation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_conversation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_conversation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_conversation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_conversation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_conversations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_conversations(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 = ConversationalSearchServiceRestTransport(interceptor=MyCustomConversationalSearchServiceInterceptor()) + client = ConversationalSearchServiceClient(transport=transport) + + + """ + def pre_converse_conversation(self, request: conversational_search_service.ConverseConversationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversational_search_service.ConverseConversationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for converse_conversation + + Override in a subclass to manipulate the request or metadata + before they are sent to the ConversationalSearchService server. + """ + return request, metadata + + def post_converse_conversation(self, response: conversational_search_service.ConverseConversationResponse) -> conversational_search_service.ConverseConversationResponse: + """Post-rpc interceptor for converse_conversation + + Override in a subclass to manipulate the response + after it is returned by the ConversationalSearchService server but before + it is returned to user code. + """ + return response + def pre_create_conversation(self, request: conversational_search_service.CreateConversationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversational_search_service.CreateConversationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_conversation + + Override in a subclass to manipulate the request or metadata + before they are sent to the ConversationalSearchService server. + """ + return request, metadata + + def post_create_conversation(self, response: gcd_conversation.Conversation) -> gcd_conversation.Conversation: + """Post-rpc interceptor for create_conversation + + Override in a subclass to manipulate the response + after it is returned by the ConversationalSearchService server but before + it is returned to user code. + """ + return response + def pre_delete_conversation(self, request: conversational_search_service.DeleteConversationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversational_search_service.DeleteConversationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_conversation + + Override in a subclass to manipulate the request or metadata + before they are sent to the ConversationalSearchService server. + """ + return request, metadata + + def pre_get_conversation(self, request: conversational_search_service.GetConversationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversational_search_service.GetConversationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_conversation + + Override in a subclass to manipulate the request or metadata + before they are sent to the ConversationalSearchService server. + """ + return request, metadata + + def post_get_conversation(self, response: conversation.Conversation) -> conversation.Conversation: + """Post-rpc interceptor for get_conversation + + Override in a subclass to manipulate the response + after it is returned by the ConversationalSearchService server but before + it is returned to user code. + """ + return response + def pre_list_conversations(self, request: conversational_search_service.ListConversationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversational_search_service.ListConversationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_conversations + + Override in a subclass to manipulate the request or metadata + before they are sent to the ConversationalSearchService server. + """ + return request, metadata + + def post_list_conversations(self, response: conversational_search_service.ListConversationsResponse) -> conversational_search_service.ListConversationsResponse: + """Post-rpc interceptor for list_conversations + + Override in a subclass to manipulate the response + after it is returned by the ConversationalSearchService server but before + it is returned to user code. + """ + return response + def pre_update_conversation(self, request: conversational_search_service.UpdateConversationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversational_search_service.UpdateConversationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_conversation + + Override in a subclass to manipulate the request or metadata + before they are sent to the ConversationalSearchService server. + """ + return request, metadata + + def post_update_conversation(self, response: gcd_conversation.Conversation) -> gcd_conversation.Conversation: + """Post-rpc interceptor for update_conversation + + Override in a subclass to manipulate the response + after it is returned by the ConversationalSearchService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the ConversationalSearchService 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 ConversationalSearchService server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the ConversationalSearchService 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 ConversationalSearchService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class ConversationalSearchServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ConversationalSearchServiceRestInterceptor + + +class ConversationalSearchServiceRestTransport(ConversationalSearchServiceTransport): + """REST backend transport for ConversationalSearchService. + + Service for conversational search. + + 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 = 'discoveryengine.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[ConversationalSearchServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or ConversationalSearchServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _ConverseConversation(ConversationalSearchServiceRestStub): + def __hash__(self): + return hash("ConverseConversation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: conversational_search_service.ConverseConversationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> conversational_search_service.ConverseConversationResponse: + r"""Call the converse conversation method over HTTP. + + Args: + request (~.conversational_search_service.ConverseConversationRequest): + The request object. Request message for + [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1alpha.ConversationalSearchService.ConverseConversation] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.conversational_search_service.ConverseConversationResponse: + Response message for + [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1alpha.ConversationalSearchService.ConverseConversation] + method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/conversations/*}:converse', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/conversations/*}:converse', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_converse_conversation(request, metadata) + pb_request = conversational_search_service.ConverseConversationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = conversational_search_service.ConverseConversationResponse() + pb_resp = conversational_search_service.ConverseConversationResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_converse_conversation(resp) + return resp + + class _CreateConversation(ConversationalSearchServiceRestStub): + def __hash__(self): + return hash("CreateConversation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: conversational_search_service.CreateConversationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcd_conversation.Conversation: + r"""Call the create conversation method over HTTP. + + Args: + request (~.conversational_search_service.CreateConversationRequest): + The request object. Request for CreateConversation + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcd_conversation.Conversation: + External conversation proto + definition. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=projects/*/locations/*/dataStores/*}/conversations', + 'body': 'conversation', + }, +{ + 'method': 'post', + 'uri': '/v1alpha/{parent=projects/*/locations/*/collections/*/dataStores/*}/conversations', + 'body': 'conversation', + }, + ] + request, metadata = self._interceptor.pre_create_conversation(request, metadata) + pb_request = conversational_search_service.CreateConversationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcd_conversation.Conversation() + pb_resp = gcd_conversation.Conversation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_conversation(resp) + return resp + + class _DeleteConversation(ConversationalSearchServiceRestStub): + def __hash__(self): + return hash("DeleteConversation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: conversational_search_service.DeleteConversationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete conversation method over HTTP. + + Args: + request (~.conversational_search_service.DeleteConversationRequest): + The request object. Request for DeleteConversation + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/conversations/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/conversations/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_conversation(request, metadata) + pb_request = conversational_search_service.DeleteConversationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _GetConversation(ConversationalSearchServiceRestStub): + def __hash__(self): + return hash("GetConversation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: conversational_search_service.GetConversationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> conversation.Conversation: + r"""Call the get conversation method over HTTP. + + Args: + request (~.conversational_search_service.GetConversationRequest): + The request object. Request for GetConversation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.conversation.Conversation: + External conversation proto + definition. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/conversations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/conversations/*}', + }, + ] + request, metadata = self._interceptor.pre_get_conversation(request, metadata) + pb_request = conversational_search_service.GetConversationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = conversation.Conversation() + pb_resp = conversation.Conversation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_conversation(resp) + return resp + + class _ListConversations(ConversationalSearchServiceRestStub): + def __hash__(self): + return hash("ListConversations") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: conversational_search_service.ListConversationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> conversational_search_service.ListConversationsResponse: + r"""Call the list conversations method over HTTP. + + Args: + request (~.conversational_search_service.ListConversationsRequest): + The request object. Request for ListConversations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.conversational_search_service.ListConversationsResponse: + Response for ListConversations + method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=projects/*/locations/*/dataStores/*}/conversations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{parent=projects/*/locations/*/collections/*/dataStores/*}/conversations', + }, + ] + request, metadata = self._interceptor.pre_list_conversations(request, metadata) + pb_request = conversational_search_service.ListConversationsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = conversational_search_service.ListConversationsResponse() + pb_resp = conversational_search_service.ListConversationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_conversations(resp) + return resp + + class _UpdateConversation(ConversationalSearchServiceRestStub): + def __hash__(self): + return hash("UpdateConversation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: conversational_search_service.UpdateConversationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcd_conversation.Conversation: + r"""Call the update conversation method over HTTP. + + Args: + request (~.conversational_search_service.UpdateConversationRequest): + The request object. Request for UpdateConversation + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcd_conversation.Conversation: + External conversation proto + definition. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha/{conversation.name=projects/*/locations/*/dataStores/*/conversations/*}', + 'body': 'conversation', + }, +{ + 'method': 'patch', + 'uri': '/v1alpha/{conversation.name=projects/*/locations/*/collections/*/dataStores/*/conversations/*}', + 'body': 'conversation', + }, + ] + request, metadata = self._interceptor.pre_update_conversation(request, metadata) + pb_request = conversational_search_service.UpdateConversationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcd_conversation.Conversation() + pb_resp = gcd_conversation.Conversation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_conversation(resp) + return resp + + @property + def converse_conversation(self) -> Callable[ + [conversational_search_service.ConverseConversationRequest], + conversational_search_service.ConverseConversationResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ConverseConversation(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_conversation(self) -> Callable[ + [conversational_search_service.CreateConversationRequest], + gcd_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._CreateConversation(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_conversation(self) -> Callable[ + [conversational_search_service.DeleteConversationRequest], + 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._DeleteConversation(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_conversation(self) -> Callable[ + [conversational_search_service.GetConversationRequest], + 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._GetConversation(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_conversations(self) -> Callable[ + [conversational_search_service.ListConversationsRequest], + conversational_search_service.ListConversationsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListConversations(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_conversation(self) -> Callable[ + [conversational_search_service.UpdateConversationRequest], + gcd_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_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(ConversationalSearchServiceRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(ConversationalSearchServiceRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'ConversationalSearchServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/__init__.py new file mode 100644 index 000000000000..0411e2029431 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import DataStoreServiceClient +from .async_client import DataStoreServiceAsyncClient + +__all__ = ( + 'DataStoreServiceClient', + 'DataStoreServiceAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/async_client.py new file mode 100644 index 000000000000..6bc8835ec9a9 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/async_client.py @@ -0,0 +1,977 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.discoveryengine_v1alpha.services.data_store_service import pagers +from google.cloud.discoveryengine_v1alpha.types import common +from google.cloud.discoveryengine_v1alpha.types import data_store +from google.cloud.discoveryengine_v1alpha.types import data_store as gcd_data_store +from google.cloud.discoveryengine_v1alpha.types import data_store_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import DataStoreServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import DataStoreServiceGrpcAsyncIOTransport +from .client import DataStoreServiceClient + + +class DataStoreServiceAsyncClient: + """Service for managing + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore] + configuration. + """ + + _client: DataStoreServiceClient + + DEFAULT_ENDPOINT = DataStoreServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = DataStoreServiceClient.DEFAULT_MTLS_ENDPOINT + + collection_path = staticmethod(DataStoreServiceClient.collection_path) + parse_collection_path = staticmethod(DataStoreServiceClient.parse_collection_path) + data_store_path = staticmethod(DataStoreServiceClient.data_store_path) + parse_data_store_path = staticmethod(DataStoreServiceClient.parse_data_store_path) + common_billing_account_path = staticmethod(DataStoreServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(DataStoreServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(DataStoreServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(DataStoreServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(DataStoreServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(DataStoreServiceClient.parse_common_organization_path) + common_project_path = staticmethod(DataStoreServiceClient.common_project_path) + parse_common_project_path = staticmethod(DataStoreServiceClient.parse_common_project_path) + common_location_path = staticmethod(DataStoreServiceClient.common_location_path) + parse_common_location_path = staticmethod(DataStoreServiceClient.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: + DataStoreServiceAsyncClient: The constructed client. + """ + return DataStoreServiceClient.from_service_account_info.__func__(DataStoreServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DataStoreServiceAsyncClient: The constructed client. + """ + return DataStoreServiceClient.from_service_account_file.__func__(DataStoreServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return DataStoreServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> DataStoreServiceTransport: + """Returns the transport used by the client instance. + + Returns: + DataStoreServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(DataStoreServiceClient).get_transport_class, type(DataStoreServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, DataStoreServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the data store 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 (Union[str, ~.DataStoreServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = DataStoreServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_data_store(self, + request: Optional[Union[data_store_service.CreateDataStoreRequest, dict]] = None, + *, + parent: Optional[str] = None, + data_store: Optional[gcd_data_store.DataStore] = None, + data_store_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]. + + DataStore is for storing + [Documents][google.cloud.discoveryengine.v1alpha.Document]. To + serve these documents for Search, or Recommendation use case, an + [Engine][google.cloud.discoveryengine.v1alpha.Engine] needs to + be created separately. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_create_data_store(): + # Create a client + client = discoveryengine_v1alpha.DataStoreServiceAsyncClient() + + # Initialize request argument(s) + data_store = discoveryengine_v1alpha.DataStore() + data_store.display_name = "display_name_value" + + request = discoveryengine_v1alpha.CreateDataStoreRequest( + parent="parent_value", + data_store=data_store, + data_store_id="data_store_id_value", + ) + + # Make the request + operation = client.create_data_store(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.CreateDataStoreRequest, dict]]): + The request object. Request for + [DataStoreService.CreateDataStore][google.cloud.discoveryengine.v1alpha.DataStoreService.CreateDataStore] + method. + parent (:class:`str`): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data_store (:class:`google.cloud.discoveryengine_v1alpha.types.DataStore`): + Required. The + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore] + to create. + + This corresponds to the ``data_store`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data_store_id (:class:`str`): + Required. The ID to use for the + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore], + which will become the final component of the + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]'s + resource name. + + This field must conform to + `RFC-1034 `__ + standard with a length limit of 63 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + This corresponds to the ``data_store_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.discoveryengine_v1alpha.types.DataStore` + DataStore captures global settings and configs at the + DataStore level. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, data_store, data_store_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = data_store_service.CreateDataStoreRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if data_store is not None: + request.data_store = data_store + if data_store_id is not None: + request.data_store_id = data_store_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_data_store, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcd_data_store.DataStore, + metadata_type=data_store_service.CreateDataStoreMetadata, + ) + + # Done; return the response. + return response + + async def get_data_store(self, + request: Optional[Union[data_store_service.GetDataStoreRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> data_store.DataStore: + r"""Gets a + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_get_data_store(): + # Create a client + client = discoveryengine_v1alpha.DataStoreServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.GetDataStoreRequest( + name="name_value", + ) + + # Make the request + response = await client.get_data_store(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.GetDataStoreRequest, dict]]): + The request object. Request message for + [DataStoreService.GetDataStore][google.cloud.discoveryengine.v1alpha.DataStoreService.GetDataStore] + method. + name (:class:`str`): + Required. Full resource name of + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore], + such as + ``projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}``. + + If the caller does not have permission to access the + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the requested + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore] + does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.DataStore: + DataStore captures global settings + and configs at the DataStore level. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = data_store_service.GetDataStoreRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_data_store, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_data_stores(self, + request: Optional[Union[data_store_service.ListDataStoresRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDataStoresAsyncPager: + r"""Lists all the + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]s + associated with the project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_list_data_stores(): + # Create a client + client = discoveryengine_v1alpha.DataStoreServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ListDataStoresRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_data_stores(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.ListDataStoresRequest, dict]]): + The request object. Request message for + [DataStoreService.ListDataStores][google.cloud.discoveryengine.v1alpha.DataStoreService.ListDataStores] + method. + parent (:class:`str`): + Required. The parent branch resource name, such as + ``projects/{project}/locations/{location}/collections/{collection_id}``. + + If the caller does not have permission to list + [DataStores][]s under this location, regardless of + whether or not this data store exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.services.data_store_service.pagers.ListDataStoresAsyncPager: + Response message for + [DataStoreService.ListDataStores][google.cloud.discoveryengine.v1alpha.DataStoreService.ListDataStores] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = data_store_service.ListDataStoresRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_data_stores, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListDataStoresAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_data_store(self, + request: Optional[Union[data_store_service.DeleteDataStoreRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_delete_data_store(): + # Create a client + client = discoveryengine_v1alpha.DataStoreServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.DeleteDataStoreRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_data_store(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.DeleteDataStoreRequest, dict]]): + The request object. Request message for + [DataStoreService.DeleteDataStore][google.cloud.discoveryengine.v1alpha.DataStoreService.DeleteDataStore] + method. + name (:class:`str`): + Required. Full resource name of + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore], + such as + ``projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}``. + + If the caller does not have permission to delete the + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore] + to delete does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = data_store_service.DeleteDataStoreRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_data_store, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=data_store_service.DeleteDataStoreMetadata, + ) + + # Done; return the response. + return response + + async def update_data_store(self, + request: Optional[Union[data_store_service.UpdateDataStoreRequest, dict]] = None, + *, + data_store: Optional[gcd_data_store.DataStore] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_data_store.DataStore: + r"""Updates a + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore] + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_update_data_store(): + # Create a client + client = discoveryengine_v1alpha.DataStoreServiceAsyncClient() + + # Initialize request argument(s) + data_store = discoveryengine_v1alpha.DataStore() + data_store.display_name = "display_name_value" + + request = discoveryengine_v1alpha.UpdateDataStoreRequest( + data_store=data_store, + ) + + # Make the request + response = await client.update_data_store(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.UpdateDataStoreRequest, dict]]): + The request object. Request message for + [DataStoreService.UpdateDataStore][google.cloud.discoveryengine.v1alpha.DataStoreService.UpdateDataStore] + method. + data_store (:class:`google.cloud.discoveryengine_v1alpha.types.DataStore`): + Required. The + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore] + to update. + + If the caller does not have permission to update the + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore] + to update does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``data_store`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Indicates which fields in the provided + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore] + to update. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.DataStore: + DataStore captures global settings + and configs at the DataStore level. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([data_store, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = data_store_service.UpdateDataStoreRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if data_store is not None: + request.data_store = data_store + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_data_store, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("data_store.name", request.data_store.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "DataStoreServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "DataStoreServiceAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/client.py new file mode 100644 index 000000000000..f400ac0a667d --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/client.py @@ -0,0 +1,1193 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.discoveryengine_v1alpha.services.data_store_service import pagers +from google.cloud.discoveryengine_v1alpha.types import common +from google.cloud.discoveryengine_v1alpha.types import data_store +from google.cloud.discoveryengine_v1alpha.types import data_store as gcd_data_store +from google.cloud.discoveryengine_v1alpha.types import data_store_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import DataStoreServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import DataStoreServiceGrpcTransport +from .transports.grpc_asyncio import DataStoreServiceGrpcAsyncIOTransport +from .transports.rest import DataStoreServiceRestTransport + + +class DataStoreServiceClientMeta(type): + """Metaclass for the DataStoreService 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[DataStoreServiceTransport]] + _transport_registry["grpc"] = DataStoreServiceGrpcTransport + _transport_registry["grpc_asyncio"] = DataStoreServiceGrpcAsyncIOTransport + _transport_registry["rest"] = DataStoreServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[DataStoreServiceTransport]: + """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 DataStoreServiceClient(metaclass=DataStoreServiceClientMeta): + """Service for managing + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore] + configuration. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DataStoreServiceClient: 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: + DataStoreServiceClient: 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) -> DataStoreServiceTransport: + """Returns the transport used by the client instance. + + Returns: + DataStoreServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def collection_path(project: str,location: str,collection: str,) -> str: + """Returns a fully-qualified collection string.""" + return "projects/{project}/locations/{location}/collections/{collection}".format(project=project, location=location, collection=collection, ) + + @staticmethod + def parse_collection_path(path: str) -> Dict[str,str]: + """Parses a collection path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/collections/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def data_store_path(project: str,location: str,data_store: str,) -> str: + """Returns a fully-qualified data_store string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) + + @staticmethod + def parse_data_store_path(path: str) -> Dict[str,str]: + """Parses a data_store path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, DataStoreServiceTransport]] = 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 store 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 (Union[str, DataStoreServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, DataStoreServiceTransport): + # transport is a DataStoreServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def create_data_store(self, + request: Optional[Union[data_store_service.CreateDataStoreRequest, dict]] = None, + *, + parent: Optional[str] = None, + data_store: Optional[gcd_data_store.DataStore] = None, + data_store_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]. + + DataStore is for storing + [Documents][google.cloud.discoveryengine.v1alpha.Document]. To + serve these documents for Search, or Recommendation use case, an + [Engine][google.cloud.discoveryengine.v1alpha.Engine] needs to + be created separately. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_create_data_store(): + # Create a client + client = discoveryengine_v1alpha.DataStoreServiceClient() + + # Initialize request argument(s) + data_store = discoveryengine_v1alpha.DataStore() + data_store.display_name = "display_name_value" + + request = discoveryengine_v1alpha.CreateDataStoreRequest( + parent="parent_value", + data_store=data_store, + data_store_id="data_store_id_value", + ) + + # Make the request + operation = client.create_data_store(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.CreateDataStoreRequest, dict]): + The request object. Request for + [DataStoreService.CreateDataStore][google.cloud.discoveryengine.v1alpha.DataStoreService.CreateDataStore] + method. + parent (str): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data_store (google.cloud.discoveryengine_v1alpha.types.DataStore): + Required. The + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore] + to create. + + This corresponds to the ``data_store`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data_store_id (str): + Required. The ID to use for the + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore], + which will become the final component of the + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]'s + resource name. + + This field must conform to + `RFC-1034 `__ + standard with a length limit of 63 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + This corresponds to the ``data_store_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.discoveryengine_v1alpha.types.DataStore` + DataStore captures global settings and configs at the + DataStore level. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, data_store, data_store_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a data_store_service.CreateDataStoreRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_store_service.CreateDataStoreRequest): + request = data_store_service.CreateDataStoreRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if data_store is not None: + request.data_store = data_store + if data_store_id is not None: + request.data_store_id = data_store_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_data_store] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gcd_data_store.DataStore, + metadata_type=data_store_service.CreateDataStoreMetadata, + ) + + # Done; return the response. + return response + + def get_data_store(self, + request: Optional[Union[data_store_service.GetDataStoreRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> data_store.DataStore: + r"""Gets a + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_get_data_store(): + # Create a client + client = discoveryengine_v1alpha.DataStoreServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.GetDataStoreRequest( + name="name_value", + ) + + # Make the request + response = client.get_data_store(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.GetDataStoreRequest, dict]): + The request object. Request message for + [DataStoreService.GetDataStore][google.cloud.discoveryengine.v1alpha.DataStoreService.GetDataStore] + method. + name (str): + Required. Full resource name of + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore], + such as + ``projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}``. + + If the caller does not have permission to access the + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the requested + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore] + does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.DataStore: + DataStore captures global settings + and configs at the DataStore level. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a data_store_service.GetDataStoreRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_store_service.GetDataStoreRequest): + request = data_store_service.GetDataStoreRequest(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_data_store] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_data_stores(self, + request: Optional[Union[data_store_service.ListDataStoresRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDataStoresPager: + r"""Lists all the + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]s + associated with the project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_list_data_stores(): + # Create a client + client = discoveryengine_v1alpha.DataStoreServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ListDataStoresRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_data_stores(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.ListDataStoresRequest, dict]): + The request object. Request message for + [DataStoreService.ListDataStores][google.cloud.discoveryengine.v1alpha.DataStoreService.ListDataStores] + method. + parent (str): + Required. The parent branch resource name, such as + ``projects/{project}/locations/{location}/collections/{collection_id}``. + + If the caller does not have permission to list + [DataStores][]s under this location, regardless of + whether or not this data store exists, a + PERMISSION_DENIED error is returned. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.services.data_store_service.pagers.ListDataStoresPager: + Response message for + [DataStoreService.ListDataStores][google.cloud.discoveryengine.v1alpha.DataStoreService.ListDataStores] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a data_store_service.ListDataStoresRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_store_service.ListDataStoresRequest): + request = data_store_service.ListDataStoresRequest(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_data_stores] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListDataStoresPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_data_store(self, + request: Optional[Union[data_store_service.DeleteDataStoreRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_delete_data_store(): + # Create a client + client = discoveryengine_v1alpha.DataStoreServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.DeleteDataStoreRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_data_store(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.DeleteDataStoreRequest, dict]): + The request object. Request message for + [DataStoreService.DeleteDataStore][google.cloud.discoveryengine.v1alpha.DataStoreService.DeleteDataStore] + method. + name (str): + Required. Full resource name of + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore], + such as + ``projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}``. + + If the caller does not have permission to delete the + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore] + to delete does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a data_store_service.DeleteDataStoreRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_store_service.DeleteDataStoreRequest): + request = data_store_service.DeleteDataStoreRequest(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_data_store] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=data_store_service.DeleteDataStoreMetadata, + ) + + # Done; return the response. + return response + + def update_data_store(self, + request: Optional[Union[data_store_service.UpdateDataStoreRequest, dict]] = None, + *, + data_store: Optional[gcd_data_store.DataStore] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_data_store.DataStore: + r"""Updates a + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore] + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_update_data_store(): + # Create a client + client = discoveryengine_v1alpha.DataStoreServiceClient() + + # Initialize request argument(s) + data_store = discoveryengine_v1alpha.DataStore() + data_store.display_name = "display_name_value" + + request = discoveryengine_v1alpha.UpdateDataStoreRequest( + data_store=data_store, + ) + + # Make the request + response = client.update_data_store(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.UpdateDataStoreRequest, dict]): + The request object. Request message for + [DataStoreService.UpdateDataStore][google.cloud.discoveryengine.v1alpha.DataStoreService.UpdateDataStore] + method. + data_store (google.cloud.discoveryengine_v1alpha.types.DataStore): + Required. The + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore] + to update. + + If the caller does not have permission to update the + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore] + to update does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``data_store`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore] + to update. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.DataStore: + DataStore captures global settings + and configs at the DataStore level. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([data_store, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a data_store_service.UpdateDataStoreRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, data_store_service.UpdateDataStoreRequest): + request = data_store_service.UpdateDataStoreRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if data_store is not None: + request.data_store = data_store + 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_data_store] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("data_store.name", request.data_store.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "DataStoreServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "DataStoreServiceClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/pagers.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/pagers.py new file mode 100644 index 000000000000..e13cd9efb8de --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.discoveryengine_v1alpha.types import data_store +from google.cloud.discoveryengine_v1alpha.types import data_store_service + + +class ListDataStoresPager: + """A pager for iterating through ``list_data_stores`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1alpha.types.ListDataStoresResponse` object, and + provides an ``__iter__`` method to iterate through its + ``data_stores`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDataStores`` requests and continue to iterate + through the ``data_stores`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1alpha.types.ListDataStoresResponse` + 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[..., data_store_service.ListDataStoresResponse], + request: data_store_service.ListDataStoresRequest, + response: data_store_service.ListDataStoresResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.discoveryengine_v1alpha.types.ListDataStoresRequest): + The initial request object. + response (google.cloud.discoveryengine_v1alpha.types.ListDataStoresResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = data_store_service.ListDataStoresRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[data_store_service.ListDataStoresResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[data_store.DataStore]: + for page in self.pages: + yield from page.data_stores + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDataStoresAsyncPager: + """A pager for iterating through ``list_data_stores`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1alpha.types.ListDataStoresResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``data_stores`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDataStores`` requests and continue to iterate + through the ``data_stores`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1alpha.types.ListDataStoresResponse` + 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[data_store_service.ListDataStoresResponse]], + request: data_store_service.ListDataStoresRequest, + response: data_store_service.ListDataStoresResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.discoveryengine_v1alpha.types.ListDataStoresRequest): + The initial request object. + response (google.cloud.discoveryengine_v1alpha.types.ListDataStoresResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = data_store_service.ListDataStoresRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[data_store_service.ListDataStoresResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[data_store.DataStore]: + async def async_generator(): + async for page in self.pages: + for response in page.data_stores: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/__init__.py new file mode 100644 index 000000000000..3bb6e679b823 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import DataStoreServiceTransport +from .grpc import DataStoreServiceGrpcTransport +from .grpc_asyncio import DataStoreServiceGrpcAsyncIOTransport +from .rest import DataStoreServiceRestTransport +from .rest import DataStoreServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[DataStoreServiceTransport]] +_transport_registry['grpc'] = DataStoreServiceGrpcTransport +_transport_registry['grpc_asyncio'] = DataStoreServiceGrpcAsyncIOTransport +_transport_registry['rest'] = DataStoreServiceRestTransport + +__all__ = ( + 'DataStoreServiceTransport', + 'DataStoreServiceGrpcTransport', + 'DataStoreServiceGrpcAsyncIOTransport', + 'DataStoreServiceRestTransport', + 'DataStoreServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/base.py new file mode 100644 index 000000000000..2b728dcc7339 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/base.py @@ -0,0 +1,232 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import data_store +from google.cloud.discoveryengine_v1alpha.types import data_store as gcd_data_store +from google.cloud.discoveryengine_v1alpha.types import data_store_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class DataStoreServiceTransport(abc.ABC): + """Abstract transport class for DataStoreService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'discoveryengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_data_store: gapic_v1.method.wrap_method( + self.create_data_store, + default_timeout=None, + client_info=client_info, + ), + self.get_data_store: gapic_v1.method.wrap_method( + self.get_data_store, + default_timeout=None, + client_info=client_info, + ), + self.list_data_stores: gapic_v1.method.wrap_method( + self.list_data_stores, + default_timeout=None, + client_info=client_info, + ), + self.delete_data_store: gapic_v1.method.wrap_method( + self.delete_data_store, + default_timeout=None, + client_info=client_info, + ), + self.update_data_store: gapic_v1.method.wrap_method( + self.update_data_store, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_data_store(self) -> Callable[ + [data_store_service.CreateDataStoreRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_data_store(self) -> Callable[ + [data_store_service.GetDataStoreRequest], + Union[ + data_store.DataStore, + Awaitable[data_store.DataStore] + ]]: + raise NotImplementedError() + + @property + def list_data_stores(self) -> Callable[ + [data_store_service.ListDataStoresRequest], + Union[ + data_store_service.ListDataStoresResponse, + Awaitable[data_store_service.ListDataStoresResponse] + ]]: + raise NotImplementedError() + + @property + def delete_data_store(self) -> Callable[ + [data_store_service.DeleteDataStoreRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_data_store(self) -> Callable[ + [data_store_service.UpdateDataStoreRequest], + Union[ + gcd_data_store.DataStore, + Awaitable[gcd_data_store.DataStore] + ]]: + 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 kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'DataStoreServiceTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/grpc.py new file mode 100644 index 000000000000..1c382863e8e6 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/grpc.py @@ -0,0 +1,440 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import data_store +from google.cloud.discoveryengine_v1alpha.types import data_store as gcd_data_store +from google.cloud.discoveryengine_v1alpha.types import data_store_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import DataStoreServiceTransport, DEFAULT_CLIENT_INFO + + +class DataStoreServiceGrpcTransport(DataStoreServiceTransport): + """gRPC backend transport for DataStoreService. + + Service for managing + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore] + configuration. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_data_store(self) -> Callable[ + [data_store_service.CreateDataStoreRequest], + operations_pb2.Operation]: + r"""Return a callable for the create data store method over gRPC. + + Creates a + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]. + + DataStore is for storing + [Documents][google.cloud.discoveryengine.v1alpha.Document]. To + serve these documents for Search, or Recommendation use case, an + [Engine][google.cloud.discoveryengine.v1alpha.Engine] needs to + be created separately. + + Returns: + Callable[[~.CreateDataStoreRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_store' not in self._stubs: + self._stubs['create_data_store'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.DataStoreService/CreateDataStore', + request_serializer=data_store_service.CreateDataStoreRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_data_store'] + + @property + def get_data_store(self) -> Callable[ + [data_store_service.GetDataStoreRequest], + data_store.DataStore]: + r"""Return a callable for the get data store method over gRPC. + + Gets a + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]. + + Returns: + Callable[[~.GetDataStoreRequest], + ~.DataStore]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_store' not in self._stubs: + self._stubs['get_data_store'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.DataStoreService/GetDataStore', + request_serializer=data_store_service.GetDataStoreRequest.serialize, + response_deserializer=data_store.DataStore.deserialize, + ) + return self._stubs['get_data_store'] + + @property + def list_data_stores(self) -> Callable[ + [data_store_service.ListDataStoresRequest], + data_store_service.ListDataStoresResponse]: + r"""Return a callable for the list data stores method over gRPC. + + Lists all the + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]s + associated with the project. + + Returns: + Callable[[~.ListDataStoresRequest], + ~.ListDataStoresResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_stores' not in self._stubs: + self._stubs['list_data_stores'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.DataStoreService/ListDataStores', + request_serializer=data_store_service.ListDataStoresRequest.serialize, + response_deserializer=data_store_service.ListDataStoresResponse.deserialize, + ) + return self._stubs['list_data_stores'] + + @property + def delete_data_store(self) -> Callable[ + [data_store_service.DeleteDataStoreRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete data store method over gRPC. + + Deletes a + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]. + + Returns: + Callable[[~.DeleteDataStoreRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_store' not in self._stubs: + self._stubs['delete_data_store'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.DataStoreService/DeleteDataStore', + request_serializer=data_store_service.DeleteDataStoreRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_data_store'] + + @property + def update_data_store(self) -> Callable[ + [data_store_service.UpdateDataStoreRequest], + gcd_data_store.DataStore]: + r"""Return a callable for the update data store method over gRPC. + + Updates a + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore] + + Returns: + Callable[[~.UpdateDataStoreRequest], + ~.DataStore]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_store' not in self._stubs: + self._stubs['update_data_store'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.DataStoreService/UpdateDataStore', + request_serializer=data_store_service.UpdateDataStoreRequest.serialize, + response_deserializer=gcd_data_store.DataStore.deserialize, + ) + return self._stubs['update_data_store'] + + def close(self): + self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'DataStoreServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..ae6065d7eb54 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/grpc_asyncio.py @@ -0,0 +1,439 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import data_store +from google.cloud.discoveryengine_v1alpha.types import data_store as gcd_data_store +from google.cloud.discoveryengine_v1alpha.types import data_store_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import DataStoreServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import DataStoreServiceGrpcTransport + + +class DataStoreServiceGrpcAsyncIOTransport(DataStoreServiceTransport): + """gRPC AsyncIO backend transport for DataStoreService. + + Service for managing + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore] + configuration. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_data_store(self) -> Callable[ + [data_store_service.CreateDataStoreRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create data store method over gRPC. + + Creates a + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]. + + DataStore is for storing + [Documents][google.cloud.discoveryengine.v1alpha.Document]. To + serve these documents for Search, or Recommendation use case, an + [Engine][google.cloud.discoveryengine.v1alpha.Engine] needs to + be created separately. + + Returns: + Callable[[~.CreateDataStoreRequest], + 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_data_store' not in self._stubs: + self._stubs['create_data_store'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.DataStoreService/CreateDataStore', + request_serializer=data_store_service.CreateDataStoreRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_data_store'] + + @property + def get_data_store(self) -> Callable[ + [data_store_service.GetDataStoreRequest], + Awaitable[data_store.DataStore]]: + r"""Return a callable for the get data store method over gRPC. + + Gets a + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]. + + Returns: + Callable[[~.GetDataStoreRequest], + Awaitable[~.DataStore]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_store' not in self._stubs: + self._stubs['get_data_store'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.DataStoreService/GetDataStore', + request_serializer=data_store_service.GetDataStoreRequest.serialize, + response_deserializer=data_store.DataStore.deserialize, + ) + return self._stubs['get_data_store'] + + @property + def list_data_stores(self) -> Callable[ + [data_store_service.ListDataStoresRequest], + Awaitable[data_store_service.ListDataStoresResponse]]: + r"""Return a callable for the list data stores method over gRPC. + + Lists all the + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]s + associated with the project. + + Returns: + Callable[[~.ListDataStoresRequest], + Awaitable[~.ListDataStoresResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_stores' not in self._stubs: + self._stubs['list_data_stores'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.DataStoreService/ListDataStores', + request_serializer=data_store_service.ListDataStoresRequest.serialize, + response_deserializer=data_store_service.ListDataStoresResponse.deserialize, + ) + return self._stubs['list_data_stores'] + + @property + def delete_data_store(self) -> Callable[ + [data_store_service.DeleteDataStoreRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete data store method over gRPC. + + Deletes a + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]. + + Returns: + Callable[[~.DeleteDataStoreRequest], + 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_data_store' not in self._stubs: + self._stubs['delete_data_store'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.DataStoreService/DeleteDataStore', + request_serializer=data_store_service.DeleteDataStoreRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_data_store'] + + @property + def update_data_store(self) -> Callable[ + [data_store_service.UpdateDataStoreRequest], + Awaitable[gcd_data_store.DataStore]]: + r"""Return a callable for the update data store method over gRPC. + + Updates a + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore] + + Returns: + Callable[[~.UpdateDataStoreRequest], + Awaitable[~.DataStore]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_data_store' not in self._stubs: + self._stubs['update_data_store'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.DataStoreService/UpdateDataStore', + request_serializer=data_store_service.UpdateDataStoreRequest.serialize, + response_deserializer=gcd_data_store.DataStore.deserialize, + ) + return self._stubs['update_data_store'] + + def close(self): + return self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ( + 'DataStoreServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/rest.py new file mode 100644 index 000000000000..442e40a5726c --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/rest.py @@ -0,0 +1,1195 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.cloud.location import locations_pb2 # type: ignore +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.discoveryengine_v1alpha.types import data_store +from google.cloud.discoveryengine_v1alpha.types import data_store as gcd_data_store +from google.cloud.discoveryengine_v1alpha.types import data_store_service +from google.longrunning import operations_pb2 # type: ignore + +from .base import DataStoreServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class DataStoreServiceRestInterceptor: + """Interceptor for DataStoreService. + + 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 DataStoreServiceRestTransport. + + .. code-block:: python + class MyCustomDataStoreServiceInterceptor(DataStoreServiceRestInterceptor): + def pre_create_data_store(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_data_store(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_data_store(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_data_store(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_data_store(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_data_store(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_data_stores(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_data_stores(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_data_store(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_data_store(self, response): + logging.log(f"Received response: {response}") + return response + + transport = DataStoreServiceRestTransport(interceptor=MyCustomDataStoreServiceInterceptor()) + client = DataStoreServiceClient(transport=transport) + + + """ + def pre_create_data_store(self, request: data_store_service.CreateDataStoreRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[data_store_service.CreateDataStoreRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_data_store + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataStoreService server. + """ + return request, metadata + + def post_create_data_store(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_data_store + + Override in a subclass to manipulate the response + after it is returned by the DataStoreService server but before + it is returned to user code. + """ + return response + def pre_delete_data_store(self, request: data_store_service.DeleteDataStoreRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[data_store_service.DeleteDataStoreRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_data_store + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataStoreService server. + """ + return request, metadata + + def post_delete_data_store(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_data_store + + Override in a subclass to manipulate the response + after it is returned by the DataStoreService server but before + it is returned to user code. + """ + return response + def pre_get_data_store(self, request: data_store_service.GetDataStoreRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[data_store_service.GetDataStoreRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_data_store + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataStoreService server. + """ + return request, metadata + + def post_get_data_store(self, response: data_store.DataStore) -> data_store.DataStore: + """Post-rpc interceptor for get_data_store + + Override in a subclass to manipulate the response + after it is returned by the DataStoreService server but before + it is returned to user code. + """ + return response + def pre_list_data_stores(self, request: data_store_service.ListDataStoresRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[data_store_service.ListDataStoresRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_data_stores + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataStoreService server. + """ + return request, metadata + + def post_list_data_stores(self, response: data_store_service.ListDataStoresResponse) -> data_store_service.ListDataStoresResponse: + """Post-rpc interceptor for list_data_stores + + Override in a subclass to manipulate the response + after it is returned by the DataStoreService server but before + it is returned to user code. + """ + return response + def pre_update_data_store(self, request: data_store_service.UpdateDataStoreRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[data_store_service.UpdateDataStoreRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_data_store + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataStoreService server. + """ + return request, metadata + + def post_update_data_store(self, response: gcd_data_store.DataStore) -> gcd_data_store.DataStore: + """Post-rpc interceptor for update_data_store + + Override in a subclass to manipulate the response + after it is returned by the DataStoreService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataStoreService 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 DataStoreService server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataStoreService 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 DataStoreService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class DataStoreServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: DataStoreServiceRestInterceptor + + +class DataStoreServiceRestTransport(DataStoreServiceTransport): + """REST backend transport for DataStoreService. + + Service for managing + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore] + configuration. + + 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 = 'discoveryengine.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[DataStoreServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or DataStoreServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1alpha") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CreateDataStore(DataStoreServiceRestStub): + def __hash__(self): + return hash("CreateDataStore") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "dataStoreId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: data_store_service.CreateDataStoreRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create data store method over HTTP. + + Args: + request (~.data_store_service.CreateDataStoreRequest): + The request object. Request for + [DataStoreService.CreateDataStore][google.cloud.discoveryengine.v1alpha.DataStoreService.CreateDataStore] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=projects/*/locations/*}/dataStores', + 'body': 'data_store', + }, +{ + 'method': 'post', + 'uri': '/v1alpha/{parent=projects/*/locations/*/collections/*}/dataStores', + 'body': 'data_store', + }, + ] + request, metadata = self._interceptor.pre_create_data_store(request, metadata) + pb_request = data_store_service.CreateDataStoreRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_data_store(resp) + return resp + + class _DeleteDataStore(DataStoreServiceRestStub): + def __hash__(self): + return hash("DeleteDataStore") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: data_store_service.DeleteDataStoreRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete data store method over HTTP. + + Args: + request (~.data_store_service.DeleteDataStoreRequest): + The request object. Request message for + [DataStoreService.DeleteDataStore][google.cloud.discoveryengine.v1alpha.DataStoreService.DeleteDataStore] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_data_store(request, metadata) + pb_request = data_store_service.DeleteDataStoreRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_data_store(resp) + return resp + + class _GetDataStore(DataStoreServiceRestStub): + def __hash__(self): + return hash("GetDataStore") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: data_store_service.GetDataStoreRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> data_store.DataStore: + r"""Call the get data store method over HTTP. + + Args: + request (~.data_store_service.GetDataStoreRequest): + The request object. Request message for + [DataStoreService.GetDataStore][google.cloud.discoveryengine.v1alpha.DataStoreService.GetDataStore] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.data_store.DataStore: + DataStore captures global settings + and configs at the DataStore level. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}', + }, + ] + request, metadata = self._interceptor.pre_get_data_store(request, metadata) + pb_request = data_store_service.GetDataStoreRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = data_store.DataStore() + pb_resp = data_store.DataStore.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_data_store(resp) + return resp + + class _ListDataStores(DataStoreServiceRestStub): + def __hash__(self): + return hash("ListDataStores") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: data_store_service.ListDataStoresRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> data_store_service.ListDataStoresResponse: + r"""Call the list data stores method over HTTP. + + Args: + request (~.data_store_service.ListDataStoresRequest): + The request object. Request message for + [DataStoreService.ListDataStores][google.cloud.discoveryengine.v1alpha.DataStoreService.ListDataStores] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.data_store_service.ListDataStoresResponse: + Response message for + [DataStoreService.ListDataStores][google.cloud.discoveryengine.v1alpha.DataStoreService.ListDataStores] + method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=projects/*/locations/*}/dataStores', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{parent=projects/*/locations/*/collections/*}/dataStores', + }, + ] + request, metadata = self._interceptor.pre_list_data_stores(request, metadata) + pb_request = data_store_service.ListDataStoresRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = data_store_service.ListDataStoresResponse() + pb_resp = data_store_service.ListDataStoresResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_data_stores(resp) + return resp + + class _UpdateDataStore(DataStoreServiceRestStub): + def __hash__(self): + return hash("UpdateDataStore") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: data_store_service.UpdateDataStoreRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcd_data_store.DataStore: + r"""Call the update data store method over HTTP. + + Args: + request (~.data_store_service.UpdateDataStoreRequest): + The request object. Request message for + [DataStoreService.UpdateDataStore][google.cloud.discoveryengine.v1alpha.DataStoreService.UpdateDataStore] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcd_data_store.DataStore: + DataStore captures global settings + and configs at the DataStore level. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha/{data_store.name=projects/*/locations/*/dataStores/*}', + 'body': 'data_store', + }, +{ + 'method': 'patch', + 'uri': '/v1alpha/{data_store.name=projects/*/locations/*/collections/*/dataStores/*}', + 'body': 'data_store', + }, + ] + request, metadata = self._interceptor.pre_update_data_store(request, metadata) + pb_request = data_store_service.UpdateDataStoreRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcd_data_store.DataStore() + pb_resp = gcd_data_store.DataStore.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_data_store(resp) + return resp + + @property + def create_data_store(self) -> Callable[ + [data_store_service.CreateDataStoreRequest], + 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._CreateDataStore(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_data_store(self) -> Callable[ + [data_store_service.DeleteDataStoreRequest], + 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._DeleteDataStore(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_data_store(self) -> Callable[ + [data_store_service.GetDataStoreRequest], + data_store.DataStore]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetDataStore(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_data_stores(self) -> Callable[ + [data_store_service.ListDataStoresRequest], + data_store_service.ListDataStoresResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListDataStores(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_data_store(self) -> Callable[ + [data_store_service.UpdateDataStoreRequest], + gcd_data_store.DataStore]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateDataStore(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(DataStoreServiceRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(DataStoreServiceRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'DataStoreServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/__init__.py new file mode 100644 index 000000000000..e4f0b808a498 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import DocumentServiceClient +from .async_client import DocumentServiceAsyncClient + +__all__ = ( + 'DocumentServiceClient', + 'DocumentServiceAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/async_client.py new file mode 100644 index 000000000000..95fcb6bd4e65 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/async_client.py @@ -0,0 +1,1113 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.discoveryengine_v1alpha.services.document_service import pagers +from google.cloud.discoveryengine_v1alpha.types import document +from google.cloud.discoveryengine_v1alpha.types import document as gcd_document +from google.cloud.discoveryengine_v1alpha.types import document_service +from google.cloud.discoveryengine_v1alpha.types import import_config +from google.cloud.discoveryengine_v1alpha.types import purge_config +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from .transports.base import DocumentServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import DocumentServiceGrpcAsyncIOTransport +from .client import DocumentServiceClient + + +class DocumentServiceAsyncClient: + """Service for ingesting + [Document][google.cloud.discoveryengine.v1alpha.Document] + information of the customer's website. + """ + + _client: DocumentServiceClient + + DEFAULT_ENDPOINT = DocumentServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = DocumentServiceClient.DEFAULT_MTLS_ENDPOINT + + branch_path = staticmethod(DocumentServiceClient.branch_path) + parse_branch_path = staticmethod(DocumentServiceClient.parse_branch_path) + document_path = staticmethod(DocumentServiceClient.document_path) + parse_document_path = staticmethod(DocumentServiceClient.parse_document_path) + common_billing_account_path = staticmethod(DocumentServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(DocumentServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(DocumentServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(DocumentServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(DocumentServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(DocumentServiceClient.parse_common_organization_path) + common_project_path = staticmethod(DocumentServiceClient.common_project_path) + parse_common_project_path = staticmethod(DocumentServiceClient.parse_common_project_path) + common_location_path = staticmethod(DocumentServiceClient.common_location_path) + parse_common_location_path = staticmethod(DocumentServiceClient.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: + DocumentServiceAsyncClient: The constructed client. + """ + return DocumentServiceClient.from_service_account_info.__func__(DocumentServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DocumentServiceAsyncClient: The constructed client. + """ + return DocumentServiceClient.from_service_account_file.__func__(DocumentServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return DocumentServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> DocumentServiceTransport: + """Returns the transport used by the client instance. + + Returns: + DocumentServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(DocumentServiceClient).get_transport_class, type(DocumentServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, DocumentServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the document 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 (Union[str, ~.DocumentServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = DocumentServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def get_document(self, + request: Optional[Union[document_service.GetDocumentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> document.Document: + r"""Gets a + [Document][google.cloud.discoveryengine.v1alpha.Document]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_get_document(): + # Create a client + client = discoveryengine_v1alpha.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.GetDocumentRequest( + name="name_value", + ) + + # Make the request + response = await client.get_document(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.GetDocumentRequest, dict]]): + The request object. Request message for + [DocumentService.GetDocument][google.cloud.discoveryengine.v1alpha.DocumentService.GetDocument] + method. + name (:class:`str`): + Required. Full resource name of + [Document][google.cloud.discoveryengine.v1alpha.Document], + such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. + + If the caller does not have permission to access the + [Document][google.cloud.discoveryengine.v1alpha.Document], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the requested + [Document][google.cloud.discoveryengine.v1alpha.Document] + does not exist, a ``NOT_FOUND`` error is returned. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.Document: + Document captures all raw metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = document_service.GetDocumentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_document, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_documents(self, + request: Optional[Union[document_service.ListDocumentsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDocumentsAsyncPager: + r"""Gets a list of + [Document][google.cloud.discoveryengine.v1alpha.Document]s. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_list_documents(): + # Create a client + client = discoveryengine_v1alpha.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ListDocumentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_documents(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.ListDocumentsRequest, dict]]): + The request object. Request message for + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.ListDocuments] + method. + parent (:class:`str`): + Required. The parent branch resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. + Use ``default_branch`` as the branch ID, to list + documents under the default branch. + + If the caller does not have permission to list + [Document][google.cloud.discoveryengine.v1alpha.Document]s + under this branch, regardless of whether or not this + branch exists, a ``PERMISSION_DENIED`` error is + returned. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.services.document_service.pagers.ListDocumentsAsyncPager: + Response message for + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.ListDocuments] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = document_service.ListDocumentsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_documents, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListDocumentsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_document(self, + request: Optional[Union[document_service.CreateDocumentRequest, dict]] = None, + *, + parent: Optional[str] = None, + document: Optional[gcd_document.Document] = None, + document_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_document.Document: + r"""Creates a + [Document][google.cloud.discoveryengine.v1alpha.Document]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_create_document(): + # Create a client + client = discoveryengine_v1alpha.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.CreateDocumentRequest( + parent="parent_value", + document_id="document_id_value", + ) + + # Make the request + response = await client.create_document(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.CreateDocumentRequest, dict]]): + The request object. Request message for + [DocumentService.CreateDocument][google.cloud.discoveryengine.v1alpha.DocumentService.CreateDocument] + method. + parent (:class:`str`): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + document (:class:`google.cloud.discoveryengine_v1alpha.types.Document`): + Required. The + [Document][google.cloud.discoveryengine.v1alpha.Document] + to create. + + This corresponds to the ``document`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + document_id (:class:`str`): + Required. The ID to use for the + [Document][google.cloud.discoveryengine.v1alpha.Document], + which will become the final component of the + [Document.name][google.cloud.discoveryengine.v1alpha.Document.name]. + + If the caller does not have permission to create the + [Document][google.cloud.discoveryengine.v1alpha.Document], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + This field must be unique among all + [Document][google.cloud.discoveryengine.v1alpha.Document]s + with the same + [parent][google.cloud.discoveryengine.v1alpha.CreateDocumentRequest.parent]. + Otherwise, an ``ALREADY_EXISTS`` error is returned. + + This field must conform to + `RFC-1034 `__ + standard with a length limit of 63 characters. + Otherwise, an ``INVALID_ARGUMENT`` error is returned. + + This corresponds to the ``document_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.Document: + Document captures all raw metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, document, document_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = document_service.CreateDocumentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if document is not None: + request.document = document + if document_id is not None: + request.document_id = document_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_document, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_document(self, + request: Optional[Union[document_service.UpdateDocumentRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> document.Document: + r"""Updates a + [Document][google.cloud.discoveryengine.v1alpha.Document]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_update_document(): + # Create a client + client = discoveryengine_v1alpha.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.UpdateDocumentRequest( + ) + + # Make the request + response = await client.update_document(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.UpdateDocumentRequest, dict]]): + The request object. Request message for + [DocumentService.UpdateDocument][google.cloud.discoveryengine.v1alpha.DocumentService.UpdateDocument] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.Document: + Document captures all raw metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + request = document_service.UpdateDocumentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_document, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("document.name", request.document.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_document(self, + request: Optional[Union[document_service.DeleteDocumentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a + [Document][google.cloud.discoveryengine.v1alpha.Document]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_delete_document(): + # Create a client + client = discoveryengine_v1alpha.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.DeleteDocumentRequest( + name="name_value", + ) + + # Make the request + await client.delete_document(request=request) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.DeleteDocumentRequest, dict]]): + The request object. Request message for + [DocumentService.DeleteDocument][google.cloud.discoveryengine.v1alpha.DocumentService.DeleteDocument] + method. + name (:class:`str`): + Required. Full resource name of + [Document][google.cloud.discoveryengine.v1alpha.Document], + such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. + + If the caller does not have permission to delete the + [Document][google.cloud.discoveryengine.v1alpha.Document], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [Document][google.cloud.discoveryengine.v1alpha.Document] + to delete does not exist, a ``NOT_FOUND`` error is + returned. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = document_service.DeleteDocumentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_document, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def import_documents(self, + request: Optional[Union[import_config.ImportDocumentsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of multiple + [Document][google.cloud.discoveryengine.v1alpha.Document]s. + Request processing may be synchronous. Non-existing items will + be created. + + Note: It is possible for a subset of the + [Document][google.cloud.discoveryengine.v1alpha.Document]s to be + successfully updated. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_import_documents(): + # Create a client + client = discoveryengine_v1alpha.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ImportDocumentsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.import_documents(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.ImportDocumentsRequest, dict]]): + The request object. Request message for Import methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1alpha.types.ImportDocumentsResponse` Response of the + [ImportDocumentsRequest][google.cloud.discoveryengine.v1alpha.ImportDocumentsRequest]. + If the long running operation is done, then this + message is returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + request = import_config.ImportDocumentsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_documents, + default_retry=retries.Retry( +initial=1.0,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_config.ImportDocumentsResponse, + metadata_type=import_config.ImportDocumentsMetadata, + ) + + # Done; return the response. + return response + + async def purge_documents(self, + request: Optional[Union[purge_config.PurgeDocumentsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Permanently deletes all selected + [Document][google.cloud.discoveryengine.v1alpha.Document]s in a + branch. + + This process is asynchronous. Depending on the number of + [Document][google.cloud.discoveryengine.v1alpha.Document]s to be + deleted, this operation can take hours to complete. Before the + delete operation completes, some + [Document][google.cloud.discoveryengine.v1alpha.Document]s might + still be returned by + [DocumentService.GetDocument][google.cloud.discoveryengine.v1alpha.DocumentService.GetDocument] + or + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.ListDocuments]. + + To get a list of the + [Document][google.cloud.discoveryengine.v1alpha.Document]s to be + deleted, set + [PurgeDocumentsRequest.force][google.cloud.discoveryengine.v1alpha.PurgeDocumentsRequest.force] + to false. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_purge_documents(): + # Create a client + client = discoveryengine_v1alpha.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.PurgeDocumentsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_documents(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.PurgeDocumentsRequest, dict]]): + The request object. Request message for + [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.PurgeDocuments] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1alpha.types.PurgeDocumentsResponse` Response message for + [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.PurgeDocuments] + method. If the long running operation is successfully + done, then this message is returned by the + google.longrunning.Operations.response field. + + """ + # Create or coerce a protobuf request object. + request = purge_config.PurgeDocumentsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.purge_documents, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + purge_config.PurgeDocumentsResponse, + metadata_type=purge_config.PurgeDocumentsMetadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "DocumentServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "DocumentServiceAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/client.py new file mode 100644 index 000000000000..25859a535026 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/client.py @@ -0,0 +1,1326 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.discoveryengine_v1alpha.services.document_service import pagers +from google.cloud.discoveryengine_v1alpha.types import document +from google.cloud.discoveryengine_v1alpha.types import document as gcd_document +from google.cloud.discoveryengine_v1alpha.types import document_service +from google.cloud.discoveryengine_v1alpha.types import import_config +from google.cloud.discoveryengine_v1alpha.types import purge_config +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from .transports.base import DocumentServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import DocumentServiceGrpcTransport +from .transports.grpc_asyncio import DocumentServiceGrpcAsyncIOTransport +from .transports.rest import DocumentServiceRestTransport + + +class DocumentServiceClientMeta(type): + """Metaclass for the DocumentService 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[DocumentServiceTransport]] + _transport_registry["grpc"] = DocumentServiceGrpcTransport + _transport_registry["grpc_asyncio"] = DocumentServiceGrpcAsyncIOTransport + _transport_registry["rest"] = DocumentServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[DocumentServiceTransport]: + """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 DocumentServiceClient(metaclass=DocumentServiceClientMeta): + """Service for ingesting + [Document][google.cloud.discoveryengine.v1alpha.Document] + information of the customer's website. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DocumentServiceClient: 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: + DocumentServiceClient: 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) -> DocumentServiceTransport: + """Returns the transport used by the client instance. + + Returns: + DocumentServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def branch_path(project: str,location: str,data_store: str,branch: str,) -> str: + """Returns a fully-qualified branch string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}".format(project=project, location=location, data_store=data_store, branch=branch, ) + + @staticmethod + def parse_branch_path(path: str) -> Dict[str,str]: + """Parses a branch path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def document_path(project: str,location: str,data_store: str,branch: str,document: str,) -> str: + """Returns a fully-qualified document string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) + + @staticmethod + def parse_document_path(path: str) -> Dict[str,str]: + """Parses a document path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)/documents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, DocumentServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the document 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 (Union[str, DocumentServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, DocumentServiceTransport): + # transport is a DocumentServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def get_document(self, + request: Optional[Union[document_service.GetDocumentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> document.Document: + r"""Gets a + [Document][google.cloud.discoveryengine.v1alpha.Document]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_get_document(): + # Create a client + client = discoveryengine_v1alpha.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.GetDocumentRequest( + name="name_value", + ) + + # Make the request + response = client.get_document(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.GetDocumentRequest, dict]): + The request object. Request message for + [DocumentService.GetDocument][google.cloud.discoveryengine.v1alpha.DocumentService.GetDocument] + method. + name (str): + Required. Full resource name of + [Document][google.cloud.discoveryengine.v1alpha.Document], + such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. + + If the caller does not have permission to access the + [Document][google.cloud.discoveryengine.v1alpha.Document], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the requested + [Document][google.cloud.discoveryengine.v1alpha.Document] + does not exist, a ``NOT_FOUND`` error is returned. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.Document: + Document captures all raw metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a document_service.GetDocumentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, document_service.GetDocumentRequest): + request = document_service.GetDocumentRequest(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_document] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_documents(self, + request: Optional[Union[document_service.ListDocumentsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDocumentsPager: + r"""Gets a list of + [Document][google.cloud.discoveryengine.v1alpha.Document]s. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_list_documents(): + # Create a client + client = discoveryengine_v1alpha.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ListDocumentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_documents(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.ListDocumentsRequest, dict]): + The request object. Request message for + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.ListDocuments] + method. + parent (str): + Required. The parent branch resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. + Use ``default_branch`` as the branch ID, to list + documents under the default branch. + + If the caller does not have permission to list + [Document][google.cloud.discoveryengine.v1alpha.Document]s + under this branch, regardless of whether or not this + branch exists, a ``PERMISSION_DENIED`` error is + returned. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.services.document_service.pagers.ListDocumentsPager: + Response message for + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.ListDocuments] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a document_service.ListDocumentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, document_service.ListDocumentsRequest): + request = document_service.ListDocumentsRequest(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_documents] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListDocumentsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_document(self, + request: Optional[Union[document_service.CreateDocumentRequest, dict]] = None, + *, + parent: Optional[str] = None, + document: Optional[gcd_document.Document] = None, + document_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_document.Document: + r"""Creates a + [Document][google.cloud.discoveryengine.v1alpha.Document]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_create_document(): + # Create a client + client = discoveryengine_v1alpha.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.CreateDocumentRequest( + parent="parent_value", + document_id="document_id_value", + ) + + # Make the request + response = client.create_document(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.CreateDocumentRequest, dict]): + The request object. Request message for + [DocumentService.CreateDocument][google.cloud.discoveryengine.v1alpha.DocumentService.CreateDocument] + method. + parent (str): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + document (google.cloud.discoveryengine_v1alpha.types.Document): + Required. The + [Document][google.cloud.discoveryengine.v1alpha.Document] + to create. + + This corresponds to the ``document`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + document_id (str): + Required. The ID to use for the + [Document][google.cloud.discoveryengine.v1alpha.Document], + which will become the final component of the + [Document.name][google.cloud.discoveryengine.v1alpha.Document.name]. + + If the caller does not have permission to create the + [Document][google.cloud.discoveryengine.v1alpha.Document], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + This field must be unique among all + [Document][google.cloud.discoveryengine.v1alpha.Document]s + with the same + [parent][google.cloud.discoveryengine.v1alpha.CreateDocumentRequest.parent]. + Otherwise, an ``ALREADY_EXISTS`` error is returned. + + This field must conform to + `RFC-1034 `__ + standard with a length limit of 63 characters. + Otherwise, an ``INVALID_ARGUMENT`` error is returned. + + This corresponds to the ``document_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.Document: + Document captures all raw metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, document, document_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a document_service.CreateDocumentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, document_service.CreateDocumentRequest): + request = document_service.CreateDocumentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if document is not None: + request.document = document + if document_id is not None: + request.document_id = document_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_document] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_document(self, + request: Optional[Union[document_service.UpdateDocumentRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> document.Document: + r"""Updates a + [Document][google.cloud.discoveryengine.v1alpha.Document]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_update_document(): + # Create a client + client = discoveryengine_v1alpha.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.UpdateDocumentRequest( + ) + + # Make the request + response = client.update_document(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.UpdateDocumentRequest, dict]): + The request object. Request message for + [DocumentService.UpdateDocument][google.cloud.discoveryengine.v1alpha.DocumentService.UpdateDocument] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.Document: + Document captures all raw metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a document_service.UpdateDocumentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, document_service.UpdateDocumentRequest): + request = document_service.UpdateDocumentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_document] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("document.name", request.document.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_document(self, + request: Optional[Union[document_service.DeleteDocumentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a + [Document][google.cloud.discoveryengine.v1alpha.Document]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_delete_document(): + # Create a client + client = discoveryengine_v1alpha.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.DeleteDocumentRequest( + name="name_value", + ) + + # Make the request + client.delete_document(request=request) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.DeleteDocumentRequest, dict]): + The request object. Request message for + [DocumentService.DeleteDocument][google.cloud.discoveryengine.v1alpha.DocumentService.DeleteDocument] + method. + name (str): + Required. Full resource name of + [Document][google.cloud.discoveryengine.v1alpha.Document], + such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. + + If the caller does not have permission to delete the + [Document][google.cloud.discoveryengine.v1alpha.Document], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [Document][google.cloud.discoveryengine.v1alpha.Document] + to delete does not exist, a ``NOT_FOUND`` error is + returned. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a document_service.DeleteDocumentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, document_service.DeleteDocumentRequest): + request = document_service.DeleteDocumentRequest(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_document] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def import_documents(self, + request: Optional[Union[import_config.ImportDocumentsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Bulk import of multiple + [Document][google.cloud.discoveryengine.v1alpha.Document]s. + Request processing may be synchronous. Non-existing items will + be created. + + Note: It is possible for a subset of the + [Document][google.cloud.discoveryengine.v1alpha.Document]s to be + successfully updated. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_import_documents(): + # Create a client + client = discoveryengine_v1alpha.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ImportDocumentsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.import_documents(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.ImportDocumentsRequest, dict]): + The request object. Request message for Import methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1alpha.types.ImportDocumentsResponse` Response of the + [ImportDocumentsRequest][google.cloud.discoveryengine.v1alpha.ImportDocumentsRequest]. + If the long running operation is done, then this + message is returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a import_config.ImportDocumentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, import_config.ImportDocumentsRequest): + request = import_config.ImportDocumentsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_documents] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_config.ImportDocumentsResponse, + metadata_type=import_config.ImportDocumentsMetadata, + ) + + # Done; return the response. + return response + + def purge_documents(self, + request: Optional[Union[purge_config.PurgeDocumentsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Permanently deletes all selected + [Document][google.cloud.discoveryengine.v1alpha.Document]s in a + branch. + + This process is asynchronous. Depending on the number of + [Document][google.cloud.discoveryengine.v1alpha.Document]s to be + deleted, this operation can take hours to complete. Before the + delete operation completes, some + [Document][google.cloud.discoveryengine.v1alpha.Document]s might + still be returned by + [DocumentService.GetDocument][google.cloud.discoveryengine.v1alpha.DocumentService.GetDocument] + or + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.ListDocuments]. + + To get a list of the + [Document][google.cloud.discoveryengine.v1alpha.Document]s to be + deleted, set + [PurgeDocumentsRequest.force][google.cloud.discoveryengine.v1alpha.PurgeDocumentsRequest.force] + to false. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_purge_documents(): + # Create a client + client = discoveryengine_v1alpha.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.PurgeDocumentsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_documents(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.PurgeDocumentsRequest, dict]): + The request object. Request message for + [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.PurgeDocuments] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1alpha.types.PurgeDocumentsResponse` Response message for + [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.PurgeDocuments] + method. If the long running operation is successfully + done, then this message is returned by the + google.longrunning.Operations.response field. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a purge_config.PurgeDocumentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, purge_config.PurgeDocumentsRequest): + request = purge_config.PurgeDocumentsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.purge_documents] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + purge_config.PurgeDocumentsResponse, + metadata_type=purge_config.PurgeDocumentsMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "DocumentServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "DocumentServiceClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/pagers.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/pagers.py new file mode 100644 index 000000000000..c85996e0b84b --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.discoveryengine_v1alpha.types import document +from google.cloud.discoveryengine_v1alpha.types import document_service + + +class ListDocumentsPager: + """A pager for iterating through ``list_documents`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1alpha.types.ListDocumentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``documents`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDocuments`` requests and continue to iterate + through the ``documents`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1alpha.types.ListDocumentsResponse` + 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[..., document_service.ListDocumentsResponse], + request: document_service.ListDocumentsRequest, + response: document_service.ListDocumentsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.discoveryengine_v1alpha.types.ListDocumentsRequest): + The initial request object. + response (google.cloud.discoveryengine_v1alpha.types.ListDocumentsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = document_service.ListDocumentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[document_service.ListDocumentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[document.Document]: + for page in self.pages: + yield from page.documents + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDocumentsAsyncPager: + """A pager for iterating through ``list_documents`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1alpha.types.ListDocumentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``documents`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDocuments`` requests and continue to iterate + through the ``documents`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1alpha.types.ListDocumentsResponse` + 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[document_service.ListDocumentsResponse]], + request: document_service.ListDocumentsRequest, + response: document_service.ListDocumentsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.discoveryengine_v1alpha.types.ListDocumentsRequest): + The initial request object. + response (google.cloud.discoveryengine_v1alpha.types.ListDocumentsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = document_service.ListDocumentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[document_service.ListDocumentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[document.Document]: + async def async_generator(): + async for page in self.pages: + for response in page.documents: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/__init__.py new file mode 100644 index 000000000000..fb08db02f32c --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import DocumentServiceTransport +from .grpc import DocumentServiceGrpcTransport +from .grpc_asyncio import DocumentServiceGrpcAsyncIOTransport +from .rest import DocumentServiceRestTransport +from .rest import DocumentServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[DocumentServiceTransport]] +_transport_registry['grpc'] = DocumentServiceGrpcTransport +_transport_registry['grpc_asyncio'] = DocumentServiceGrpcAsyncIOTransport +_transport_registry['rest'] = DocumentServiceRestTransport + +__all__ = ( + 'DocumentServiceTransport', + 'DocumentServiceGrpcTransport', + 'DocumentServiceGrpcAsyncIOTransport', + 'DocumentServiceRestTransport', + 'DocumentServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/base.py new file mode 100644 index 000000000000..3d8e5687bd47 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/base.py @@ -0,0 +1,269 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import document +from google.cloud.discoveryengine_v1alpha.types import document as gcd_document +from google.cloud.discoveryengine_v1alpha.types import document_service +from google.cloud.discoveryengine_v1alpha.types import import_config +from google.cloud.discoveryengine_v1alpha.types import purge_config +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class DocumentServiceTransport(abc.ABC): + """Abstract transport class for DocumentService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'discoveryengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_document: gapic_v1.method.wrap_method( + self.get_document, + default_timeout=None, + client_info=client_info, + ), + self.list_documents: gapic_v1.method.wrap_method( + self.list_documents, + default_timeout=None, + client_info=client_info, + ), + self.create_document: gapic_v1.method.wrap_method( + self.create_document, + default_timeout=None, + client_info=client_info, + ), + self.update_document: gapic_v1.method.wrap_method( + self.update_document, + default_timeout=None, + client_info=client_info, + ), + self.delete_document: gapic_v1.method.wrap_method( + self.delete_document, + default_timeout=None, + client_info=client_info, + ), + self.import_documents: gapic_v1.method.wrap_method( + self.import_documents, + default_retry=retries.Retry( +initial=1.0,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.0, + client_info=client_info, + ), + self.purge_documents: gapic_v1.method.wrap_method( + self.purge_documents, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def get_document(self) -> Callable[ + [document_service.GetDocumentRequest], + Union[ + document.Document, + Awaitable[document.Document] + ]]: + raise NotImplementedError() + + @property + def list_documents(self) -> Callable[ + [document_service.ListDocumentsRequest], + Union[ + document_service.ListDocumentsResponse, + Awaitable[document_service.ListDocumentsResponse] + ]]: + raise NotImplementedError() + + @property + def create_document(self) -> Callable[ + [document_service.CreateDocumentRequest], + Union[ + gcd_document.Document, + Awaitable[gcd_document.Document] + ]]: + raise NotImplementedError() + + @property + def update_document(self) -> Callable[ + [document_service.UpdateDocumentRequest], + Union[ + document.Document, + Awaitable[document.Document] + ]]: + raise NotImplementedError() + + @property + def delete_document(self) -> Callable[ + [document_service.DeleteDocumentRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def import_documents(self) -> Callable[ + [import_config.ImportDocumentsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def purge_documents(self) -> Callable[ + [purge_config.PurgeDocumentsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'DocumentServiceTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/grpc.py new file mode 100644 index 000000000000..96c8692508a2 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/grpc.py @@ -0,0 +1,513 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import document +from google.cloud.discoveryengine_v1alpha.types import document as gcd_document +from google.cloud.discoveryengine_v1alpha.types import document_service +from google.cloud.discoveryengine_v1alpha.types import import_config +from google.cloud.discoveryengine_v1alpha.types import purge_config +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import DocumentServiceTransport, DEFAULT_CLIENT_INFO + + +class DocumentServiceGrpcTransport(DocumentServiceTransport): + """gRPC backend transport for DocumentService. + + Service for ingesting + [Document][google.cloud.discoveryengine.v1alpha.Document] + information of the customer's website. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def get_document(self) -> Callable[ + [document_service.GetDocumentRequest], + document.Document]: + r"""Return a callable for the get document method over gRPC. + + Gets a + [Document][google.cloud.discoveryengine.v1alpha.Document]. + + Returns: + Callable[[~.GetDocumentRequest], + ~.Document]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_document' not in self._stubs: + self._stubs['get_document'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.DocumentService/GetDocument', + request_serializer=document_service.GetDocumentRequest.serialize, + response_deserializer=document.Document.deserialize, + ) + return self._stubs['get_document'] + + @property + def list_documents(self) -> Callable[ + [document_service.ListDocumentsRequest], + document_service.ListDocumentsResponse]: + r"""Return a callable for the list documents method over gRPC. + + Gets a list of + [Document][google.cloud.discoveryengine.v1alpha.Document]s. + + Returns: + Callable[[~.ListDocumentsRequest], + ~.ListDocumentsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_documents' not in self._stubs: + self._stubs['list_documents'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.DocumentService/ListDocuments', + request_serializer=document_service.ListDocumentsRequest.serialize, + response_deserializer=document_service.ListDocumentsResponse.deserialize, + ) + return self._stubs['list_documents'] + + @property + def create_document(self) -> Callable[ + [document_service.CreateDocumentRequest], + gcd_document.Document]: + r"""Return a callable for the create document method over gRPC. + + Creates a + [Document][google.cloud.discoveryengine.v1alpha.Document]. + + Returns: + Callable[[~.CreateDocumentRequest], + ~.Document]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_document' not in self._stubs: + self._stubs['create_document'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.DocumentService/CreateDocument', + request_serializer=document_service.CreateDocumentRequest.serialize, + response_deserializer=gcd_document.Document.deserialize, + ) + return self._stubs['create_document'] + + @property + def update_document(self) -> Callable[ + [document_service.UpdateDocumentRequest], + document.Document]: + r"""Return a callable for the update document method over gRPC. + + Updates a + [Document][google.cloud.discoveryengine.v1alpha.Document]. + + Returns: + Callable[[~.UpdateDocumentRequest], + ~.Document]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_document' not in self._stubs: + self._stubs['update_document'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.DocumentService/UpdateDocument', + request_serializer=document_service.UpdateDocumentRequest.serialize, + response_deserializer=document.Document.deserialize, + ) + return self._stubs['update_document'] + + @property + def delete_document(self) -> Callable[ + [document_service.DeleteDocumentRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete document method over gRPC. + + Deletes a + [Document][google.cloud.discoveryengine.v1alpha.Document]. + + Returns: + Callable[[~.DeleteDocumentRequest], + ~.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_document' not in self._stubs: + self._stubs['delete_document'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.DocumentService/DeleteDocument', + request_serializer=document_service.DeleteDocumentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_document'] + + @property + def import_documents(self) -> Callable[ + [import_config.ImportDocumentsRequest], + operations_pb2.Operation]: + r"""Return a callable for the import documents method over gRPC. + + Bulk import of multiple + [Document][google.cloud.discoveryengine.v1alpha.Document]s. + Request processing may be synchronous. Non-existing items will + be created. + + Note: It is possible for a subset of the + [Document][google.cloud.discoveryengine.v1alpha.Document]s to be + successfully updated. + + Returns: + Callable[[~.ImportDocumentsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_documents' not in self._stubs: + self._stubs['import_documents'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.DocumentService/ImportDocuments', + request_serializer=import_config.ImportDocumentsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_documents'] + + @property + def purge_documents(self) -> Callable[ + [purge_config.PurgeDocumentsRequest], + operations_pb2.Operation]: + r"""Return a callable for the purge documents method over gRPC. + + Permanently deletes all selected + [Document][google.cloud.discoveryengine.v1alpha.Document]s in a + branch. + + This process is asynchronous. Depending on the number of + [Document][google.cloud.discoveryengine.v1alpha.Document]s to be + deleted, this operation can take hours to complete. Before the + delete operation completes, some + [Document][google.cloud.discoveryengine.v1alpha.Document]s might + still be returned by + [DocumentService.GetDocument][google.cloud.discoveryengine.v1alpha.DocumentService.GetDocument] + or + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.ListDocuments]. + + To get a list of the + [Document][google.cloud.discoveryengine.v1alpha.Document]s to be + deleted, set + [PurgeDocumentsRequest.force][google.cloud.discoveryengine.v1alpha.PurgeDocumentsRequest.force] + to false. + + Returns: + Callable[[~.PurgeDocumentsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'purge_documents' not in self._stubs: + self._stubs['purge_documents'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.DocumentService/PurgeDocuments', + request_serializer=purge_config.PurgeDocumentsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['purge_documents'] + + def close(self): + self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'DocumentServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..e15ed17c3f75 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/grpc_asyncio.py @@ -0,0 +1,512 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import document +from google.cloud.discoveryengine_v1alpha.types import document as gcd_document +from google.cloud.discoveryengine_v1alpha.types import document_service +from google.cloud.discoveryengine_v1alpha.types import import_config +from google.cloud.discoveryengine_v1alpha.types import purge_config +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import DocumentServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import DocumentServiceGrpcTransport + + +class DocumentServiceGrpcAsyncIOTransport(DocumentServiceTransport): + """gRPC AsyncIO backend transport for DocumentService. + + Service for ingesting + [Document][google.cloud.discoveryengine.v1alpha.Document] + information of the customer's website. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def get_document(self) -> Callable[ + [document_service.GetDocumentRequest], + Awaitable[document.Document]]: + r"""Return a callable for the get document method over gRPC. + + Gets a + [Document][google.cloud.discoveryengine.v1alpha.Document]. + + Returns: + Callable[[~.GetDocumentRequest], + Awaitable[~.Document]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_document' not in self._stubs: + self._stubs['get_document'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.DocumentService/GetDocument', + request_serializer=document_service.GetDocumentRequest.serialize, + response_deserializer=document.Document.deserialize, + ) + return self._stubs['get_document'] + + @property + def list_documents(self) -> Callable[ + [document_service.ListDocumentsRequest], + Awaitable[document_service.ListDocumentsResponse]]: + r"""Return a callable for the list documents method over gRPC. + + Gets a list of + [Document][google.cloud.discoveryengine.v1alpha.Document]s. + + Returns: + Callable[[~.ListDocumentsRequest], + Awaitable[~.ListDocumentsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_documents' not in self._stubs: + self._stubs['list_documents'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.DocumentService/ListDocuments', + request_serializer=document_service.ListDocumentsRequest.serialize, + response_deserializer=document_service.ListDocumentsResponse.deserialize, + ) + return self._stubs['list_documents'] + + @property + def create_document(self) -> Callable[ + [document_service.CreateDocumentRequest], + Awaitable[gcd_document.Document]]: + r"""Return a callable for the create document method over gRPC. + + Creates a + [Document][google.cloud.discoveryengine.v1alpha.Document]. + + Returns: + Callable[[~.CreateDocumentRequest], + Awaitable[~.Document]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_document' not in self._stubs: + self._stubs['create_document'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.DocumentService/CreateDocument', + request_serializer=document_service.CreateDocumentRequest.serialize, + response_deserializer=gcd_document.Document.deserialize, + ) + return self._stubs['create_document'] + + @property + def update_document(self) -> Callable[ + [document_service.UpdateDocumentRequest], + Awaitable[document.Document]]: + r"""Return a callable for the update document method over gRPC. + + Updates a + [Document][google.cloud.discoveryengine.v1alpha.Document]. + + Returns: + Callable[[~.UpdateDocumentRequest], + Awaitable[~.Document]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_document' not in self._stubs: + self._stubs['update_document'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.DocumentService/UpdateDocument', + request_serializer=document_service.UpdateDocumentRequest.serialize, + response_deserializer=document.Document.deserialize, + ) + return self._stubs['update_document'] + + @property + def delete_document(self) -> Callable[ + [document_service.DeleteDocumentRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete document method over gRPC. + + Deletes a + [Document][google.cloud.discoveryengine.v1alpha.Document]. + + Returns: + Callable[[~.DeleteDocumentRequest], + 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_document' not in self._stubs: + self._stubs['delete_document'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.DocumentService/DeleteDocument', + request_serializer=document_service.DeleteDocumentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_document'] + + @property + def import_documents(self) -> Callable[ + [import_config.ImportDocumentsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import documents method over gRPC. + + Bulk import of multiple + [Document][google.cloud.discoveryengine.v1alpha.Document]s. + Request processing may be synchronous. Non-existing items will + be created. + + Note: It is possible for a subset of the + [Document][google.cloud.discoveryengine.v1alpha.Document]s to be + successfully updated. + + Returns: + Callable[[~.ImportDocumentsRequest], + 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 'import_documents' not in self._stubs: + self._stubs['import_documents'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.DocumentService/ImportDocuments', + request_serializer=import_config.ImportDocumentsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_documents'] + + @property + def purge_documents(self) -> Callable[ + [purge_config.PurgeDocumentsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the purge documents method over gRPC. + + Permanently deletes all selected + [Document][google.cloud.discoveryengine.v1alpha.Document]s in a + branch. + + This process is asynchronous. Depending on the number of + [Document][google.cloud.discoveryengine.v1alpha.Document]s to be + deleted, this operation can take hours to complete. Before the + delete operation completes, some + [Document][google.cloud.discoveryengine.v1alpha.Document]s might + still be returned by + [DocumentService.GetDocument][google.cloud.discoveryengine.v1alpha.DocumentService.GetDocument] + or + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.ListDocuments]. + + To get a list of the + [Document][google.cloud.discoveryengine.v1alpha.Document]s to be + deleted, set + [PurgeDocumentsRequest.force][google.cloud.discoveryengine.v1alpha.PurgeDocumentsRequest.force] + to false. + + Returns: + Callable[[~.PurgeDocumentsRequest], + 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 'purge_documents' not in self._stubs: + self._stubs['purge_documents'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.DocumentService/PurgeDocuments', + request_serializer=purge_config.PurgeDocumentsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['purge_documents'] + + def close(self): + return self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ( + 'DocumentServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/rest.py new file mode 100644 index 000000000000..7595268f0392 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/rest.py @@ -0,0 +1,1429 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.cloud.location import locations_pb2 # type: ignore +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.discoveryengine_v1alpha.types import document +from google.cloud.discoveryengine_v1alpha.types import document as gcd_document +from google.cloud.discoveryengine_v1alpha.types import document_service +from google.cloud.discoveryengine_v1alpha.types import import_config +from google.cloud.discoveryengine_v1alpha.types import purge_config +from google.protobuf import empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from .base import DocumentServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class DocumentServiceRestInterceptor: + """Interceptor for DocumentService. + + 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 DocumentServiceRestTransport. + + .. code-block:: python + class MyCustomDocumentServiceInterceptor(DocumentServiceRestInterceptor): + def pre_create_document(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_document(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_document(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_document(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_document(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_import_documents(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_import_documents(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_documents(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_documents(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_purge_documents(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_purge_documents(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_document(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_document(self, response): + logging.log(f"Received response: {response}") + return response + + transport = DocumentServiceRestTransport(interceptor=MyCustomDocumentServiceInterceptor()) + client = DocumentServiceClient(transport=transport) + + + """ + def pre_create_document(self, request: document_service.CreateDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_service.CreateDocumentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_document + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentService server. + """ + return request, metadata + + def post_create_document(self, response: gcd_document.Document) -> gcd_document.Document: + """Post-rpc interceptor for create_document + + Override in a subclass to manipulate the response + after it is returned by the DocumentService server but before + it is returned to user code. + """ + return response + def pre_delete_document(self, request: document_service.DeleteDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_service.DeleteDocumentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_document + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentService server. + """ + return request, metadata + + def pre_get_document(self, request: document_service.GetDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_service.GetDocumentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_document + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentService server. + """ + return request, metadata + + def post_get_document(self, response: document.Document) -> document.Document: + """Post-rpc interceptor for get_document + + Override in a subclass to manipulate the response + after it is returned by the DocumentService server but before + it is returned to user code. + """ + return response + def pre_import_documents(self, request: import_config.ImportDocumentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[import_config.ImportDocumentsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for import_documents + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentService server. + """ + return request, metadata + + def post_import_documents(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for import_documents + + Override in a subclass to manipulate the response + after it is returned by the DocumentService server but before + it is returned to user code. + """ + return response + def pre_list_documents(self, request: document_service.ListDocumentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_service.ListDocumentsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_documents + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentService server. + """ + return request, metadata + + def post_list_documents(self, response: document_service.ListDocumentsResponse) -> document_service.ListDocumentsResponse: + """Post-rpc interceptor for list_documents + + Override in a subclass to manipulate the response + after it is returned by the DocumentService server but before + it is returned to user code. + """ + return response + def pre_purge_documents(self, request: purge_config.PurgeDocumentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[purge_config.PurgeDocumentsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for purge_documents + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentService server. + """ + return request, metadata + + def post_purge_documents(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for purge_documents + + Override in a subclass to manipulate the response + after it is returned by the DocumentService server but before + it is returned to user code. + """ + return response + def pre_update_document(self, request: document_service.UpdateDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_service.UpdateDocumentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_document + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentService server. + """ + return request, metadata + + def post_update_document(self, response: document.Document) -> document.Document: + """Post-rpc interceptor for update_document + + Override in a subclass to manipulate the response + after it is returned by the DocumentService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentService 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 DocumentService server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentService 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 DocumentService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class DocumentServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: DocumentServiceRestInterceptor + + +class DocumentServiceRestTransport(DocumentServiceTransport): + """REST backend transport for DocumentService. + + Service for ingesting + [Document][google.cloud.discoveryengine.v1alpha.Document] + information of the customer's website. + + 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 = 'discoveryengine.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[DocumentServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or DocumentServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1alpha") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CreateDocument(DocumentServiceRestStub): + def __hash__(self): + return hash("CreateDocument") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "documentId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_service.CreateDocumentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcd_document.Document: + r"""Call the create document method over HTTP. + + Args: + request (~.document_service.CreateDocumentRequest): + The request object. Request message for + [DocumentService.CreateDocument][google.cloud.discoveryengine.v1alpha.DocumentService.CreateDocument] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcd_document.Document: + Document captures all raw metadata + information of items to be recommended + or searched. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=projects/*/locations/*/dataStores/*/branches/*}/documents', + 'body': 'document', + }, +{ + 'method': 'post', + 'uri': '/v1alpha/{parent=projects/*/locations/*/collections/*/dataStores/*/branches/*}/documents', + 'body': 'document', + }, + ] + request, metadata = self._interceptor.pre_create_document(request, metadata) + pb_request = document_service.CreateDocumentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcd_document.Document() + pb_resp = gcd_document.Document.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_document(resp) + return resp + + class _DeleteDocument(DocumentServiceRestStub): + def __hash__(self): + return hash("DeleteDocument") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_service.DeleteDocumentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete document method over HTTP. + + Args: + request (~.document_service.DeleteDocumentRequest): + The request object. Request message for + [DocumentService.DeleteDocument][google.cloud.discoveryengine.v1alpha.DocumentService.DeleteDocument] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/documents/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/documents/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_document(request, metadata) + pb_request = document_service.DeleteDocumentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _GetDocument(DocumentServiceRestStub): + def __hash__(self): + return hash("GetDocument") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_service.GetDocumentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> document.Document: + r"""Call the get document method over HTTP. + + Args: + request (~.document_service.GetDocumentRequest): + The request object. Request message for + [DocumentService.GetDocument][google.cloud.discoveryengine.v1alpha.DocumentService.GetDocument] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.document.Document: + Document captures all raw metadata + information of items to be recommended + or searched. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/documents/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/documents/*}', + }, + ] + request, metadata = self._interceptor.pre_get_document(request, metadata) + pb_request = document_service.GetDocumentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = document.Document() + pb_resp = document.Document.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_document(resp) + return resp + + class _ImportDocuments(DocumentServiceRestStub): + def __hash__(self): + return hash("ImportDocuments") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: import_config.ImportDocumentsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the import documents method over HTTP. + + Args: + request (~.import_config.ImportDocumentsRequest): + The request object. Request message for Import methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=projects/*/locations/*/dataStores/*/branches/*}/documents:import', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha/{parent=projects/*/locations/*/collections/*/dataStores/*/branches/*}/documents:import', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_import_documents(request, metadata) + pb_request = import_config.ImportDocumentsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_import_documents(resp) + return resp + + class _ListDocuments(DocumentServiceRestStub): + def __hash__(self): + return hash("ListDocuments") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_service.ListDocumentsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> document_service.ListDocumentsResponse: + r"""Call the list documents method over HTTP. + + Args: + request (~.document_service.ListDocumentsRequest): + The request object. Request message for + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.ListDocuments] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.document_service.ListDocumentsResponse: + Response message for + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.ListDocuments] + method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=projects/*/locations/*/dataStores/*/branches/*}/documents', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{parent=projects/*/locations/*/collections/*/dataStores/*/branches/*}/documents', + }, + ] + request, metadata = self._interceptor.pre_list_documents(request, metadata) + pb_request = document_service.ListDocumentsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = document_service.ListDocumentsResponse() + pb_resp = document_service.ListDocumentsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_documents(resp) + return resp + + class _PurgeDocuments(DocumentServiceRestStub): + def __hash__(self): + return hash("PurgeDocuments") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: purge_config.PurgeDocumentsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the purge documents method over HTTP. + + Args: + request (~.purge_config.PurgeDocumentsRequest): + The request object. Request message for + [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.PurgeDocuments] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=projects/*/locations/*/dataStores/*/branches/*}/documents:purge', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha/{parent=projects/*/locations/*/collections/*/dataStores/*/branches/*}/documents:purge', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_purge_documents(request, metadata) + pb_request = purge_config.PurgeDocumentsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_purge_documents(resp) + return resp + + class _UpdateDocument(DocumentServiceRestStub): + def __hash__(self): + return hash("UpdateDocument") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_service.UpdateDocumentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> document.Document: + r"""Call the update document method over HTTP. + + Args: + request (~.document_service.UpdateDocumentRequest): + The request object. Request message for + [DocumentService.UpdateDocument][google.cloud.discoveryengine.v1alpha.DocumentService.UpdateDocument] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.document.Document: + Document captures all raw metadata + information of items to be recommended + or searched. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha/{document.name=projects/*/locations/*/dataStores/*/branches/*/documents/*}', + 'body': 'document', + }, +{ + 'method': 'patch', + 'uri': '/v1alpha/{document.name=projects/*/locations/*/collections/*/dataStores/*/branches/*/documents/*}', + 'body': 'document', + }, + ] + request, metadata = self._interceptor.pre_update_document(request, metadata) + pb_request = document_service.UpdateDocumentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = document.Document() + pb_resp = document.Document.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_document(resp) + return resp + + @property + def create_document(self) -> Callable[ + [document_service.CreateDocumentRequest], + gcd_document.Document]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateDocument(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_document(self) -> Callable[ + [document_service.DeleteDocumentRequest], + 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._DeleteDocument(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_document(self) -> Callable[ + [document_service.GetDocumentRequest], + document.Document]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetDocument(self._session, self._host, self._interceptor) # type: ignore + + @property + def import_documents(self) -> Callable[ + [import_config.ImportDocumentsRequest], + 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._ImportDocuments(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_documents(self) -> Callable[ + [document_service.ListDocumentsRequest], + document_service.ListDocumentsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListDocuments(self._session, self._host, self._interceptor) # type: ignore + + @property + def purge_documents(self) -> Callable[ + [purge_config.PurgeDocumentsRequest], + 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._PurgeDocuments(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_document(self) -> Callable[ + [document_service.UpdateDocumentRequest], + document.Document]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateDocument(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(DocumentServiceRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(DocumentServiceRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'DocumentServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/__init__.py new file mode 100644 index 000000000000..84cdcf706834 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import EngineServiceClient +from .async_client import EngineServiceAsyncClient + +__all__ = ( + 'EngineServiceClient', + 'EngineServiceAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/async_client.py new file mode 100644 index 000000000000..957377607715 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/async_client.py @@ -0,0 +1,1279 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.discoveryengine_v1alpha.services.engine_service import pagers +from google.cloud.discoveryengine_v1alpha.types import common +from google.cloud.discoveryengine_v1alpha.types import engine +from google.cloud.discoveryengine_v1alpha.types import engine as gcd_engine +from google.cloud.discoveryengine_v1alpha.types import engine_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import EngineServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import EngineServiceGrpcAsyncIOTransport +from .client import EngineServiceClient + + +class EngineServiceAsyncClient: + """Service for managing + [Engine][google.cloud.discoveryengine.v1alpha.Engine] configuration. + """ + + _client: EngineServiceClient + + DEFAULT_ENDPOINT = EngineServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = EngineServiceClient.DEFAULT_MTLS_ENDPOINT + + collection_path = staticmethod(EngineServiceClient.collection_path) + parse_collection_path = staticmethod(EngineServiceClient.parse_collection_path) + engine_path = staticmethod(EngineServiceClient.engine_path) + parse_engine_path = staticmethod(EngineServiceClient.parse_engine_path) + common_billing_account_path = staticmethod(EngineServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(EngineServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(EngineServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(EngineServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(EngineServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(EngineServiceClient.parse_common_organization_path) + common_project_path = staticmethod(EngineServiceClient.common_project_path) + parse_common_project_path = staticmethod(EngineServiceClient.parse_common_project_path) + common_location_path = staticmethod(EngineServiceClient.common_location_path) + parse_common_location_path = staticmethod(EngineServiceClient.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: + EngineServiceAsyncClient: The constructed client. + """ + return EngineServiceClient.from_service_account_info.__func__(EngineServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + EngineServiceAsyncClient: The constructed client. + """ + return EngineServiceClient.from_service_account_file.__func__(EngineServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return EngineServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> EngineServiceTransport: + """Returns the transport used by the client instance. + + Returns: + EngineServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(EngineServiceClient).get_transport_class, type(EngineServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, EngineServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the engine 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 (Union[str, ~.EngineServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = EngineServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_engine(self, + request: Optional[Union[engine_service.CreateEngineRequest, dict]] = None, + *, + parent: Optional[str] = None, + engine: Optional[gcd_engine.Engine] = None, + engine_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a [Engine][google.cloud.discoveryengine.v1alpha.Engine]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_create_engine(): + # Create a client + client = discoveryengine_v1alpha.EngineServiceAsyncClient() + + # Initialize request argument(s) + engine = discoveryengine_v1alpha.Engine() + engine.display_name = "display_name_value" + engine.solution_type = "SOLUTION_TYPE_CHAT" + + request = discoveryengine_v1alpha.CreateEngineRequest( + parent="parent_value", + engine=engine, + engine_id="engine_id_value", + ) + + # Make the request + operation = client.create_engine(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.CreateEngineRequest, dict]]): + The request object. Request for + [EngineService.CreateEngine][google.cloud.discoveryengine.v1alpha.EngineService.CreateEngine] + method. + parent (:class:`str`): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + engine (:class:`google.cloud.discoveryengine_v1alpha.types.Engine`): + Required. The + [Engine][google.cloud.discoveryengine.v1alpha.Engine] to + create. + + This corresponds to the ``engine`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + engine_id (:class:`str`): + Required. The ID to use for the + [Engine][google.cloud.discoveryengine.v1alpha.Engine], + which will become the final component of the + [Engine][google.cloud.discoveryengine.v1alpha.Engine]'s + resource name. + + This field must conform to + `RFC-1034 `__ + standard with a length limit of 63 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + This corresponds to the ``engine_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1alpha.types.Engine` Metadata that describes the training and serving parameters of an + [Engine][google.cloud.discoveryengine.v1alpha.Engine]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, engine, engine_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = engine_service.CreateEngineRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if engine is not None: + request.engine = engine + if engine_id is not None: + request.engine_id = engine_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_engine, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcd_engine.Engine, + metadata_type=engine_service.CreateEngineMetadata, + ) + + # Done; return the response. + return response + + async def delete_engine(self, + request: Optional[Union[engine_service.DeleteEngineRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a [Engine][google.cloud.discoveryengine.v1alpha.Engine]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_delete_engine(): + # Create a client + client = discoveryengine_v1alpha.EngineServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.DeleteEngineRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_engine(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.DeleteEngineRequest, dict]]): + The request object. Request message for + [EngineService.DeleteEngine][google.cloud.discoveryengine.v1alpha.EngineService.DeleteEngine] + method. + name (:class:`str`): + Required. Full resource name of + [Engine][google.cloud.discoveryengine.v1alpha.Engine], + such as + ``projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}``. + + If the caller does not have permission to delete the + [Engine][google.cloud.discoveryengine.v1alpha.Engine], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the + [Engine][google.cloud.discoveryengine.v1alpha.Engine] to + delete does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = engine_service.DeleteEngineRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_engine, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=engine_service.DeleteEngineMetadata, + ) + + # Done; return the response. + return response + + async def update_engine(self, + request: Optional[Union[engine_service.UpdateEngineRequest, dict]] = None, + *, + engine: Optional[gcd_engine.Engine] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_engine.Engine: + r"""Updates an [Engine][google.cloud.discoveryengine.v1alpha.Engine] + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_update_engine(): + # Create a client + client = discoveryengine_v1alpha.EngineServiceAsyncClient() + + # Initialize request argument(s) + engine = discoveryengine_v1alpha.Engine() + engine.display_name = "display_name_value" + engine.solution_type = "SOLUTION_TYPE_CHAT" + + request = discoveryengine_v1alpha.UpdateEngineRequest( + engine=engine, + ) + + # Make the request + response = await client.update_engine(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.UpdateEngineRequest, dict]]): + The request object. Request message for + [EngineService.UpdateEngine][google.cloud.discoveryengine.v1alpha.EngineService.UpdateEngine] + method. + engine (:class:`google.cloud.discoveryengine_v1alpha.types.Engine`): + Required. The + [Engine][google.cloud.discoveryengine.v1alpha.Engine] to + update. + + If the caller does not have permission to update the + [Engine][google.cloud.discoveryengine.v1alpha.Engine], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the + [Engine][google.cloud.discoveryengine.v1alpha.Engine] to + update does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``engine`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Indicates which fields in the provided + [Engine][google.cloud.discoveryengine.v1alpha.Engine] to + update. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.Engine: + Metadata that describes the training and serving parameters of an + [Engine][google.cloud.discoveryengine.v1alpha.Engine]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([engine, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = engine_service.UpdateEngineRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if engine is not None: + request.engine = engine + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_engine, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("engine.name", request.engine.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_engine(self, + request: Optional[Union[engine_service.GetEngineRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> engine.Engine: + r"""Gets a [Engine][google.cloud.discoveryengine.v1alpha.Engine]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_get_engine(): + # Create a client + client = discoveryengine_v1alpha.EngineServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.GetEngineRequest( + name="name_value", + ) + + # Make the request + response = await client.get_engine(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.GetEngineRequest, dict]]): + The request object. Request message for + [EngineService.GetEngine][google.cloud.discoveryengine.v1alpha.EngineService.GetEngine] + method. + name (:class:`str`): + Required. Full resource name of + [Engine][google.cloud.discoveryengine.v1alpha.Engine], + such as + ``projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.Engine: + Metadata that describes the training and serving parameters of an + [Engine][google.cloud.discoveryengine.v1alpha.Engine]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = engine_service.GetEngineRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_engine, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_engines(self, + request: Optional[Union[engine_service.ListEnginesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEnginesAsyncPager: + r"""Lists all the + [Engine][google.cloud.discoveryengine.v1alpha.Engine]s + associated with the project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_list_engines(): + # Create a client + client = discoveryengine_v1alpha.EngineServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ListEnginesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_engines(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.ListEnginesRequest, dict]]): + The request object. Request message for + [EngineService.ListEngines][google.cloud.discoveryengine.v1alpha.EngineService.ListEngines] + method. + parent (:class:`str`): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}/collections/{collection_id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.services.engine_service.pagers.ListEnginesAsyncPager: + Response message for + [EngineService.ListEngines][google.cloud.discoveryengine.v1alpha.EngineService.ListEngines] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = engine_service.ListEnginesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_engines, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListEnginesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def pause_engine(self, + request: Optional[Union[engine_service.PauseEngineRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> engine.Engine: + r"""Pauses the training of an existing engine. Only applicable if + [solution_type][] is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.discoveryengine.v1alpha.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_pause_engine(): + # Create a client + client = discoveryengine_v1alpha.EngineServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.PauseEngineRequest( + name="name_value", + ) + + # Make the request + response = await client.pause_engine(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.PauseEngineRequest, dict]]): + The request object. Request for pausing training of an + engine. + name (:class:`str`): + Required. The name of the engine to pause. Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/engines/{engine_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.Engine: + Metadata that describes the training and serving parameters of an + [Engine][google.cloud.discoveryengine.v1alpha.Engine]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = engine_service.PauseEngineRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.pause_engine, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def resume_engine(self, + request: Optional[Union[engine_service.ResumeEngineRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> engine.Engine: + r"""Resumes the training of an existing engine. Only applicable if + [solution_type][] is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.discoveryengine.v1alpha.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_resume_engine(): + # Create a client + client = discoveryengine_v1alpha.EngineServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ResumeEngineRequest( + name="name_value", + ) + + # Make the request + response = await client.resume_engine(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.ResumeEngineRequest, dict]]): + The request object. Request for resuming training of an + engine. + name (:class:`str`): + Required. The name of the engine to resume. Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/engines/{engine_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.Engine: + Metadata that describes the training and serving parameters of an + [Engine][google.cloud.discoveryengine.v1alpha.Engine]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = engine_service.ResumeEngineRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.resume_engine, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def tune_engine(self, + request: Optional[Union[engine_service.TuneEngineRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Tunes an existing engine. Only applicable if [solution_type][] + is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.discoveryengine.v1alpha.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_tune_engine(): + # Create a client + client = discoveryengine_v1alpha.EngineServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.TuneEngineRequest( + name="name_value", + ) + + # Make the request + operation = client.tune_engine(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.TuneEngineRequest, dict]]): + The request object. Request to manually start a tuning + process now (instead of waiting for the + periodically scheduled tuning to + happen). + name (:class:`str`): + Required. The resource name of the engine to tune. + Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/engines/{engine_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.discoveryengine_v1alpha.types.TuneEngineResponse` + Response associated with a tune operation. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = engine_service.TuneEngineRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.tune_engine, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + engine_service.TuneEngineResponse, + metadata_type=engine_service.TuneEngineMetadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "EngineServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "EngineServiceAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/client.py new file mode 100644 index 000000000000..b3b713dad2c0 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/client.py @@ -0,0 +1,1495 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.discoveryengine_v1alpha.services.engine_service import pagers +from google.cloud.discoveryengine_v1alpha.types import common +from google.cloud.discoveryengine_v1alpha.types import engine +from google.cloud.discoveryengine_v1alpha.types import engine as gcd_engine +from google.cloud.discoveryengine_v1alpha.types import engine_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import EngineServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import EngineServiceGrpcTransport +from .transports.grpc_asyncio import EngineServiceGrpcAsyncIOTransport +from .transports.rest import EngineServiceRestTransport + + +class EngineServiceClientMeta(type): + """Metaclass for the EngineService 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[EngineServiceTransport]] + _transport_registry["grpc"] = EngineServiceGrpcTransport + _transport_registry["grpc_asyncio"] = EngineServiceGrpcAsyncIOTransport + _transport_registry["rest"] = EngineServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[EngineServiceTransport]: + """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 EngineServiceClient(metaclass=EngineServiceClientMeta): + """Service for managing + [Engine][google.cloud.discoveryengine.v1alpha.Engine] configuration. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + EngineServiceClient: 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: + EngineServiceClient: 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) -> EngineServiceTransport: + """Returns the transport used by the client instance. + + Returns: + EngineServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def collection_path(project: str,location: str,collection: str,) -> str: + """Returns a fully-qualified collection string.""" + return "projects/{project}/locations/{location}/collections/{collection}".format(project=project, location=location, collection=collection, ) + + @staticmethod + def parse_collection_path(path: str) -> Dict[str,str]: + """Parses a collection path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/collections/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def engine_path(project: str,location: str,collection: str,engine: str,) -> str: + """Returns a fully-qualified engine string.""" + return "projects/{project}/locations/{location}/collections/{collection}/engines/{engine}".format(project=project, location=location, collection=collection, engine=engine, ) + + @staticmethod + def parse_engine_path(path: str) -> Dict[str,str]: + """Parses a engine path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/collections/(?P.+?)/engines/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, EngineServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the engine 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 (Union[str, EngineServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, EngineServiceTransport): + # transport is a EngineServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def create_engine(self, + request: Optional[Union[engine_service.CreateEngineRequest, dict]] = None, + *, + parent: Optional[str] = None, + engine: Optional[gcd_engine.Engine] = None, + engine_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a [Engine][google.cloud.discoveryengine.v1alpha.Engine]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_create_engine(): + # Create a client + client = discoveryengine_v1alpha.EngineServiceClient() + + # Initialize request argument(s) + engine = discoveryengine_v1alpha.Engine() + engine.display_name = "display_name_value" + engine.solution_type = "SOLUTION_TYPE_CHAT" + + request = discoveryengine_v1alpha.CreateEngineRequest( + parent="parent_value", + engine=engine, + engine_id="engine_id_value", + ) + + # Make the request + operation = client.create_engine(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.CreateEngineRequest, dict]): + The request object. Request for + [EngineService.CreateEngine][google.cloud.discoveryengine.v1alpha.EngineService.CreateEngine] + method. + parent (str): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + engine (google.cloud.discoveryengine_v1alpha.types.Engine): + Required. The + [Engine][google.cloud.discoveryengine.v1alpha.Engine] to + create. + + This corresponds to the ``engine`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + engine_id (str): + Required. The ID to use for the + [Engine][google.cloud.discoveryengine.v1alpha.Engine], + which will become the final component of the + [Engine][google.cloud.discoveryengine.v1alpha.Engine]'s + resource name. + + This field must conform to + `RFC-1034 `__ + standard with a length limit of 63 characters. + Otherwise, an INVALID_ARGUMENT error is returned. + + This corresponds to the ``engine_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1alpha.types.Engine` Metadata that describes the training and serving parameters of an + [Engine][google.cloud.discoveryengine.v1alpha.Engine]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, engine, engine_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a engine_service.CreateEngineRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, engine_service.CreateEngineRequest): + request = engine_service.CreateEngineRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if engine is not None: + request.engine = engine + if engine_id is not None: + request.engine_id = engine_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_engine] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gcd_engine.Engine, + metadata_type=engine_service.CreateEngineMetadata, + ) + + # Done; return the response. + return response + + def delete_engine(self, + request: Optional[Union[engine_service.DeleteEngineRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a [Engine][google.cloud.discoveryengine.v1alpha.Engine]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_delete_engine(): + # Create a client + client = discoveryengine_v1alpha.EngineServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.DeleteEngineRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_engine(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.DeleteEngineRequest, dict]): + The request object. Request message for + [EngineService.DeleteEngine][google.cloud.discoveryengine.v1alpha.EngineService.DeleteEngine] + method. + name (str): + Required. Full resource name of + [Engine][google.cloud.discoveryengine.v1alpha.Engine], + such as + ``projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}``. + + If the caller does not have permission to delete the + [Engine][google.cloud.discoveryengine.v1alpha.Engine], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the + [Engine][google.cloud.discoveryengine.v1alpha.Engine] to + delete does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a engine_service.DeleteEngineRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, engine_service.DeleteEngineRequest): + request = engine_service.DeleteEngineRequest(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_engine] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=engine_service.DeleteEngineMetadata, + ) + + # Done; return the response. + return response + + def update_engine(self, + request: Optional[Union[engine_service.UpdateEngineRequest, dict]] = None, + *, + engine: Optional[gcd_engine.Engine] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_engine.Engine: + r"""Updates an [Engine][google.cloud.discoveryengine.v1alpha.Engine] + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_update_engine(): + # Create a client + client = discoveryengine_v1alpha.EngineServiceClient() + + # Initialize request argument(s) + engine = discoveryengine_v1alpha.Engine() + engine.display_name = "display_name_value" + engine.solution_type = "SOLUTION_TYPE_CHAT" + + request = discoveryengine_v1alpha.UpdateEngineRequest( + engine=engine, + ) + + # Make the request + response = client.update_engine(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.UpdateEngineRequest, dict]): + The request object. Request message for + [EngineService.UpdateEngine][google.cloud.discoveryengine.v1alpha.EngineService.UpdateEngine] + method. + engine (google.cloud.discoveryengine_v1alpha.types.Engine): + Required. The + [Engine][google.cloud.discoveryengine.v1alpha.Engine] to + update. + + If the caller does not have permission to update the + [Engine][google.cloud.discoveryengine.v1alpha.Engine], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the + [Engine][google.cloud.discoveryengine.v1alpha.Engine] to + update does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``engine`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [Engine][google.cloud.discoveryengine.v1alpha.Engine] to + update. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.Engine: + Metadata that describes the training and serving parameters of an + [Engine][google.cloud.discoveryengine.v1alpha.Engine]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([engine, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a engine_service.UpdateEngineRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, engine_service.UpdateEngineRequest): + request = engine_service.UpdateEngineRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if engine is not None: + request.engine = engine + 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_engine] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("engine.name", request.engine.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_engine(self, + request: Optional[Union[engine_service.GetEngineRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> engine.Engine: + r"""Gets a [Engine][google.cloud.discoveryengine.v1alpha.Engine]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_get_engine(): + # Create a client + client = discoveryengine_v1alpha.EngineServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.GetEngineRequest( + name="name_value", + ) + + # Make the request + response = client.get_engine(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.GetEngineRequest, dict]): + The request object. Request message for + [EngineService.GetEngine][google.cloud.discoveryengine.v1alpha.EngineService.GetEngine] + method. + name (str): + Required. Full resource name of + [Engine][google.cloud.discoveryengine.v1alpha.Engine], + such as + ``projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.Engine: + Metadata that describes the training and serving parameters of an + [Engine][google.cloud.discoveryengine.v1alpha.Engine]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a engine_service.GetEngineRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, engine_service.GetEngineRequest): + request = engine_service.GetEngineRequest(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_engine] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_engines(self, + request: Optional[Union[engine_service.ListEnginesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEnginesPager: + r"""Lists all the + [Engine][google.cloud.discoveryengine.v1alpha.Engine]s + associated with the project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_list_engines(): + # Create a client + client = discoveryengine_v1alpha.EngineServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ListEnginesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_engines(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.ListEnginesRequest, dict]): + The request object. Request message for + [EngineService.ListEngines][google.cloud.discoveryengine.v1alpha.EngineService.ListEngines] + method. + parent (str): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}/collections/{collection_id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.services.engine_service.pagers.ListEnginesPager: + Response message for + [EngineService.ListEngines][google.cloud.discoveryengine.v1alpha.EngineService.ListEngines] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a engine_service.ListEnginesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, engine_service.ListEnginesRequest): + request = engine_service.ListEnginesRequest(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_engines] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListEnginesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def pause_engine(self, + request: Optional[Union[engine_service.PauseEngineRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> engine.Engine: + r"""Pauses the training of an existing engine. Only applicable if + [solution_type][] is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.discoveryengine.v1alpha.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_pause_engine(): + # Create a client + client = discoveryengine_v1alpha.EngineServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.PauseEngineRequest( + name="name_value", + ) + + # Make the request + response = client.pause_engine(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.PauseEngineRequest, dict]): + The request object. Request for pausing training of an + engine. + name (str): + Required. The name of the engine to pause. Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/engines/{engine_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.Engine: + Metadata that describes the training and serving parameters of an + [Engine][google.cloud.discoveryengine.v1alpha.Engine]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a engine_service.PauseEngineRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, engine_service.PauseEngineRequest): + request = engine_service.PauseEngineRequest(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.pause_engine] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def resume_engine(self, + request: Optional[Union[engine_service.ResumeEngineRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> engine.Engine: + r"""Resumes the training of an existing engine. Only applicable if + [solution_type][] is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.discoveryengine.v1alpha.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_resume_engine(): + # Create a client + client = discoveryengine_v1alpha.EngineServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ResumeEngineRequest( + name="name_value", + ) + + # Make the request + response = client.resume_engine(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.ResumeEngineRequest, dict]): + The request object. Request for resuming training of an + engine. + name (str): + Required. The name of the engine to resume. Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/engines/{engine_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.Engine: + Metadata that describes the training and serving parameters of an + [Engine][google.cloud.discoveryengine.v1alpha.Engine]. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a engine_service.ResumeEngineRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, engine_service.ResumeEngineRequest): + request = engine_service.ResumeEngineRequest(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.resume_engine] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def tune_engine(self, + request: Optional[Union[engine_service.TuneEngineRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Tunes an existing engine. Only applicable if [solution_type][] + is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.discoveryengine.v1alpha.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_tune_engine(): + # Create a client + client = discoveryengine_v1alpha.EngineServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.TuneEngineRequest( + name="name_value", + ) + + # Make the request + operation = client.tune_engine(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.TuneEngineRequest, dict]): + The request object. Request to manually start a tuning + process now (instead of waiting for the + periodically scheduled tuning to + happen). + name (str): + Required. The resource name of the engine to tune. + Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/engines/{engine_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.discoveryengine_v1alpha.types.TuneEngineResponse` + Response associated with a tune operation. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a engine_service.TuneEngineRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, engine_service.TuneEngineRequest): + request = engine_service.TuneEngineRequest(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.tune_engine] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + engine_service.TuneEngineResponse, + metadata_type=engine_service.TuneEngineMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "EngineServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "EngineServiceClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/pagers.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/pagers.py new file mode 100644 index 000000000000..4024f3c35e51 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.discoveryengine_v1alpha.types import engine +from google.cloud.discoveryengine_v1alpha.types import engine_service + + +class ListEnginesPager: + """A pager for iterating through ``list_engines`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1alpha.types.ListEnginesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``engines`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEngines`` requests and continue to iterate + through the ``engines`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1alpha.types.ListEnginesResponse` + 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[..., engine_service.ListEnginesResponse], + request: engine_service.ListEnginesRequest, + response: engine_service.ListEnginesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.discoveryengine_v1alpha.types.ListEnginesRequest): + The initial request object. + response (google.cloud.discoveryengine_v1alpha.types.ListEnginesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = engine_service.ListEnginesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[engine_service.ListEnginesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[engine.Engine]: + for page in self.pages: + yield from page.engines + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEnginesAsyncPager: + """A pager for iterating through ``list_engines`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1alpha.types.ListEnginesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``engines`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEngines`` requests and continue to iterate + through the ``engines`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1alpha.types.ListEnginesResponse` + 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[engine_service.ListEnginesResponse]], + request: engine_service.ListEnginesRequest, + response: engine_service.ListEnginesResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.discoveryengine_v1alpha.types.ListEnginesRequest): + The initial request object. + response (google.cloud.discoveryengine_v1alpha.types.ListEnginesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = engine_service.ListEnginesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[engine_service.ListEnginesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[engine.Engine]: + async def async_generator(): + async for page in self.pages: + for response in page.engines: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/__init__.py new file mode 100644 index 000000000000..e6f573dcd7dd --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import EngineServiceTransport +from .grpc import EngineServiceGrpcTransport +from .grpc_asyncio import EngineServiceGrpcAsyncIOTransport +from .rest import EngineServiceRestTransport +from .rest import EngineServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[EngineServiceTransport]] +_transport_registry['grpc'] = EngineServiceGrpcTransport +_transport_registry['grpc_asyncio'] = EngineServiceGrpcAsyncIOTransport +_transport_registry['rest'] = EngineServiceRestTransport + +__all__ = ( + 'EngineServiceTransport', + 'EngineServiceGrpcTransport', + 'EngineServiceGrpcAsyncIOTransport', + 'EngineServiceRestTransport', + 'EngineServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/base.py new file mode 100644 index 000000000000..7bf38c24e227 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/base.py @@ -0,0 +1,274 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import engine +from google.cloud.discoveryengine_v1alpha.types import engine as gcd_engine +from google.cloud.discoveryengine_v1alpha.types import engine_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class EngineServiceTransport(abc.ABC): + """Abstract transport class for EngineService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'discoveryengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_engine: gapic_v1.method.wrap_method( + self.create_engine, + default_timeout=None, + client_info=client_info, + ), + self.delete_engine: gapic_v1.method.wrap_method( + self.delete_engine, + default_timeout=None, + client_info=client_info, + ), + self.update_engine: gapic_v1.method.wrap_method( + self.update_engine, + default_timeout=None, + client_info=client_info, + ), + self.get_engine: gapic_v1.method.wrap_method( + self.get_engine, + default_timeout=None, + client_info=client_info, + ), + self.list_engines: gapic_v1.method.wrap_method( + self.list_engines, + default_timeout=None, + client_info=client_info, + ), + self.pause_engine: gapic_v1.method.wrap_method( + self.pause_engine, + default_timeout=None, + client_info=client_info, + ), + self.resume_engine: gapic_v1.method.wrap_method( + self.resume_engine, + default_timeout=None, + client_info=client_info, + ), + self.tune_engine: gapic_v1.method.wrap_method( + self.tune_engine, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_engine(self) -> Callable[ + [engine_service.CreateEngineRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_engine(self) -> Callable[ + [engine_service.DeleteEngineRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_engine(self) -> Callable[ + [engine_service.UpdateEngineRequest], + Union[ + gcd_engine.Engine, + Awaitable[gcd_engine.Engine] + ]]: + raise NotImplementedError() + + @property + def get_engine(self) -> Callable[ + [engine_service.GetEngineRequest], + Union[ + engine.Engine, + Awaitable[engine.Engine] + ]]: + raise NotImplementedError() + + @property + def list_engines(self) -> Callable[ + [engine_service.ListEnginesRequest], + Union[ + engine_service.ListEnginesResponse, + Awaitable[engine_service.ListEnginesResponse] + ]]: + raise NotImplementedError() + + @property + def pause_engine(self) -> Callable[ + [engine_service.PauseEngineRequest], + Union[ + engine.Engine, + Awaitable[engine.Engine] + ]]: + raise NotImplementedError() + + @property + def resume_engine(self) -> Callable[ + [engine_service.ResumeEngineRequest], + Union[ + engine.Engine, + Awaitable[engine.Engine] + ]]: + raise NotImplementedError() + + @property + def tune_engine(self) -> Callable[ + [engine_service.TuneEngineRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'EngineServiceTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/grpc.py new file mode 100644 index 000000000000..0c2a0d8a9e70 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/grpc.py @@ -0,0 +1,513 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import engine +from google.cloud.discoveryengine_v1alpha.types import engine as gcd_engine +from google.cloud.discoveryengine_v1alpha.types import engine_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import EngineServiceTransport, DEFAULT_CLIENT_INFO + + +class EngineServiceGrpcTransport(EngineServiceTransport): + """gRPC backend transport for EngineService. + + Service for managing + [Engine][google.cloud.discoveryengine.v1alpha.Engine] configuration. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_engine(self) -> Callable[ + [engine_service.CreateEngineRequest], + operations_pb2.Operation]: + r"""Return a callable for the create engine method over gRPC. + + Creates a [Engine][google.cloud.discoveryengine.v1alpha.Engine]. + + Returns: + Callable[[~.CreateEngineRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_engine' not in self._stubs: + self._stubs['create_engine'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.EngineService/CreateEngine', + request_serializer=engine_service.CreateEngineRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_engine'] + + @property + def delete_engine(self) -> Callable[ + [engine_service.DeleteEngineRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete engine method over gRPC. + + Deletes a [Engine][google.cloud.discoveryengine.v1alpha.Engine]. + + Returns: + Callable[[~.DeleteEngineRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_engine' not in self._stubs: + self._stubs['delete_engine'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.EngineService/DeleteEngine', + request_serializer=engine_service.DeleteEngineRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_engine'] + + @property + def update_engine(self) -> Callable[ + [engine_service.UpdateEngineRequest], + gcd_engine.Engine]: + r"""Return a callable for the update engine method over gRPC. + + Updates an [Engine][google.cloud.discoveryengine.v1alpha.Engine] + + Returns: + Callable[[~.UpdateEngineRequest], + ~.Engine]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_engine' not in self._stubs: + self._stubs['update_engine'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.EngineService/UpdateEngine', + request_serializer=engine_service.UpdateEngineRequest.serialize, + response_deserializer=gcd_engine.Engine.deserialize, + ) + return self._stubs['update_engine'] + + @property + def get_engine(self) -> Callable[ + [engine_service.GetEngineRequest], + engine.Engine]: + r"""Return a callable for the get engine method over gRPC. + + Gets a [Engine][google.cloud.discoveryengine.v1alpha.Engine]. + + Returns: + Callable[[~.GetEngineRequest], + ~.Engine]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_engine' not in self._stubs: + self._stubs['get_engine'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.EngineService/GetEngine', + request_serializer=engine_service.GetEngineRequest.serialize, + response_deserializer=engine.Engine.deserialize, + ) + return self._stubs['get_engine'] + + @property + def list_engines(self) -> Callable[ + [engine_service.ListEnginesRequest], + engine_service.ListEnginesResponse]: + r"""Return a callable for the list engines method over gRPC. + + Lists all the + [Engine][google.cloud.discoveryengine.v1alpha.Engine]s + associated with the project. + + Returns: + Callable[[~.ListEnginesRequest], + ~.ListEnginesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_engines' not in self._stubs: + self._stubs['list_engines'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.EngineService/ListEngines', + request_serializer=engine_service.ListEnginesRequest.serialize, + response_deserializer=engine_service.ListEnginesResponse.deserialize, + ) + return self._stubs['list_engines'] + + @property + def pause_engine(self) -> Callable[ + [engine_service.PauseEngineRequest], + engine.Engine]: + r"""Return a callable for the pause engine method over gRPC. + + Pauses the training of an existing engine. Only applicable if + [solution_type][] is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.discoveryengine.v1alpha.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + + Returns: + Callable[[~.PauseEngineRequest], + ~.Engine]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'pause_engine' not in self._stubs: + self._stubs['pause_engine'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.EngineService/PauseEngine', + request_serializer=engine_service.PauseEngineRequest.serialize, + response_deserializer=engine.Engine.deserialize, + ) + return self._stubs['pause_engine'] + + @property + def resume_engine(self) -> Callable[ + [engine_service.ResumeEngineRequest], + engine.Engine]: + r"""Return a callable for the resume engine method over gRPC. + + Resumes the training of an existing engine. Only applicable if + [solution_type][] is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.discoveryengine.v1alpha.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + + Returns: + Callable[[~.ResumeEngineRequest], + ~.Engine]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'resume_engine' not in self._stubs: + self._stubs['resume_engine'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.EngineService/ResumeEngine', + request_serializer=engine_service.ResumeEngineRequest.serialize, + response_deserializer=engine.Engine.deserialize, + ) + return self._stubs['resume_engine'] + + @property + def tune_engine(self) -> Callable[ + [engine_service.TuneEngineRequest], + operations_pb2.Operation]: + r"""Return a callable for the tune engine method over gRPC. + + Tunes an existing engine. Only applicable if [solution_type][] + is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.discoveryengine.v1alpha.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + + Returns: + Callable[[~.TuneEngineRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'tune_engine' not in self._stubs: + self._stubs['tune_engine'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.EngineService/TuneEngine', + request_serializer=engine_service.TuneEngineRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['tune_engine'] + + def close(self): + self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'EngineServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..2fd747d0f02a --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/grpc_asyncio.py @@ -0,0 +1,512 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import engine +from google.cloud.discoveryengine_v1alpha.types import engine as gcd_engine +from google.cloud.discoveryengine_v1alpha.types import engine_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import EngineServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import EngineServiceGrpcTransport + + +class EngineServiceGrpcAsyncIOTransport(EngineServiceTransport): + """gRPC AsyncIO backend transport for EngineService. + + Service for managing + [Engine][google.cloud.discoveryengine.v1alpha.Engine] configuration. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_engine(self) -> Callable[ + [engine_service.CreateEngineRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create engine method over gRPC. + + Creates a [Engine][google.cloud.discoveryengine.v1alpha.Engine]. + + Returns: + Callable[[~.CreateEngineRequest], + 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_engine' not in self._stubs: + self._stubs['create_engine'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.EngineService/CreateEngine', + request_serializer=engine_service.CreateEngineRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_engine'] + + @property + def delete_engine(self) -> Callable[ + [engine_service.DeleteEngineRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete engine method over gRPC. + + Deletes a [Engine][google.cloud.discoveryengine.v1alpha.Engine]. + + Returns: + Callable[[~.DeleteEngineRequest], + 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_engine' not in self._stubs: + self._stubs['delete_engine'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.EngineService/DeleteEngine', + request_serializer=engine_service.DeleteEngineRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_engine'] + + @property + def update_engine(self) -> Callable[ + [engine_service.UpdateEngineRequest], + Awaitable[gcd_engine.Engine]]: + r"""Return a callable for the update engine method over gRPC. + + Updates an [Engine][google.cloud.discoveryengine.v1alpha.Engine] + + Returns: + Callable[[~.UpdateEngineRequest], + Awaitable[~.Engine]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_engine' not in self._stubs: + self._stubs['update_engine'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.EngineService/UpdateEngine', + request_serializer=engine_service.UpdateEngineRequest.serialize, + response_deserializer=gcd_engine.Engine.deserialize, + ) + return self._stubs['update_engine'] + + @property + def get_engine(self) -> Callable[ + [engine_service.GetEngineRequest], + Awaitable[engine.Engine]]: + r"""Return a callable for the get engine method over gRPC. + + Gets a [Engine][google.cloud.discoveryengine.v1alpha.Engine]. + + Returns: + Callable[[~.GetEngineRequest], + Awaitable[~.Engine]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_engine' not in self._stubs: + self._stubs['get_engine'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.EngineService/GetEngine', + request_serializer=engine_service.GetEngineRequest.serialize, + response_deserializer=engine.Engine.deserialize, + ) + return self._stubs['get_engine'] + + @property + def list_engines(self) -> Callable[ + [engine_service.ListEnginesRequest], + Awaitable[engine_service.ListEnginesResponse]]: + r"""Return a callable for the list engines method over gRPC. + + Lists all the + [Engine][google.cloud.discoveryengine.v1alpha.Engine]s + associated with the project. + + Returns: + Callable[[~.ListEnginesRequest], + Awaitable[~.ListEnginesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_engines' not in self._stubs: + self._stubs['list_engines'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.EngineService/ListEngines', + request_serializer=engine_service.ListEnginesRequest.serialize, + response_deserializer=engine_service.ListEnginesResponse.deserialize, + ) + return self._stubs['list_engines'] + + @property + def pause_engine(self) -> Callable[ + [engine_service.PauseEngineRequest], + Awaitable[engine.Engine]]: + r"""Return a callable for the pause engine method over gRPC. + + Pauses the training of an existing engine. Only applicable if + [solution_type][] is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.discoveryengine.v1alpha.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + + Returns: + Callable[[~.PauseEngineRequest], + Awaitable[~.Engine]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'pause_engine' not in self._stubs: + self._stubs['pause_engine'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.EngineService/PauseEngine', + request_serializer=engine_service.PauseEngineRequest.serialize, + response_deserializer=engine.Engine.deserialize, + ) + return self._stubs['pause_engine'] + + @property + def resume_engine(self) -> Callable[ + [engine_service.ResumeEngineRequest], + Awaitable[engine.Engine]]: + r"""Return a callable for the resume engine method over gRPC. + + Resumes the training of an existing engine. Only applicable if + [solution_type][] is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.discoveryengine.v1alpha.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + + Returns: + Callable[[~.ResumeEngineRequest], + Awaitable[~.Engine]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'resume_engine' not in self._stubs: + self._stubs['resume_engine'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.EngineService/ResumeEngine', + request_serializer=engine_service.ResumeEngineRequest.serialize, + response_deserializer=engine.Engine.deserialize, + ) + return self._stubs['resume_engine'] + + @property + def tune_engine(self) -> Callable[ + [engine_service.TuneEngineRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the tune engine method over gRPC. + + Tunes an existing engine. Only applicable if [solution_type][] + is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.discoveryengine.v1alpha.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + + Returns: + Callable[[~.TuneEngineRequest], + 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 'tune_engine' not in self._stubs: + self._stubs['tune_engine'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.EngineService/TuneEngine', + request_serializer=engine_service.TuneEngineRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['tune_engine'] + + def close(self): + return self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ( + 'EngineServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/rest.py new file mode 100644 index 000000000000..b763e7a23378 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/rest.py @@ -0,0 +1,1543 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.cloud.location import locations_pb2 # type: ignore +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.discoveryengine_v1alpha.types import engine +from google.cloud.discoveryengine_v1alpha.types import engine as gcd_engine +from google.cloud.discoveryengine_v1alpha.types import engine_service +from google.longrunning import operations_pb2 # type: ignore + +from .base import EngineServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class EngineServiceRestInterceptor: + """Interceptor for EngineService. + + 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 EngineServiceRestTransport. + + .. code-block:: python + class MyCustomEngineServiceInterceptor(EngineServiceRestInterceptor): + def pre_create_engine(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_engine(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_engine(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_engine(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_engine(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_engine(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_engines(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_engines(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_pause_engine(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_pause_engine(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_resume_engine(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_resume_engine(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_tune_engine(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_tune_engine(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_engine(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_engine(self, response): + logging.log(f"Received response: {response}") + return response + + transport = EngineServiceRestTransport(interceptor=MyCustomEngineServiceInterceptor()) + client = EngineServiceClient(transport=transport) + + + """ + def pre_create_engine(self, request: engine_service.CreateEngineRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[engine_service.CreateEngineRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_engine + + Override in a subclass to manipulate the request or metadata + before they are sent to the EngineService server. + """ + return request, metadata + + def post_create_engine(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_engine + + Override in a subclass to manipulate the response + after it is returned by the EngineService server but before + it is returned to user code. + """ + return response + def pre_delete_engine(self, request: engine_service.DeleteEngineRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[engine_service.DeleteEngineRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_engine + + Override in a subclass to manipulate the request or metadata + before they are sent to the EngineService server. + """ + return request, metadata + + def post_delete_engine(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_engine + + Override in a subclass to manipulate the response + after it is returned by the EngineService server but before + it is returned to user code. + """ + return response + def pre_get_engine(self, request: engine_service.GetEngineRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[engine_service.GetEngineRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_engine + + Override in a subclass to manipulate the request or metadata + before they are sent to the EngineService server. + """ + return request, metadata + + def post_get_engine(self, response: engine.Engine) -> engine.Engine: + """Post-rpc interceptor for get_engine + + Override in a subclass to manipulate the response + after it is returned by the EngineService server but before + it is returned to user code. + """ + return response + def pre_list_engines(self, request: engine_service.ListEnginesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[engine_service.ListEnginesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_engines + + Override in a subclass to manipulate the request or metadata + before they are sent to the EngineService server. + """ + return request, metadata + + def post_list_engines(self, response: engine_service.ListEnginesResponse) -> engine_service.ListEnginesResponse: + """Post-rpc interceptor for list_engines + + Override in a subclass to manipulate the response + after it is returned by the EngineService server but before + it is returned to user code. + """ + return response + def pre_pause_engine(self, request: engine_service.PauseEngineRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[engine_service.PauseEngineRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for pause_engine + + Override in a subclass to manipulate the request or metadata + before they are sent to the EngineService server. + """ + return request, metadata + + def post_pause_engine(self, response: engine.Engine) -> engine.Engine: + """Post-rpc interceptor for pause_engine + + Override in a subclass to manipulate the response + after it is returned by the EngineService server but before + it is returned to user code. + """ + return response + def pre_resume_engine(self, request: engine_service.ResumeEngineRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[engine_service.ResumeEngineRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for resume_engine + + Override in a subclass to manipulate the request or metadata + before they are sent to the EngineService server. + """ + return request, metadata + + def post_resume_engine(self, response: engine.Engine) -> engine.Engine: + """Post-rpc interceptor for resume_engine + + Override in a subclass to manipulate the response + after it is returned by the EngineService server but before + it is returned to user code. + """ + return response + def pre_tune_engine(self, request: engine_service.TuneEngineRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[engine_service.TuneEngineRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for tune_engine + + Override in a subclass to manipulate the request or metadata + before they are sent to the EngineService server. + """ + return request, metadata + + def post_tune_engine(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for tune_engine + + Override in a subclass to manipulate the response + after it is returned by the EngineService server but before + it is returned to user code. + """ + return response + def pre_update_engine(self, request: engine_service.UpdateEngineRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[engine_service.UpdateEngineRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_engine + + Override in a subclass to manipulate the request or metadata + before they are sent to the EngineService server. + """ + return request, metadata + + def post_update_engine(self, response: gcd_engine.Engine) -> gcd_engine.Engine: + """Post-rpc interceptor for update_engine + + Override in a subclass to manipulate the response + after it is returned by the EngineService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the EngineService 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 EngineService server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the EngineService 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 EngineService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class EngineServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: EngineServiceRestInterceptor + + +class EngineServiceRestTransport(EngineServiceTransport): + """REST backend transport for EngineService. + + Service for managing + [Engine][google.cloud.discoveryengine.v1alpha.Engine] configuration. + + 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 = 'discoveryengine.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[EngineServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or EngineServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1alpha") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CreateEngine(EngineServiceRestStub): + def __hash__(self): + return hash("CreateEngine") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "engineId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: engine_service.CreateEngineRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create engine method over HTTP. + + Args: + request (~.engine_service.CreateEngineRequest): + The request object. Request for + [EngineService.CreateEngine][google.cloud.discoveryengine.v1alpha.EngineService.CreateEngine] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=projects/*/locations/*/collections/*}/engines', + 'body': 'engine', + }, + ] + request, metadata = self._interceptor.pre_create_engine(request, metadata) + pb_request = engine_service.CreateEngineRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_engine(resp) + return resp + + class _DeleteEngine(EngineServiceRestStub): + def __hash__(self): + return hash("DeleteEngine") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: engine_service.DeleteEngineRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete engine method over HTTP. + + Args: + request (~.engine_service.DeleteEngineRequest): + The request object. Request message for + [EngineService.DeleteEngine][google.cloud.discoveryengine.v1alpha.EngineService.DeleteEngine] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_engine(request, metadata) + pb_request = engine_service.DeleteEngineRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_engine(resp) + return resp + + class _GetEngine(EngineServiceRestStub): + def __hash__(self): + return hash("GetEngine") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: engine_service.GetEngineRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> engine.Engine: + r"""Call the get engine method over HTTP. + + Args: + request (~.engine_service.GetEngineRequest): + The request object. Request message for + [EngineService.GetEngine][google.cloud.discoveryengine.v1alpha.EngineService.GetEngine] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.engine.Engine: + Metadata that describes the training and serving + parameters of an + [Engine][google.cloud.discoveryengine.v1alpha.Engine]. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}', + }, + ] + request, metadata = self._interceptor.pre_get_engine(request, metadata) + pb_request = engine_service.GetEngineRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = engine.Engine() + pb_resp = engine.Engine.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_engine(resp) + return resp + + class _ListEngines(EngineServiceRestStub): + def __hash__(self): + return hash("ListEngines") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: engine_service.ListEnginesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> engine_service.ListEnginesResponse: + r"""Call the list engines method over HTTP. + + Args: + request (~.engine_service.ListEnginesRequest): + The request object. Request message for + [EngineService.ListEngines][google.cloud.discoveryengine.v1alpha.EngineService.ListEngines] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.engine_service.ListEnginesResponse: + Response message for + [EngineService.ListEngines][google.cloud.discoveryengine.v1alpha.EngineService.ListEngines] + method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=projects/*/locations/*/collections/*}/engines', + }, + ] + request, metadata = self._interceptor.pre_list_engines(request, metadata) + pb_request = engine_service.ListEnginesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = engine_service.ListEnginesResponse() + pb_resp = engine_service.ListEnginesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_engines(resp) + return resp + + class _PauseEngine(EngineServiceRestStub): + def __hash__(self): + return hash("PauseEngine") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: engine_service.PauseEngineRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> engine.Engine: + r"""Call the pause engine method over HTTP. + + Args: + request (~.engine_service.PauseEngineRequest): + The request object. Request for pausing training of an + engine. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.engine.Engine: + Metadata that describes the training and serving + parameters of an + [Engine][google.cloud.discoveryengine.v1alpha.Engine]. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}:pause', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_pause_engine(request, metadata) + pb_request = engine_service.PauseEngineRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = engine.Engine() + pb_resp = engine.Engine.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_pause_engine(resp) + return resp + + class _ResumeEngine(EngineServiceRestStub): + def __hash__(self): + return hash("ResumeEngine") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: engine_service.ResumeEngineRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> engine.Engine: + r"""Call the resume engine method over HTTP. + + Args: + request (~.engine_service.ResumeEngineRequest): + The request object. Request for resuming training of an + engine. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.engine.Engine: + Metadata that describes the training and serving + parameters of an + [Engine][google.cloud.discoveryengine.v1alpha.Engine]. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}:resume', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_resume_engine(request, metadata) + pb_request = engine_service.ResumeEngineRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = engine.Engine() + pb_resp = engine.Engine.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_resume_engine(resp) + return resp + + class _TuneEngine(EngineServiceRestStub): + def __hash__(self): + return hash("TuneEngine") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: engine_service.TuneEngineRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the tune engine method over HTTP. + + Args: + request (~.engine_service.TuneEngineRequest): + The request object. Request to manually start a tuning + process now (instead of waiting for the + periodically scheduled tuning to + happen). + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}:tune', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_tune_engine(request, metadata) + pb_request = engine_service.TuneEngineRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_tune_engine(resp) + return resp + + class _UpdateEngine(EngineServiceRestStub): + def __hash__(self): + return hash("UpdateEngine") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: engine_service.UpdateEngineRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcd_engine.Engine: + r"""Call the update engine method over HTTP. + + Args: + request (~.engine_service.UpdateEngineRequest): + The request object. Request message for + [EngineService.UpdateEngine][google.cloud.discoveryengine.v1alpha.EngineService.UpdateEngine] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcd_engine.Engine: + Metadata that describes the training and serving + parameters of an + [Engine][google.cloud.discoveryengine.v1alpha.Engine]. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha/{engine.name=projects/*/locations/*/collections/*/engines/*}', + 'body': 'engine', + }, + ] + request, metadata = self._interceptor.pre_update_engine(request, metadata) + pb_request = engine_service.UpdateEngineRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcd_engine.Engine() + pb_resp = gcd_engine.Engine.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_engine(resp) + return resp + + @property + def create_engine(self) -> Callable[ + [engine_service.CreateEngineRequest], + 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._CreateEngine(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_engine(self) -> Callable[ + [engine_service.DeleteEngineRequest], + 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._DeleteEngine(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_engine(self) -> Callable[ + [engine_service.GetEngineRequest], + engine.Engine]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetEngine(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_engines(self) -> Callable[ + [engine_service.ListEnginesRequest], + engine_service.ListEnginesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListEngines(self._session, self._host, self._interceptor) # type: ignore + + @property + def pause_engine(self) -> Callable[ + [engine_service.PauseEngineRequest], + engine.Engine]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._PauseEngine(self._session, self._host, self._interceptor) # type: ignore + + @property + def resume_engine(self) -> Callable[ + [engine_service.ResumeEngineRequest], + engine.Engine]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ResumeEngine(self._session, self._host, self._interceptor) # type: ignore + + @property + def tune_engine(self) -> Callable[ + [engine_service.TuneEngineRequest], + 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._TuneEngine(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_engine(self) -> Callable[ + [engine_service.UpdateEngineRequest], + gcd_engine.Engine]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateEngine(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(EngineServiceRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(EngineServiceRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'EngineServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/__init__.py new file mode 100644 index 000000000000..ad8f24a9e055 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import RecommendationServiceClient +from .async_client import RecommendationServiceAsyncClient + +__all__ = ( + 'RecommendationServiceClient', + 'RecommendationServiceAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/async_client.py new file mode 100644 index 000000000000..33cfc476e3a6 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/async_client.py @@ -0,0 +1,389 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import recommendation_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .transports.base import RecommendationServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import RecommendationServiceGrpcAsyncIOTransport +from .client import RecommendationServiceClient + + +class RecommendationServiceAsyncClient: + """Service for making recommendations.""" + + _client: RecommendationServiceClient + + DEFAULT_ENDPOINT = RecommendationServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = RecommendationServiceClient.DEFAULT_MTLS_ENDPOINT + + document_path = staticmethod(RecommendationServiceClient.document_path) + parse_document_path = staticmethod(RecommendationServiceClient.parse_document_path) + serving_config_path = staticmethod(RecommendationServiceClient.serving_config_path) + parse_serving_config_path = staticmethod(RecommendationServiceClient.parse_serving_config_path) + common_billing_account_path = staticmethod(RecommendationServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(RecommendationServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(RecommendationServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(RecommendationServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(RecommendationServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(RecommendationServiceClient.parse_common_organization_path) + common_project_path = staticmethod(RecommendationServiceClient.common_project_path) + parse_common_project_path = staticmethod(RecommendationServiceClient.parse_common_project_path) + common_location_path = staticmethod(RecommendationServiceClient.common_location_path) + parse_common_location_path = staticmethod(RecommendationServiceClient.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: + RecommendationServiceAsyncClient: The constructed client. + """ + return RecommendationServiceClient.from_service_account_info.__func__(RecommendationServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RecommendationServiceAsyncClient: The constructed client. + """ + return RecommendationServiceClient.from_service_account_file.__func__(RecommendationServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return RecommendationServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> RecommendationServiceTransport: + """Returns the transport used by the client instance. + + Returns: + RecommendationServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(RecommendationServiceClient).get_transport_class, type(RecommendationServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, RecommendationServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the recommendation 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 (Union[str, ~.RecommendationServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = RecommendationServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def recommend(self, + request: Optional[Union[recommendation_service.RecommendRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> recommendation_service.RecommendResponse: + r"""Makes a recommendation, which requires a contextual + user event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_recommend(): + # Create a client + client = discoveryengine_v1alpha.RecommendationServiceAsyncClient() + + # Initialize request argument(s) + user_event = discoveryengine_v1alpha.UserEvent() + user_event.event_type = "event_type_value" + user_event.user_pseudo_id = "user_pseudo_id_value" + + request = discoveryengine_v1alpha.RecommendRequest( + serving_config="serving_config_value", + user_event=user_event, + ) + + # Make the request + response = await client.recommend(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.RecommendRequest, dict]]): + The request object. Request message for Recommend method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.RecommendResponse: + Response message for Recommend + method. + + """ + # Create or coerce a protobuf request object. + request = recommendation_service.RecommendRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.recommend, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config", request.serving_config), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "RecommendationServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "RecommendationServiceAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/client.py new file mode 100644 index 000000000000..9fd6b59e83b4 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/client.py @@ -0,0 +1,606 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import recommendation_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .transports.base import RecommendationServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import RecommendationServiceGrpcTransport +from .transports.grpc_asyncio import RecommendationServiceGrpcAsyncIOTransport +from .transports.rest import RecommendationServiceRestTransport + + +class RecommendationServiceClientMeta(type): + """Metaclass for the RecommendationService 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[RecommendationServiceTransport]] + _transport_registry["grpc"] = RecommendationServiceGrpcTransport + _transport_registry["grpc_asyncio"] = RecommendationServiceGrpcAsyncIOTransport + _transport_registry["rest"] = RecommendationServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[RecommendationServiceTransport]: + """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 RecommendationServiceClient(metaclass=RecommendationServiceClientMeta): + """Service for making recommendations.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RecommendationServiceClient: 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: + RecommendationServiceClient: 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) -> RecommendationServiceTransport: + """Returns the transport used by the client instance. + + Returns: + RecommendationServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def document_path(project: str,location: str,data_store: str,branch: str,document: str,) -> str: + """Returns a fully-qualified document string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) + + @staticmethod + def parse_document_path(path: str) -> Dict[str,str]: + """Parses a document path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)/documents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def serving_config_path(project: str,location: str,data_store: str,serving_config: str,) -> str: + """Returns a fully-qualified serving_config string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/servingConfigs/{serving_config}".format(project=project, location=location, data_store=data_store, serving_config=serving_config, ) + + @staticmethod + def parse_serving_config_path(path: str) -> Dict[str,str]: + """Parses a serving_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/servingConfigs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, RecommendationServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the recommendation 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 (Union[str, RecommendationServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, RecommendationServiceTransport): + # transport is a RecommendationServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def recommend(self, + request: Optional[Union[recommendation_service.RecommendRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> recommendation_service.RecommendResponse: + r"""Makes a recommendation, which requires a contextual + user event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_recommend(): + # Create a client + client = discoveryengine_v1alpha.RecommendationServiceClient() + + # Initialize request argument(s) + user_event = discoveryengine_v1alpha.UserEvent() + user_event.event_type = "event_type_value" + user_event.user_pseudo_id = "user_pseudo_id_value" + + request = discoveryengine_v1alpha.RecommendRequest( + serving_config="serving_config_value", + user_event=user_event, + ) + + # Make the request + response = client.recommend(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.RecommendRequest, dict]): + The request object. Request message for Recommend method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.RecommendResponse: + Response message for Recommend + method. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a recommendation_service.RecommendRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, recommendation_service.RecommendRequest): + request = recommendation_service.RecommendRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.recommend] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config", request.serving_config), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "RecommendationServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "RecommendationServiceClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/__init__.py new file mode 100644 index 000000000000..ce9f9edfd346 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import RecommendationServiceTransport +from .grpc import RecommendationServiceGrpcTransport +from .grpc_asyncio import RecommendationServiceGrpcAsyncIOTransport +from .rest import RecommendationServiceRestTransport +from .rest import RecommendationServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[RecommendationServiceTransport]] +_transport_registry['grpc'] = RecommendationServiceGrpcTransport +_transport_registry['grpc_asyncio'] = RecommendationServiceGrpcAsyncIOTransport +_transport_registry['rest'] = RecommendationServiceRestTransport + +__all__ = ( + 'RecommendationServiceTransport', + 'RecommendationServiceGrpcTransport', + 'RecommendationServiceGrpcAsyncIOTransport', + 'RecommendationServiceRestTransport', + 'RecommendationServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/base.py new file mode 100644 index 000000000000..d351956c74c7 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/base.py @@ -0,0 +1,168 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import recommendation_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class RecommendationServiceTransport(abc.ABC): + """Abstract transport class for RecommendationService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'discoveryengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.recommend: gapic_v1.method.wrap_method( + self.recommend, + 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 recommend(self) -> Callable[ + [recommendation_service.RecommendRequest], + Union[ + recommendation_service.RecommendResponse, + Awaitable[recommendation_service.RecommendResponse] + ]]: + 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 kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'RecommendationServiceTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/grpc.py new file mode 100644 index 000000000000..98c679fa7058 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/grpc.py @@ -0,0 +1,303 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import recommendation_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import RecommendationServiceTransport, DEFAULT_CLIENT_INFO + + +class RecommendationServiceGrpcTransport(RecommendationServiceTransport): + """gRPC backend transport for RecommendationService. + + Service for making recommendations. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def recommend(self) -> Callable[ + [recommendation_service.RecommendRequest], + recommendation_service.RecommendResponse]: + r"""Return a callable for the recommend method over gRPC. + + Makes a recommendation, which requires a contextual + user event. + + Returns: + Callable[[~.RecommendRequest], + ~.RecommendResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'recommend' not in self._stubs: + self._stubs['recommend'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.RecommendationService/Recommend', + request_serializer=recommendation_service.RecommendRequest.serialize, + response_deserializer=recommendation_service.RecommendResponse.deserialize, + ) + return self._stubs['recommend'] + + def close(self): + self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'RecommendationServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..3045bfc4e95a --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/grpc_asyncio.py @@ -0,0 +1,302 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import recommendation_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import RecommendationServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import RecommendationServiceGrpcTransport + + +class RecommendationServiceGrpcAsyncIOTransport(RecommendationServiceTransport): + """gRPC AsyncIO backend transport for RecommendationService. + + Service for making recommendations. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def recommend(self) -> Callable[ + [recommendation_service.RecommendRequest], + Awaitable[recommendation_service.RecommendResponse]]: + r"""Return a callable for the recommend method over gRPC. + + Makes a recommendation, which requires a contextual + user event. + + Returns: + Callable[[~.RecommendRequest], + Awaitable[~.RecommendResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'recommend' not in self._stubs: + self._stubs['recommend'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.RecommendationService/Recommend', + request_serializer=recommendation_service.RecommendRequest.serialize, + response_deserializer=recommendation_service.RecommendResponse.deserialize, + ) + return self._stubs['recommend'] + + def close(self): + return self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ( + 'RecommendationServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/rest.py new file mode 100644 index 000000000000..10eeeb90c39f --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/rest.py @@ -0,0 +1,578 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.cloud.location import locations_pb2 # type: ignore +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.discoveryengine_v1alpha.types import recommendation_service +from google.longrunning import operations_pb2 # type: ignore + +from .base import RecommendationServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class RecommendationServiceRestInterceptor: + """Interceptor for RecommendationService. + + 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 RecommendationServiceRestTransport. + + .. code-block:: python + class MyCustomRecommendationServiceInterceptor(RecommendationServiceRestInterceptor): + def pre_recommend(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_recommend(self, response): + logging.log(f"Received response: {response}") + return response + + transport = RecommendationServiceRestTransport(interceptor=MyCustomRecommendationServiceInterceptor()) + client = RecommendationServiceClient(transport=transport) + + + """ + def pre_recommend(self, request: recommendation_service.RecommendRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[recommendation_service.RecommendRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for recommend + + Override in a subclass to manipulate the request or metadata + before they are sent to the RecommendationService server. + """ + return request, metadata + + def post_recommend(self, response: recommendation_service.RecommendResponse) -> recommendation_service.RecommendResponse: + """Post-rpc interceptor for recommend + + Override in a subclass to manipulate the response + after it is returned by the RecommendationService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the RecommendationService 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 RecommendationService server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the RecommendationService 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 RecommendationService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class RecommendationServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: RecommendationServiceRestInterceptor + + +class RecommendationServiceRestTransport(RecommendationServiceTransport): + """REST backend transport for RecommendationService. + + Service for making recommendations. + + 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 = 'discoveryengine.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[RecommendationServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or RecommendationServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _Recommend(RecommendationServiceRestStub): + def __hash__(self): + return hash("Recommend") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: recommendation_service.RecommendRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> recommendation_service.RecommendResponse: + r"""Call the recommend method over HTTP. + + Args: + request (~.recommendation_service.RecommendRequest): + The request object. Request message for Recommend method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.recommendation_service.RecommendResponse: + Response message for Recommend + method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{serving_config=projects/*/locations/*/dataStores/*/servingConfigs/*}:recommend', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha/{serving_config=projects/*/locations/*/collections/*/dataStores/*/servingConfigs/*}:recommend', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha/{serving_config=projects/*/locations/*/collections/*/engines/*/servingConfigs/*}:recommend', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_recommend(request, metadata) + pb_request = recommendation_service.RecommendRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = recommendation_service.RecommendResponse() + pb_resp = recommendation_service.RecommendResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_recommend(resp) + return resp + + @property + def recommend(self) -> Callable[ + [recommendation_service.RecommendRequest], + recommendation_service.RecommendResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Recommend(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(RecommendationServiceRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(RecommendationServiceRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'RecommendationServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/__init__.py new file mode 100644 index 000000000000..4e9455a921b6 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import SchemaServiceClient +from .async_client import SchemaServiceAsyncClient + +__all__ = ( + 'SchemaServiceClient', + 'SchemaServiceAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/async_client.py new file mode 100644 index 000000000000..d31db699cf92 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/async_client.py @@ -0,0 +1,902 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.discoveryengine_v1alpha.services.schema_service import pagers +from google.cloud.discoveryengine_v1alpha.types import schema +from google.cloud.discoveryengine_v1alpha.types import schema as gcd_schema +from google.cloud.discoveryengine_v1alpha.types import schema_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from .transports.base import SchemaServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SchemaServiceGrpcAsyncIOTransport +from .client import SchemaServiceClient + + +class SchemaServiceAsyncClient: + """Service for managing + [Schema][google.cloud.discoveryengine.v1alpha.Schema]s. + """ + + _client: SchemaServiceClient + + DEFAULT_ENDPOINT = SchemaServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SchemaServiceClient.DEFAULT_MTLS_ENDPOINT + + data_store_path = staticmethod(SchemaServiceClient.data_store_path) + parse_data_store_path = staticmethod(SchemaServiceClient.parse_data_store_path) + schema_path = staticmethod(SchemaServiceClient.schema_path) + parse_schema_path = staticmethod(SchemaServiceClient.parse_schema_path) + common_billing_account_path = staticmethod(SchemaServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SchemaServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SchemaServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(SchemaServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(SchemaServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(SchemaServiceClient.parse_common_organization_path) + common_project_path = staticmethod(SchemaServiceClient.common_project_path) + parse_common_project_path = staticmethod(SchemaServiceClient.parse_common_project_path) + common_location_path = staticmethod(SchemaServiceClient.common_location_path) + parse_common_location_path = staticmethod(SchemaServiceClient.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: + SchemaServiceAsyncClient: The constructed client. + """ + return SchemaServiceClient.from_service_account_info.__func__(SchemaServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SchemaServiceAsyncClient: The constructed client. + """ + return SchemaServiceClient.from_service_account_file.__func__(SchemaServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return SchemaServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SchemaServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SchemaServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(SchemaServiceClient).get_transport_class, type(SchemaServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, SchemaServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the schema 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 (Union[str, ~.SchemaServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = SchemaServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def get_schema(self, + request: Optional[Union[schema_service.GetSchemaRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> schema.Schema: + r"""Gets a [Schema][google.cloud.discoveryengine.v1alpha.Schema]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_get_schema(): + # Create a client + client = discoveryengine_v1alpha.SchemaServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.GetSchemaRequest( + name="name_value", + ) + + # Make the request + response = await client.get_schema(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.GetSchemaRequest, dict]]): + The request object. Request message for + [SchemaService.GetSchema][google.cloud.discoveryengine.v1alpha.SchemaService.GetSchema] + method. + name (:class:`str`): + Required. The full resource name of the schema, in the + format of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.Schema: + Defines the structure and layout of a + type of document data. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = schema_service.GetSchemaRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_schema, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_schemas(self, + request: Optional[Union[schema_service.ListSchemasRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSchemasAsyncPager: + r"""Gets a list of + [Schema][google.cloud.discoveryengine.v1alpha.Schema]s. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_list_schemas(): + # Create a client + client = discoveryengine_v1alpha.SchemaServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ListSchemasRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_schemas(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.ListSchemasRequest, dict]]): + The request object. Request message for + [SchemaService.ListSchemas][google.cloud.discoveryengine.v1alpha.SchemaService.ListSchemas] + method. + parent (:class:`str`): + Required. The parent data store resource name, in the + format of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.services.schema_service.pagers.ListSchemasAsyncPager: + Response message for + [SchemaService.ListSchemas][google.cloud.discoveryengine.v1alpha.SchemaService.ListSchemas] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = schema_service.ListSchemasRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_schemas, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSchemasAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_schema(self, + request: Optional[Union[schema_service.CreateSchemaRequest, dict]] = None, + *, + parent: Optional[str] = None, + schema: Optional[gcd_schema.Schema] = None, + schema_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a [Schema][google.cloud.discoveryengine.v1alpha.Schema]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_create_schema(): + # Create a client + client = discoveryengine_v1alpha.SchemaServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.CreateSchemaRequest( + parent="parent_value", + schema_id="schema_id_value", + ) + + # Make the request + operation = client.create_schema(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.CreateSchemaRequest, dict]]): + The request object. Request message for + [SchemaService.CreateSchema][google.cloud.discoveryengine.v1alpha.SchemaService.CreateSchema] + method. + parent (:class:`str`): + Required. The parent data store resource name, in the + format of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + schema (:class:`google.cloud.discoveryengine_v1alpha.types.Schema`): + Required. The + [Schema][google.cloud.discoveryengine.v1alpha.Schema] to + create. + + This corresponds to the ``schema`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + schema_id (:class:`str`): + Required. The ID to use for the + [Schema][google.cloud.discoveryengine.v1alpha.Schema], + which will become the final component of the + [Schema.name][google.cloud.discoveryengine.v1alpha.Schema.name]. + + This field should conform to + `RFC-1034 `__ + standard with a length limit of 63 characters. + + This corresponds to the ``schema_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.discoveryengine_v1alpha.types.Schema` + Defines the structure and layout of a type of document + data. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, schema, schema_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = schema_service.CreateSchemaRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if schema is not None: + request.schema = schema + if schema_id is not None: + request.schema_id = schema_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_schema, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcd_schema.Schema, + metadata_type=schema_service.CreateSchemaMetadata, + ) + + # Done; return the response. + return response + + async def update_schema(self, + request: Optional[Union[schema_service.UpdateSchemaRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates a [Schema][google.cloud.discoveryengine.v1alpha.Schema]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_update_schema(): + # Create a client + client = discoveryengine_v1alpha.SchemaServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.UpdateSchemaRequest( + ) + + # Make the request + operation = client.update_schema(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.UpdateSchemaRequest, dict]]): + The request object. Request message for + [SchemaService.UpdateSchema][google.cloud.discoveryengine.v1alpha.SchemaService.UpdateSchema] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.discoveryengine_v1alpha.types.Schema` + Defines the structure and layout of a type of document + data. + + """ + # Create or coerce a protobuf request object. + request = schema_service.UpdateSchemaRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_schema, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("schema.name", request.schema.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + schema.Schema, + metadata_type=schema_service.UpdateSchemaMetadata, + ) + + # Done; return the response. + return response + + async def delete_schema(self, + request: Optional[Union[schema_service.DeleteSchemaRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a [Schema][google.cloud.discoveryengine.v1alpha.Schema]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_delete_schema(): + # Create a client + client = discoveryengine_v1alpha.SchemaServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.DeleteSchemaRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_schema(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.DeleteSchemaRequest, dict]]): + The request object. Request message for + [SchemaService.DeleteSchema][google.cloud.discoveryengine.v1alpha.SchemaService.DeleteSchema] + method. + name (:class:`str`): + Required. The full resource name of the schema, in the + format of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = schema_service.DeleteSchemaRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_schema, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=schema_service.DeleteSchemaMetadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "SchemaServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "SchemaServiceAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/client.py new file mode 100644 index 000000000000..760fb509e9f3 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/client.py @@ -0,0 +1,1119 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.discoveryengine_v1alpha.services.schema_service import pagers +from google.cloud.discoveryengine_v1alpha.types import schema +from google.cloud.discoveryengine_v1alpha.types import schema as gcd_schema +from google.cloud.discoveryengine_v1alpha.types import schema_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from .transports.base import SchemaServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SchemaServiceGrpcTransport +from .transports.grpc_asyncio import SchemaServiceGrpcAsyncIOTransport +from .transports.rest import SchemaServiceRestTransport + + +class SchemaServiceClientMeta(type): + """Metaclass for the SchemaService 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[SchemaServiceTransport]] + _transport_registry["grpc"] = SchemaServiceGrpcTransport + _transport_registry["grpc_asyncio"] = SchemaServiceGrpcAsyncIOTransport + _transport_registry["rest"] = SchemaServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[SchemaServiceTransport]: + """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 SchemaServiceClient(metaclass=SchemaServiceClientMeta): + """Service for managing + [Schema][google.cloud.discoveryengine.v1alpha.Schema]s. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SchemaServiceClient: 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: + SchemaServiceClient: 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) -> SchemaServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SchemaServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def data_store_path(project: str,location: str,data_store: str,) -> str: + """Returns a fully-qualified data_store string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) + + @staticmethod + def parse_data_store_path(path: str) -> Dict[str,str]: + """Parses a data_store path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def schema_path(project: str,location: str,data_store: str,schema: str,) -> str: + """Returns a fully-qualified schema string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/schemas/{schema}".format(project=project, location=location, data_store=data_store, schema=schema, ) + + @staticmethod + def parse_schema_path(path: str) -> Dict[str,str]: + """Parses a schema path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/schemas/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, SchemaServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the schema 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 (Union[str, SchemaServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, SchemaServiceTransport): + # transport is a SchemaServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def get_schema(self, + request: Optional[Union[schema_service.GetSchemaRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> schema.Schema: + r"""Gets a [Schema][google.cloud.discoveryengine.v1alpha.Schema]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_get_schema(): + # Create a client + client = discoveryengine_v1alpha.SchemaServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.GetSchemaRequest( + name="name_value", + ) + + # Make the request + response = client.get_schema(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.GetSchemaRequest, dict]): + The request object. Request message for + [SchemaService.GetSchema][google.cloud.discoveryengine.v1alpha.SchemaService.GetSchema] + method. + name (str): + Required. The full resource name of the schema, in the + format of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.Schema: + Defines the structure and layout of a + type of document data. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a schema_service.GetSchemaRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, schema_service.GetSchemaRequest): + request = schema_service.GetSchemaRequest(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_schema] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_schemas(self, + request: Optional[Union[schema_service.ListSchemasRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSchemasPager: + r"""Gets a list of + [Schema][google.cloud.discoveryengine.v1alpha.Schema]s. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_list_schemas(): + # Create a client + client = discoveryengine_v1alpha.SchemaServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ListSchemasRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_schemas(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.ListSchemasRequest, dict]): + The request object. Request message for + [SchemaService.ListSchemas][google.cloud.discoveryengine.v1alpha.SchemaService.ListSchemas] + method. + parent (str): + Required. The parent data store resource name, in the + format of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.services.schema_service.pagers.ListSchemasPager: + Response message for + [SchemaService.ListSchemas][google.cloud.discoveryengine.v1alpha.SchemaService.ListSchemas] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a schema_service.ListSchemasRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, schema_service.ListSchemasRequest): + request = schema_service.ListSchemasRequest(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_schemas] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListSchemasPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_schema(self, + request: Optional[Union[schema_service.CreateSchemaRequest, dict]] = None, + *, + parent: Optional[str] = None, + schema: Optional[gcd_schema.Schema] = None, + schema_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a [Schema][google.cloud.discoveryengine.v1alpha.Schema]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_create_schema(): + # Create a client + client = discoveryengine_v1alpha.SchemaServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.CreateSchemaRequest( + parent="parent_value", + schema_id="schema_id_value", + ) + + # Make the request + operation = client.create_schema(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.CreateSchemaRequest, dict]): + The request object. Request message for + [SchemaService.CreateSchema][google.cloud.discoveryengine.v1alpha.SchemaService.CreateSchema] + method. + parent (str): + Required. The parent data store resource name, in the + format of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + schema (google.cloud.discoveryengine_v1alpha.types.Schema): + Required. The + [Schema][google.cloud.discoveryengine.v1alpha.Schema] to + create. + + This corresponds to the ``schema`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + schema_id (str): + Required. The ID to use for the + [Schema][google.cloud.discoveryengine.v1alpha.Schema], + which will become the final component of the + [Schema.name][google.cloud.discoveryengine.v1alpha.Schema.name]. + + This field should conform to + `RFC-1034 `__ + standard with a length limit of 63 characters. + + This corresponds to the ``schema_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.discoveryengine_v1alpha.types.Schema` + Defines the structure and layout of a type of document + data. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, schema, schema_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a schema_service.CreateSchemaRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, schema_service.CreateSchemaRequest): + request = schema_service.CreateSchemaRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if schema is not None: + request.schema = schema + if schema_id is not None: + request.schema_id = schema_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_schema] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gcd_schema.Schema, + metadata_type=schema_service.CreateSchemaMetadata, + ) + + # Done; return the response. + return response + + def update_schema(self, + request: Optional[Union[schema_service.UpdateSchemaRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates a [Schema][google.cloud.discoveryengine.v1alpha.Schema]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_update_schema(): + # Create a client + client = discoveryengine_v1alpha.SchemaServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.UpdateSchemaRequest( + ) + + # Make the request + operation = client.update_schema(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.UpdateSchemaRequest, dict]): + The request object. Request message for + [SchemaService.UpdateSchema][google.cloud.discoveryengine.v1alpha.SchemaService.UpdateSchema] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.discoveryengine_v1alpha.types.Schema` + Defines the structure and layout of a type of document + data. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a schema_service.UpdateSchemaRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, schema_service.UpdateSchemaRequest): + request = schema_service.UpdateSchemaRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_schema] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("schema.name", request.schema.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + schema.Schema, + metadata_type=schema_service.UpdateSchemaMetadata, + ) + + # Done; return the response. + return response + + def delete_schema(self, + request: Optional[Union[schema_service.DeleteSchemaRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a [Schema][google.cloud.discoveryengine.v1alpha.Schema]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_delete_schema(): + # Create a client + client = discoveryengine_v1alpha.SchemaServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.DeleteSchemaRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_schema(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.DeleteSchemaRequest, dict]): + The request object. Request message for + [SchemaService.DeleteSchema][google.cloud.discoveryengine.v1alpha.SchemaService.DeleteSchema] + method. + name (str): + Required. The full resource name of the schema, in the + format of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a schema_service.DeleteSchemaRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, schema_service.DeleteSchemaRequest): + request = schema_service.DeleteSchemaRequest(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_schema] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=schema_service.DeleteSchemaMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "SchemaServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "SchemaServiceClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/pagers.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/pagers.py new file mode 100644 index 000000000000..34de8e6acea7 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.discoveryengine_v1alpha.types import schema +from google.cloud.discoveryengine_v1alpha.types import schema_service + + +class ListSchemasPager: + """A pager for iterating through ``list_schemas`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1alpha.types.ListSchemasResponse` object, and + provides an ``__iter__`` method to iterate through its + ``schemas`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSchemas`` requests and continue to iterate + through the ``schemas`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1alpha.types.ListSchemasResponse` + 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[..., schema_service.ListSchemasResponse], + request: schema_service.ListSchemasRequest, + response: schema_service.ListSchemasResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.discoveryengine_v1alpha.types.ListSchemasRequest): + The initial request object. + response (google.cloud.discoveryengine_v1alpha.types.ListSchemasResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = schema_service.ListSchemasRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[schema_service.ListSchemasResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[schema.Schema]: + for page in self.pages: + yield from page.schemas + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSchemasAsyncPager: + """A pager for iterating through ``list_schemas`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1alpha.types.ListSchemasResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``schemas`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSchemas`` requests and continue to iterate + through the ``schemas`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1alpha.types.ListSchemasResponse` + 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[schema_service.ListSchemasResponse]], + request: schema_service.ListSchemasRequest, + response: schema_service.ListSchemasResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.discoveryengine_v1alpha.types.ListSchemasRequest): + The initial request object. + response (google.cloud.discoveryengine_v1alpha.types.ListSchemasResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = schema_service.ListSchemasRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[schema_service.ListSchemasResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[schema.Schema]: + async def async_generator(): + async for page in self.pages: + for response in page.schemas: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/__init__.py new file mode 100644 index 000000000000..d5ebd14e657b --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import SchemaServiceTransport +from .grpc import SchemaServiceGrpcTransport +from .grpc_asyncio import SchemaServiceGrpcAsyncIOTransport +from .rest import SchemaServiceRestTransport +from .rest import SchemaServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SchemaServiceTransport]] +_transport_registry['grpc'] = SchemaServiceGrpcTransport +_transport_registry['grpc_asyncio'] = SchemaServiceGrpcAsyncIOTransport +_transport_registry['rest'] = SchemaServiceRestTransport + +__all__ = ( + 'SchemaServiceTransport', + 'SchemaServiceGrpcTransport', + 'SchemaServiceGrpcAsyncIOTransport', + 'SchemaServiceRestTransport', + 'SchemaServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/base.py new file mode 100644 index 000000000000..74feb3ddf1e2 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/base.py @@ -0,0 +1,231 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import schema +from google.cloud.discoveryengine_v1alpha.types import schema_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class SchemaServiceTransport(abc.ABC): + """Abstract transport class for SchemaService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'discoveryengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_schema: gapic_v1.method.wrap_method( + self.get_schema, + default_timeout=None, + client_info=client_info, + ), + self.list_schemas: gapic_v1.method.wrap_method( + self.list_schemas, + default_timeout=None, + client_info=client_info, + ), + self.create_schema: gapic_v1.method.wrap_method( + self.create_schema, + default_timeout=None, + client_info=client_info, + ), + self.update_schema: gapic_v1.method.wrap_method( + self.update_schema, + default_timeout=None, + client_info=client_info, + ), + self.delete_schema: gapic_v1.method.wrap_method( + self.delete_schema, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def get_schema(self) -> Callable[ + [schema_service.GetSchemaRequest], + Union[ + schema.Schema, + Awaitable[schema.Schema] + ]]: + raise NotImplementedError() + + @property + def list_schemas(self) -> Callable[ + [schema_service.ListSchemasRequest], + Union[ + schema_service.ListSchemasResponse, + Awaitable[schema_service.ListSchemasResponse] + ]]: + raise NotImplementedError() + + @property + def create_schema(self) -> Callable[ + [schema_service.CreateSchemaRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_schema(self) -> Callable[ + [schema_service.UpdateSchemaRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_schema(self) -> Callable[ + [schema_service.DeleteSchemaRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'SchemaServiceTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/grpc.py new file mode 100644 index 000000000000..caa7905828f2 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/grpc.py @@ -0,0 +1,427 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import schema +from google.cloud.discoveryengine_v1alpha.types import schema_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import SchemaServiceTransport, DEFAULT_CLIENT_INFO + + +class SchemaServiceGrpcTransport(SchemaServiceTransport): + """gRPC backend transport for SchemaService. + + Service for managing + [Schema][google.cloud.discoveryengine.v1alpha.Schema]s. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def get_schema(self) -> Callable[ + [schema_service.GetSchemaRequest], + schema.Schema]: + r"""Return a callable for the get schema method over gRPC. + + Gets a [Schema][google.cloud.discoveryengine.v1alpha.Schema]. + + Returns: + Callable[[~.GetSchemaRequest], + ~.Schema]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_schema' not in self._stubs: + self._stubs['get_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.SchemaService/GetSchema', + request_serializer=schema_service.GetSchemaRequest.serialize, + response_deserializer=schema.Schema.deserialize, + ) + return self._stubs['get_schema'] + + @property + def list_schemas(self) -> Callable[ + [schema_service.ListSchemasRequest], + schema_service.ListSchemasResponse]: + r"""Return a callable for the list schemas method over gRPC. + + Gets a list of + [Schema][google.cloud.discoveryengine.v1alpha.Schema]s. + + Returns: + Callable[[~.ListSchemasRequest], + ~.ListSchemasResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_schemas' not in self._stubs: + self._stubs['list_schemas'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.SchemaService/ListSchemas', + request_serializer=schema_service.ListSchemasRequest.serialize, + response_deserializer=schema_service.ListSchemasResponse.deserialize, + ) + return self._stubs['list_schemas'] + + @property + def create_schema(self) -> Callable[ + [schema_service.CreateSchemaRequest], + operations_pb2.Operation]: + r"""Return a callable for the create schema method over gRPC. + + Creates a [Schema][google.cloud.discoveryengine.v1alpha.Schema]. + + Returns: + Callable[[~.CreateSchemaRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_schema' not in self._stubs: + self._stubs['create_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.SchemaService/CreateSchema', + request_serializer=schema_service.CreateSchemaRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_schema'] + + @property + def update_schema(self) -> Callable[ + [schema_service.UpdateSchemaRequest], + operations_pb2.Operation]: + r"""Return a callable for the update schema method over gRPC. + + Updates a [Schema][google.cloud.discoveryengine.v1alpha.Schema]. + + Returns: + Callable[[~.UpdateSchemaRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_schema' not in self._stubs: + self._stubs['update_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.SchemaService/UpdateSchema', + request_serializer=schema_service.UpdateSchemaRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_schema'] + + @property + def delete_schema(self) -> Callable[ + [schema_service.DeleteSchemaRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete schema method over gRPC. + + Deletes a [Schema][google.cloud.discoveryengine.v1alpha.Schema]. + + Returns: + Callable[[~.DeleteSchemaRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_schema' not in self._stubs: + self._stubs['delete_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.SchemaService/DeleteSchema', + request_serializer=schema_service.DeleteSchemaRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_schema'] + + def close(self): + self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'SchemaServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..ded95061acb4 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/grpc_asyncio.py @@ -0,0 +1,426 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import schema +from google.cloud.discoveryengine_v1alpha.types import schema_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import SchemaServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import SchemaServiceGrpcTransport + + +class SchemaServiceGrpcAsyncIOTransport(SchemaServiceTransport): + """gRPC AsyncIO backend transport for SchemaService. + + Service for managing + [Schema][google.cloud.discoveryengine.v1alpha.Schema]s. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def get_schema(self) -> Callable[ + [schema_service.GetSchemaRequest], + Awaitable[schema.Schema]]: + r"""Return a callable for the get schema method over gRPC. + + Gets a [Schema][google.cloud.discoveryengine.v1alpha.Schema]. + + Returns: + Callable[[~.GetSchemaRequest], + Awaitable[~.Schema]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_schema' not in self._stubs: + self._stubs['get_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.SchemaService/GetSchema', + request_serializer=schema_service.GetSchemaRequest.serialize, + response_deserializer=schema.Schema.deserialize, + ) + return self._stubs['get_schema'] + + @property + def list_schemas(self) -> Callable[ + [schema_service.ListSchemasRequest], + Awaitable[schema_service.ListSchemasResponse]]: + r"""Return a callable for the list schemas method over gRPC. + + Gets a list of + [Schema][google.cloud.discoveryengine.v1alpha.Schema]s. + + Returns: + Callable[[~.ListSchemasRequest], + Awaitable[~.ListSchemasResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_schemas' not in self._stubs: + self._stubs['list_schemas'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.SchemaService/ListSchemas', + request_serializer=schema_service.ListSchemasRequest.serialize, + response_deserializer=schema_service.ListSchemasResponse.deserialize, + ) + return self._stubs['list_schemas'] + + @property + def create_schema(self) -> Callable[ + [schema_service.CreateSchemaRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create schema method over gRPC. + + Creates a [Schema][google.cloud.discoveryengine.v1alpha.Schema]. + + Returns: + Callable[[~.CreateSchemaRequest], + 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_schema' not in self._stubs: + self._stubs['create_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.SchemaService/CreateSchema', + request_serializer=schema_service.CreateSchemaRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_schema'] + + @property + def update_schema(self) -> Callable[ + [schema_service.UpdateSchemaRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update schema method over gRPC. + + Updates a [Schema][google.cloud.discoveryengine.v1alpha.Schema]. + + Returns: + Callable[[~.UpdateSchemaRequest], + 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_schema' not in self._stubs: + self._stubs['update_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.SchemaService/UpdateSchema', + request_serializer=schema_service.UpdateSchemaRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_schema'] + + @property + def delete_schema(self) -> Callable[ + [schema_service.DeleteSchemaRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete schema method over gRPC. + + Deletes a [Schema][google.cloud.discoveryengine.v1alpha.Schema]. + + Returns: + Callable[[~.DeleteSchemaRequest], + 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_schema' not in self._stubs: + self._stubs['delete_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.SchemaService/DeleteSchema', + request_serializer=schema_service.DeleteSchemaRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_schema'] + + def close(self): + return self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ( + 'SchemaServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/rest.py new file mode 100644 index 000000000000..717527b50048 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/rest.py @@ -0,0 +1,1192 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.cloud.location import locations_pb2 # type: ignore +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.discoveryengine_v1alpha.types import schema +from google.cloud.discoveryengine_v1alpha.types import schema_service +from google.longrunning import operations_pb2 # type: ignore + +from .base import SchemaServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class SchemaServiceRestInterceptor: + """Interceptor for SchemaService. + + 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 SchemaServiceRestTransport. + + .. code-block:: python + class MyCustomSchemaServiceInterceptor(SchemaServiceRestInterceptor): + def pre_create_schema(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_schema(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_schema(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_schema(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_schema(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_schema(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_schemas(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_schemas(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_schema(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_schema(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SchemaServiceRestTransport(interceptor=MyCustomSchemaServiceInterceptor()) + client = SchemaServiceClient(transport=transport) + + + """ + def pre_create_schema(self, request: schema_service.CreateSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[schema_service.CreateSchemaRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_schema + + Override in a subclass to manipulate the request or metadata + before they are sent to the SchemaService server. + """ + return request, metadata + + def post_create_schema(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_schema + + Override in a subclass to manipulate the response + after it is returned by the SchemaService server but before + it is returned to user code. + """ + return response + def pre_delete_schema(self, request: schema_service.DeleteSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[schema_service.DeleteSchemaRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_schema + + Override in a subclass to manipulate the request or metadata + before they are sent to the SchemaService server. + """ + return request, metadata + + def post_delete_schema(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_schema + + Override in a subclass to manipulate the response + after it is returned by the SchemaService server but before + it is returned to user code. + """ + return response + def pre_get_schema(self, request: schema_service.GetSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[schema_service.GetSchemaRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_schema + + Override in a subclass to manipulate the request or metadata + before they are sent to the SchemaService server. + """ + return request, metadata + + def post_get_schema(self, response: schema.Schema) -> schema.Schema: + """Post-rpc interceptor for get_schema + + Override in a subclass to manipulate the response + after it is returned by the SchemaService server but before + it is returned to user code. + """ + return response + def pre_list_schemas(self, request: schema_service.ListSchemasRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[schema_service.ListSchemasRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_schemas + + Override in a subclass to manipulate the request or metadata + before they are sent to the SchemaService server. + """ + return request, metadata + + def post_list_schemas(self, response: schema_service.ListSchemasResponse) -> schema_service.ListSchemasResponse: + """Post-rpc interceptor for list_schemas + + Override in a subclass to manipulate the response + after it is returned by the SchemaService server but before + it is returned to user code. + """ + return response + def pre_update_schema(self, request: schema_service.UpdateSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[schema_service.UpdateSchemaRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_schema + + Override in a subclass to manipulate the request or metadata + before they are sent to the SchemaService server. + """ + return request, metadata + + def post_update_schema(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_schema + + Override in a subclass to manipulate the response + after it is returned by the SchemaService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the SchemaService 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 SchemaService server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the SchemaService 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 SchemaService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class SchemaServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: SchemaServiceRestInterceptor + + +class SchemaServiceRestTransport(SchemaServiceTransport): + """REST backend transport for SchemaService. + + Service for managing + [Schema][google.cloud.discoveryengine.v1alpha.Schema]s. + + 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 = 'discoveryengine.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[SchemaServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or SchemaServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1alpha") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CreateSchema(SchemaServiceRestStub): + def __hash__(self): + return hash("CreateSchema") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "schemaId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: schema_service.CreateSchemaRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create schema method over HTTP. + + Args: + request (~.schema_service.CreateSchemaRequest): + The request object. Request message for + [SchemaService.CreateSchema][google.cloud.discoveryengine.v1alpha.SchemaService.CreateSchema] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=projects/*/locations/*/dataStores/*}/schemas', + 'body': 'schema', + }, +{ + 'method': 'post', + 'uri': '/v1alpha/{parent=projects/*/locations/*/collections/*/dataStores/*}/schemas', + 'body': 'schema', + }, + ] + request, metadata = self._interceptor.pre_create_schema(request, metadata) + pb_request = schema_service.CreateSchemaRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_schema(resp) + return resp + + class _DeleteSchema(SchemaServiceRestStub): + def __hash__(self): + return hash("DeleteSchema") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: schema_service.DeleteSchemaRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete schema method over HTTP. + + Args: + request (~.schema_service.DeleteSchemaRequest): + The request object. Request message for + [SchemaService.DeleteSchema][google.cloud.discoveryengine.v1alpha.SchemaService.DeleteSchema] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/schemas/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_schema(request, metadata) + pb_request = schema_service.DeleteSchemaRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_schema(resp) + return resp + + class _GetSchema(SchemaServiceRestStub): + def __hash__(self): + return hash("GetSchema") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: schema_service.GetSchemaRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> schema.Schema: + r"""Call the get schema method over HTTP. + + Args: + request (~.schema_service.GetSchemaRequest): + The request object. Request message for + [SchemaService.GetSchema][google.cloud.discoveryengine.v1alpha.SchemaService.GetSchema] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.schema.Schema: + Defines the structure and layout of a + type of document data. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/schemas/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}', + }, + ] + request, metadata = self._interceptor.pre_get_schema(request, metadata) + pb_request = schema_service.GetSchemaRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = schema.Schema() + pb_resp = schema.Schema.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_schema(resp) + return resp + + class _ListSchemas(SchemaServiceRestStub): + def __hash__(self): + return hash("ListSchemas") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: schema_service.ListSchemasRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> schema_service.ListSchemasResponse: + r"""Call the list schemas method over HTTP. + + Args: + request (~.schema_service.ListSchemasRequest): + The request object. Request message for + [SchemaService.ListSchemas][google.cloud.discoveryengine.v1alpha.SchemaService.ListSchemas] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.schema_service.ListSchemasResponse: + Response message for + [SchemaService.ListSchemas][google.cloud.discoveryengine.v1alpha.SchemaService.ListSchemas] + method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=projects/*/locations/*/dataStores/*}/schemas', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{parent=projects/*/locations/*/collections/*/dataStores/*}/schemas', + }, + ] + request, metadata = self._interceptor.pre_list_schemas(request, metadata) + pb_request = schema_service.ListSchemasRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = schema_service.ListSchemasResponse() + pb_resp = schema_service.ListSchemasResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_schemas(resp) + return resp + + class _UpdateSchema(SchemaServiceRestStub): + def __hash__(self): + return hash("UpdateSchema") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: schema_service.UpdateSchemaRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update schema method over HTTP. + + Args: + request (~.schema_service.UpdateSchemaRequest): + The request object. Request message for + [SchemaService.UpdateSchema][google.cloud.discoveryengine.v1alpha.SchemaService.UpdateSchema] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha/{schema.name=projects/*/locations/*/dataStores/*/schemas/*}', + 'body': 'schema', + }, +{ + 'method': 'patch', + 'uri': '/v1alpha/{schema.name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}', + 'body': 'schema', + }, + ] + request, metadata = self._interceptor.pre_update_schema(request, metadata) + pb_request = schema_service.UpdateSchemaRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_schema(resp) + return resp + + @property + def create_schema(self) -> Callable[ + [schema_service.CreateSchemaRequest], + 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._CreateSchema(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_schema(self) -> Callable[ + [schema_service.DeleteSchemaRequest], + 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._DeleteSchema(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_schema(self) -> Callable[ + [schema_service.GetSchemaRequest], + schema.Schema]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSchema(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_schemas(self) -> Callable[ + [schema_service.ListSchemasRequest], + schema_service.ListSchemasResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSchemas(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_schema(self) -> Callable[ + [schema_service.UpdateSchemaRequest], + 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._UpdateSchema(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(SchemaServiceRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(SchemaServiceRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'SchemaServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/__init__.py new file mode 100644 index 000000000000..0355170e3569 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import SearchServiceClient +from .async_client import SearchServiceAsyncClient + +__all__ = ( + 'SearchServiceClient', + 'SearchServiceAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/async_client.py new file mode 100644 index 000000000000..ec796c60b958 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/async_client.py @@ -0,0 +1,402 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.discoveryengine_v1alpha.services.search_service import pagers +from google.cloud.discoveryengine_v1alpha.types import search_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport +from .client import SearchServiceClient + + +class SearchServiceAsyncClient: + """Service for search.""" + + _client: SearchServiceClient + + DEFAULT_ENDPOINT = SearchServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SearchServiceClient.DEFAULT_MTLS_ENDPOINT + + branch_path = staticmethod(SearchServiceClient.branch_path) + parse_branch_path = staticmethod(SearchServiceClient.parse_branch_path) + document_path = staticmethod(SearchServiceClient.document_path) + parse_document_path = staticmethod(SearchServiceClient.parse_document_path) + serving_config_path = staticmethod(SearchServiceClient.serving_config_path) + parse_serving_config_path = staticmethod(SearchServiceClient.parse_serving_config_path) + common_billing_account_path = staticmethod(SearchServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SearchServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SearchServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(SearchServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(SearchServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(SearchServiceClient.parse_common_organization_path) + common_project_path = staticmethod(SearchServiceClient.common_project_path) + parse_common_project_path = staticmethod(SearchServiceClient.parse_common_project_path) + common_location_path = staticmethod(SearchServiceClient.common_location_path) + parse_common_location_path = staticmethod(SearchServiceClient.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: + SearchServiceAsyncClient: The constructed client. + """ + return SearchServiceClient.from_service_account_info.__func__(SearchServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceAsyncClient: The constructed client. + """ + return SearchServiceClient.from_service_account_file.__func__(SearchServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return SearchServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SearchServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SearchServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(SearchServiceClient).get_transport_class, type(SearchServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, SearchServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the search 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 (Union[str, ~.SearchServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = SearchServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def search(self, + request: Optional[Union[search_service.SearchRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAsyncPager: + r"""Performs a search. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_search(): + # Create a client + client = discoveryengine_v1alpha.SearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.SearchRequest( + serving_config="serving_config_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.SearchRequest, dict]]): + The request object. Request message for + [SearchService.Search][google.cloud.discoveryengine.v1alpha.SearchService.Search] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.services.search_service.pagers.SearchAsyncPager: + Response message for + [SearchService.Search][google.cloud.discoveryengine.v1alpha.SearchService.Search] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + request = search_service.SearchRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.search, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config", request.serving_config), + )), + ) + + # 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.SearchAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "SearchServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "SearchServiceAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/client.py new file mode 100644 index 000000000000..b2fba548a734 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/client.py @@ -0,0 +1,628 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.discoveryengine_v1alpha.services.search_service import pagers +from google.cloud.discoveryengine_v1alpha.types import search_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SearchServiceGrpcTransport +from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport +from .transports.rest import SearchServiceRestTransport + + +class SearchServiceClientMeta(type): + """Metaclass for the SearchService 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[SearchServiceTransport]] + _transport_registry["grpc"] = SearchServiceGrpcTransport + _transport_registry["grpc_asyncio"] = SearchServiceGrpcAsyncIOTransport + _transport_registry["rest"] = SearchServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[SearchServiceTransport]: + """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 SearchServiceClient(metaclass=SearchServiceClientMeta): + """Service for search.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceClient: 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: + SearchServiceClient: 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) -> SearchServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SearchServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def branch_path(project: str,location: str,data_store: str,branch: str,) -> str: + """Returns a fully-qualified branch string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}".format(project=project, location=location, data_store=data_store, branch=branch, ) + + @staticmethod + def parse_branch_path(path: str) -> Dict[str,str]: + """Parses a branch path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def document_path(project: str,location: str,data_store: str,branch: str,document: str,) -> str: + """Returns a fully-qualified document string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) + + @staticmethod + def parse_document_path(path: str) -> Dict[str,str]: + """Parses a document path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)/documents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def serving_config_path(project: str,location: str,data_store: str,serving_config: str,) -> str: + """Returns a fully-qualified serving_config string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/servingConfigs/{serving_config}".format(project=project, location=location, data_store=data_store, serving_config=serving_config, ) + + @staticmethod + def parse_serving_config_path(path: str) -> Dict[str,str]: + """Parses a serving_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/servingConfigs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, SearchServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the search 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 (Union[str, SearchServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, SearchServiceTransport): + # transport is a SearchServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def search(self, + request: Optional[Union[search_service.SearchRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchPager: + r"""Performs a search. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_search(): + # Create a client + client = discoveryengine_v1alpha.SearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.SearchRequest( + serving_config="serving_config_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.SearchRequest, dict]): + The request object. Request message for + [SearchService.Search][google.cloud.discoveryengine.v1alpha.SearchService.Search] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.services.search_service.pagers.SearchPager: + Response message for + [SearchService.Search][google.cloud.discoveryengine.v1alpha.SearchService.Search] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a search_service.SearchRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, search_service.SearchRequest): + request = search_service.SearchRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config", request.serving_config), + )), + ) + + # 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.SearchPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "SearchServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "SearchServiceClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/pagers.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/pagers.py new file mode 100644 index 000000000000..40e9766339a0 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/pagers.py @@ -0,0 +1,139 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.discoveryengine_v1alpha.types import search_service + + +class SearchPager: + """A pager for iterating through ``search`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1alpha.types.SearchResponse` object, and + provides an ``__iter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``Search`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1alpha.types.SearchResponse` + 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[..., search_service.SearchResponse], + request: search_service.SearchRequest, + response: search_service.SearchResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.discoveryengine_v1alpha.types.SearchRequest): + The initial request object. + response (google.cloud.discoveryengine_v1alpha.types.SearchResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = search_service.SearchRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[search_service.SearchResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[search_service.SearchResponse.SearchResult]: + for page in self.pages: + yield from page.results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchAsyncPager: + """A pager for iterating through ``search`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1alpha.types.SearchResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``Search`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1alpha.types.SearchResponse` + 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[search_service.SearchResponse]], + request: search_service.SearchRequest, + response: search_service.SearchResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.discoveryengine_v1alpha.types.SearchRequest): + The initial request object. + response (google.cloud.discoveryengine_v1alpha.types.SearchResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = search_service.SearchRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[search_service.SearchResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[search_service.SearchResponse.SearchResult]: + async def async_generator(): + async for page in self.pages: + for response in page.results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/__init__.py new file mode 100644 index 000000000000..4282aef080e3 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import SearchServiceTransport +from .grpc import SearchServiceGrpcTransport +from .grpc_asyncio import SearchServiceGrpcAsyncIOTransport +from .rest import SearchServiceRestTransport +from .rest import SearchServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] +_transport_registry['grpc'] = SearchServiceGrpcTransport +_transport_registry['grpc_asyncio'] = SearchServiceGrpcAsyncIOTransport +_transport_registry['rest'] = SearchServiceRestTransport + +__all__ = ( + 'SearchServiceTransport', + 'SearchServiceGrpcTransport', + 'SearchServiceGrpcAsyncIOTransport', + 'SearchServiceRestTransport', + 'SearchServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/base.py new file mode 100644 index 000000000000..c87e6749ded3 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/base.py @@ -0,0 +1,168 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import search_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class SearchServiceTransport(abc.ABC): + """Abstract transport class for SearchService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'discoveryengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.search: gapic_v1.method.wrap_method( + self.search, + 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 search(self) -> Callable[ + [search_service.SearchRequest], + Union[ + search_service.SearchResponse, + Awaitable[search_service.SearchResponse] + ]]: + 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 kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'SearchServiceTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/grpc.py new file mode 100644 index 000000000000..d71f5df898bc --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/grpc.py @@ -0,0 +1,302 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import search_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO + + +class SearchServiceGrpcTransport(SearchServiceTransport): + """gRPC backend transport for SearchService. + + Service for search. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def search(self) -> Callable[ + [search_service.SearchRequest], + search_service.SearchResponse]: + r"""Return a callable for the search method over gRPC. + + Performs a search. + + Returns: + Callable[[~.SearchRequest], + ~.SearchResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search' not in self._stubs: + self._stubs['search'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.SearchService/Search', + request_serializer=search_service.SearchRequest.serialize, + response_deserializer=search_service.SearchResponse.deserialize, + ) + return self._stubs['search'] + + def close(self): + self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'SearchServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..91340690816b --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/grpc_asyncio.py @@ -0,0 +1,301 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import search_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import SearchServiceGrpcTransport + + +class SearchServiceGrpcAsyncIOTransport(SearchServiceTransport): + """gRPC AsyncIO backend transport for SearchService. + + Service for search. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def search(self) -> Callable[ + [search_service.SearchRequest], + Awaitable[search_service.SearchResponse]]: + r"""Return a callable for the search method over gRPC. + + Performs a search. + + Returns: + Callable[[~.SearchRequest], + Awaitable[~.SearchResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search' not in self._stubs: + self._stubs['search'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.SearchService/Search', + request_serializer=search_service.SearchRequest.serialize, + response_deserializer=search_service.SearchResponse.deserialize, + ) + return self._stubs['search'] + + def close(self): + return self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ( + 'SearchServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/rest.py new file mode 100644 index 000000000000..8e4ca6d4d16e --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/rest.py @@ -0,0 +1,581 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.cloud.location import locations_pb2 # type: ignore +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.discoveryengine_v1alpha.types import search_service +from google.longrunning import operations_pb2 # type: ignore + +from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class SearchServiceRestInterceptor: + """Interceptor for SearchService. + + 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 SearchServiceRestTransport. + + .. code-block:: python + class MyCustomSearchServiceInterceptor(SearchServiceRestInterceptor): + def pre_search(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_search(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SearchServiceRestTransport(interceptor=MyCustomSearchServiceInterceptor()) + client = SearchServiceClient(transport=transport) + + + """ + def pre_search(self, request: search_service.SearchRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[search_service.SearchRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for search + + Override in a subclass to manipulate the request or metadata + before they are sent to the SearchService server. + """ + return request, metadata + + def post_search(self, response: search_service.SearchResponse) -> search_service.SearchResponse: + """Post-rpc interceptor for search + + Override in a subclass to manipulate the response + after it is returned by the SearchService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the SearchService 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 SearchService server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the SearchService 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 SearchService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class SearchServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: SearchServiceRestInterceptor + + +class SearchServiceRestTransport(SearchServiceTransport): + """REST backend transport for SearchService. + + Service for search. + + 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 = 'discoveryengine.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[SearchServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or SearchServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _Search(SearchServiceRestStub): + def __hash__(self): + return hash("Search") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: search_service.SearchRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> search_service.SearchResponse: + r"""Call the search method over HTTP. + + Args: + request (~.search_service.SearchRequest): + The request object. Request message for + [SearchService.Search][google.cloud.discoveryengine.v1alpha.SearchService.Search] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.search_service.SearchResponse: + Response message for + [SearchService.Search][google.cloud.discoveryengine.v1alpha.SearchService.Search] + method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{serving_config=projects/*/locations/*/dataStores/*/servingConfigs/*}:search', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha/{serving_config=projects/*/locations/*/collections/*/dataStores/*/servingConfigs/*}:search', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha/{serving_config=projects/*/locations/*/collections/*/engines/*/servingConfigs/*}:search', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_search(request, metadata) + pb_request = search_service.SearchRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = search_service.SearchResponse() + pb_resp = search_service.SearchResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_search(resp) + return resp + + @property + def search(self) -> Callable[ + [search_service.SearchRequest], + search_service.SearchResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Search(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(SearchServiceRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(SearchServiceRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'SearchServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/__init__.py new file mode 100644 index 000000000000..f7c959fea4c1 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import SiteSearchEngineServiceClient +from .async_client import SiteSearchEngineServiceAsyncClient + +__all__ = ( + 'SiteSearchEngineServiceClient', + 'SiteSearchEngineServiceAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/async_client.py new file mode 100644 index 000000000000..717467934518 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/async_client.py @@ -0,0 +1,401 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.discoveryengine_v1alpha.types import site_search_engine_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .transports.base import SiteSearchEngineServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SiteSearchEngineServiceGrpcAsyncIOTransport +from .client import SiteSearchEngineServiceClient + + +class SiteSearchEngineServiceAsyncClient: + """Service for managing site search related resources.""" + + _client: SiteSearchEngineServiceClient + + DEFAULT_ENDPOINT = SiteSearchEngineServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SiteSearchEngineServiceClient.DEFAULT_MTLS_ENDPOINT + + site_search_engine_path = staticmethod(SiteSearchEngineServiceClient.site_search_engine_path) + parse_site_search_engine_path = staticmethod(SiteSearchEngineServiceClient.parse_site_search_engine_path) + common_billing_account_path = staticmethod(SiteSearchEngineServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SiteSearchEngineServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SiteSearchEngineServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(SiteSearchEngineServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(SiteSearchEngineServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(SiteSearchEngineServiceClient.parse_common_organization_path) + common_project_path = staticmethod(SiteSearchEngineServiceClient.common_project_path) + parse_common_project_path = staticmethod(SiteSearchEngineServiceClient.parse_common_project_path) + common_location_path = staticmethod(SiteSearchEngineServiceClient.common_location_path) + parse_common_location_path = staticmethod(SiteSearchEngineServiceClient.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: + SiteSearchEngineServiceAsyncClient: The constructed client. + """ + return SiteSearchEngineServiceClient.from_service_account_info.__func__(SiteSearchEngineServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SiteSearchEngineServiceAsyncClient: The constructed client. + """ + return SiteSearchEngineServiceClient.from_service_account_file.__func__(SiteSearchEngineServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return SiteSearchEngineServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SiteSearchEngineServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SiteSearchEngineServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(SiteSearchEngineServiceClient).get_transport_class, type(SiteSearchEngineServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, SiteSearchEngineServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the site search engine 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 (Union[str, ~.SiteSearchEngineServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = SiteSearchEngineServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def recrawl_uris(self, + request: Optional[Union[site_search_engine_service.RecrawlUrisRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Request on-demand recrawl for a list of URIs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_recrawl_uris(): + # Create a client + client = discoveryengine_v1alpha.SiteSearchEngineServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.RecrawlUrisRequest( + site_search_engine="site_search_engine_value", + uris=['uris_value1', 'uris_value2'], + ) + + # Make the request + operation = client.recrawl_uris(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.RecrawlUrisRequest, dict]]): + The request object. Request message for + [SiteSearchEngineService.RecrawlUris][google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.RecrawlUris] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1alpha.types.RecrawlUrisResponse` Response message for + [SiteSearchEngineService.RecrawlUris][google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.RecrawlUris] + method. + + """ + # Create or coerce a protobuf request object. + request = site_search_engine_service.RecrawlUrisRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.recrawl_uris, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("site_search_engine", request.site_search_engine), + )), + ) + + # 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, + site_search_engine_service.RecrawlUrisResponse, + metadata_type=site_search_engine_service.RecrawlUrisMetadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "SiteSearchEngineServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "SiteSearchEngineServiceAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/client.py new file mode 100644 index 000000000000..a099d618a771 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/client.py @@ -0,0 +1,609 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.discoveryengine_v1alpha.types import site_search_engine_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .transports.base import SiteSearchEngineServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SiteSearchEngineServiceGrpcTransport +from .transports.grpc_asyncio import SiteSearchEngineServiceGrpcAsyncIOTransport +from .transports.rest import SiteSearchEngineServiceRestTransport + + +class SiteSearchEngineServiceClientMeta(type): + """Metaclass for the SiteSearchEngineService 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[SiteSearchEngineServiceTransport]] + _transport_registry["grpc"] = SiteSearchEngineServiceGrpcTransport + _transport_registry["grpc_asyncio"] = SiteSearchEngineServiceGrpcAsyncIOTransport + _transport_registry["rest"] = SiteSearchEngineServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[SiteSearchEngineServiceTransport]: + """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 SiteSearchEngineServiceClient(metaclass=SiteSearchEngineServiceClientMeta): + """Service for managing site search related resources.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SiteSearchEngineServiceClient: 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: + SiteSearchEngineServiceClient: 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) -> SiteSearchEngineServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SiteSearchEngineServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def site_search_engine_path(project: str,location: str,data_store: str,) -> str: + """Returns a fully-qualified site_search_engine string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/siteSearchEngine".format(project=project, location=location, data_store=data_store, ) + + @staticmethod + def parse_site_search_engine_path(path: str) -> Dict[str,str]: + """Parses a site_search_engine path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/siteSearchEngine$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, SiteSearchEngineServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the site search engine 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 (Union[str, SiteSearchEngineServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, SiteSearchEngineServiceTransport): + # transport is a SiteSearchEngineServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def recrawl_uris(self, + request: Optional[Union[site_search_engine_service.RecrawlUrisRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Request on-demand recrawl for a list of URIs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_recrawl_uris(): + # Create a client + client = discoveryengine_v1alpha.SiteSearchEngineServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.RecrawlUrisRequest( + site_search_engine="site_search_engine_value", + uris=['uris_value1', 'uris_value2'], + ) + + # Make the request + operation = client.recrawl_uris(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.RecrawlUrisRequest, dict]): + The request object. Request message for + [SiteSearchEngineService.RecrawlUris][google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.RecrawlUris] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1alpha.types.RecrawlUrisResponse` Response message for + [SiteSearchEngineService.RecrawlUris][google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.RecrawlUris] + method. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a site_search_engine_service.RecrawlUrisRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, site_search_engine_service.RecrawlUrisRequest): + request = site_search_engine_service.RecrawlUrisRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.recrawl_uris] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("site_search_engine", request.site_search_engine), + )), + ) + + # 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, + site_search_engine_service.RecrawlUrisResponse, + metadata_type=site_search_engine_service.RecrawlUrisMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "SiteSearchEngineServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "SiteSearchEngineServiceClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/__init__.py new file mode 100644 index 000000000000..e5e6e692055c --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import SiteSearchEngineServiceTransport +from .grpc import SiteSearchEngineServiceGrpcTransport +from .grpc_asyncio import SiteSearchEngineServiceGrpcAsyncIOTransport +from .rest import SiteSearchEngineServiceRestTransport +from .rest import SiteSearchEngineServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SiteSearchEngineServiceTransport]] +_transport_registry['grpc'] = SiteSearchEngineServiceGrpcTransport +_transport_registry['grpc_asyncio'] = SiteSearchEngineServiceGrpcAsyncIOTransport +_transport_registry['rest'] = SiteSearchEngineServiceRestTransport + +__all__ = ( + 'SiteSearchEngineServiceTransport', + 'SiteSearchEngineServiceGrpcTransport', + 'SiteSearchEngineServiceGrpcAsyncIOTransport', + 'SiteSearchEngineServiceRestTransport', + 'SiteSearchEngineServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/base.py new file mode 100644 index 000000000000..7dadffd99f94 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/base.py @@ -0,0 +1,174 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import site_search_engine_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class SiteSearchEngineServiceTransport(abc.ABC): + """Abstract transport class for SiteSearchEngineService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'discoveryengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.recrawl_uris: gapic_v1.method.wrap_method( + self.recrawl_uris, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def recrawl_uris(self) -> Callable[ + [site_search_engine_service.RecrawlUrisRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'SiteSearchEngineServiceTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/grpc.py new file mode 100644 index 000000000000..0bcfb27fc85a --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/grpc.py @@ -0,0 +1,320 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import site_search_engine_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import SiteSearchEngineServiceTransport, DEFAULT_CLIENT_INFO + + +class SiteSearchEngineServiceGrpcTransport(SiteSearchEngineServiceTransport): + """gRPC backend transport for SiteSearchEngineService. + + Service for managing site search related resources. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def recrawl_uris(self) -> Callable[ + [site_search_engine_service.RecrawlUrisRequest], + operations_pb2.Operation]: + r"""Return a callable for the recrawl uris method over gRPC. + + Request on-demand recrawl for a list of URIs. + + Returns: + Callable[[~.RecrawlUrisRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'recrawl_uris' not in self._stubs: + self._stubs['recrawl_uris'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.SiteSearchEngineService/RecrawlUris', + request_serializer=site_search_engine_service.RecrawlUrisRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['recrawl_uris'] + + def close(self): + self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'SiteSearchEngineServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..3defab13caed --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/grpc_asyncio.py @@ -0,0 +1,319 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import site_search_engine_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import SiteSearchEngineServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import SiteSearchEngineServiceGrpcTransport + + +class SiteSearchEngineServiceGrpcAsyncIOTransport(SiteSearchEngineServiceTransport): + """gRPC AsyncIO backend transport for SiteSearchEngineService. + + Service for managing site search related resources. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def recrawl_uris(self) -> Callable[ + [site_search_engine_service.RecrawlUrisRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the recrawl uris method over gRPC. + + Request on-demand recrawl for a list of URIs. + + Returns: + Callable[[~.RecrawlUrisRequest], + 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 'recrawl_uris' not in self._stubs: + self._stubs['recrawl_uris'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.SiteSearchEngineService/RecrawlUris', + request_serializer=site_search_engine_service.RecrawlUrisRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['recrawl_uris'] + + def close(self): + return self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ( + 'SiteSearchEngineServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/rest.py new file mode 100644 index 000000000000..7bb24796a06b --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/rest.py @@ -0,0 +1,709 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.cloud.location import locations_pb2 # type: ignore +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.discoveryengine_v1alpha.types import site_search_engine_service +from google.longrunning import operations_pb2 # type: ignore + +from .base import SiteSearchEngineServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class SiteSearchEngineServiceRestInterceptor: + """Interceptor for SiteSearchEngineService. + + 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 SiteSearchEngineServiceRestTransport. + + .. code-block:: python + class MyCustomSiteSearchEngineServiceInterceptor(SiteSearchEngineServiceRestInterceptor): + def pre_recrawl_uris(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_recrawl_uris(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SiteSearchEngineServiceRestTransport(interceptor=MyCustomSiteSearchEngineServiceInterceptor()) + client = SiteSearchEngineServiceClient(transport=transport) + + + """ + def pre_recrawl_uris(self, request: site_search_engine_service.RecrawlUrisRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[site_search_engine_service.RecrawlUrisRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for recrawl_uris + + Override in a subclass to manipulate the request or metadata + before they are sent to the SiteSearchEngineService server. + """ + return request, metadata + + def post_recrawl_uris(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for recrawl_uris + + Override in a subclass to manipulate the response + after it is returned by the SiteSearchEngineService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the SiteSearchEngineService 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 SiteSearchEngineService server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the SiteSearchEngineService 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 SiteSearchEngineService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class SiteSearchEngineServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: SiteSearchEngineServiceRestInterceptor + + +class SiteSearchEngineServiceRestTransport(SiteSearchEngineServiceTransport): + """REST backend transport for SiteSearchEngineService. + + Service for managing site search related resources. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__(self, *, + host: str = 'discoveryengine.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[SiteSearchEngineServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or SiteSearchEngineServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1alpha") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _RecrawlUris(SiteSearchEngineServiceRestStub): + def __hash__(self): + return hash("RecrawlUris") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: site_search_engine_service.RecrawlUrisRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the recrawl uris method over HTTP. + + Args: + request (~.site_search_engine_service.RecrawlUrisRequest): + The request object. Request message for + [SiteSearchEngineService.RecrawlUris][google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.RecrawlUris] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{site_search_engine=projects/*/locations/*/dataStores/*/siteSearchEngine}:recrawlUris', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha/{site_search_engine=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}:recrawlUris', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_recrawl_uris(request, metadata) + pb_request = site_search_engine_service.RecrawlUrisRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_recrawl_uris(resp) + return resp + + @property + def recrawl_uris(self) -> Callable[ + [site_search_engine_service.RecrawlUrisRequest], + 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._RecrawlUris(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(SiteSearchEngineServiceRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(SiteSearchEngineServiceRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'SiteSearchEngineServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/__init__.py new file mode 100644 index 000000000000..387c002d1701 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import UserEventServiceClient +from .async_client import UserEventServiceAsyncClient + +__all__ = ( + 'UserEventServiceClient', + 'UserEventServiceAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/async_client.py new file mode 100644 index 000000000000..1542968dbfd3 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/async_client.py @@ -0,0 +1,746 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.discoveryengine_v1alpha.types import common +from google.cloud.discoveryengine_v1alpha.types import import_config +from google.cloud.discoveryengine_v1alpha.types import purge_config +from google.cloud.discoveryengine_v1alpha.types import user_event +from google.cloud.discoveryengine_v1alpha.types import user_event_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport +from .client import UserEventServiceClient + + +class UserEventServiceAsyncClient: + """Service for ingesting end user actions on a website to + Discovery Engine API. + """ + + _client: UserEventServiceClient + + DEFAULT_ENDPOINT = UserEventServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = UserEventServiceClient.DEFAULT_MTLS_ENDPOINT + + data_store_path = staticmethod(UserEventServiceClient.data_store_path) + parse_data_store_path = staticmethod(UserEventServiceClient.parse_data_store_path) + document_path = staticmethod(UserEventServiceClient.document_path) + parse_document_path = staticmethod(UserEventServiceClient.parse_document_path) + common_billing_account_path = staticmethod(UserEventServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(UserEventServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(UserEventServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(UserEventServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(UserEventServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(UserEventServiceClient.parse_common_organization_path) + common_project_path = staticmethod(UserEventServiceClient.common_project_path) + parse_common_project_path = staticmethod(UserEventServiceClient.parse_common_project_path) + common_location_path = staticmethod(UserEventServiceClient.common_location_path) + parse_common_location_path = staticmethod(UserEventServiceClient.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: + UserEventServiceAsyncClient: The constructed client. + """ + return UserEventServiceClient.from_service_account_info.__func__(UserEventServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceAsyncClient: The constructed client. + """ + return UserEventServiceClient.from_service_account_file.__func__(UserEventServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return UserEventServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> UserEventServiceTransport: + """Returns the transport used by the client instance. + + Returns: + UserEventServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(UserEventServiceClient).get_transport_class, type(UserEventServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, UserEventServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the user event 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 (Union[str, ~.UserEventServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = UserEventServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def write_user_event(self, + request: Optional[Union[user_event_service.WriteUserEventRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> user_event.UserEvent: + r"""Writes a single user event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_write_user_event(): + # Create a client + client = discoveryengine_v1alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.WriteUserEventRequest( + parent="parent_value", + ) + + # Make the request + response = await client.write_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.WriteUserEventRequest, dict]]): + The request object. Request message for WriteUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.UserEvent: + UserEvent captures all metadata + information Discovery Engine API needs + to know about how end users interact + with customers' website. + + """ + # Create or coerce a protobuf request object. + request = user_event_service.WriteUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.write_user_event, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def collect_user_event(self, + request: Optional[Union[user_event_service.CollectUserEventRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> httpbody_pb2.HttpBody: + r"""Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a third-party domain. + + This method is used only by the Discovery Engine API + JavaScript pixel and Google Tag Manager. Users should + not call this method directly. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_collect_user_event(): + # Create a client + client = discoveryengine_v1alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = await client.collect_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.CollectUserEventRequest, dict]]): + The request object. Request message for CollectUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It should only be used for + payload formats that can't be represented as JSON, + such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as + the response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request + fields and also want access to the raw HTTP body. + + Example: + + message GetResourceRequest { + // A unique request id. string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + # Create or coerce a protobuf request object. + request = user_event_service.CollectUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.collect_user_event, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def purge_user_events(self, + request: Optional[Union[purge_config.PurgeUserEventsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_purge_user_events(): + # Create a client + client = discoveryengine_v1alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.PurgeUserEventsRequest, dict]]): + The request object. Request message for PurgeUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1alpha.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is + successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + """ + # Create or coerce a protobuf request object. + request = purge_config.PurgeUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.purge_user_events, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + purge_config.PurgeUserEventsResponse, + metadata_type=purge_config.PurgeUserEventsMetadata, + ) + + # Done; return the response. + return response + + async def import_user_events(self, + request: Optional[Union[import_config.ImportUserEventsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + async def sample_import_user_events(): + # Create a client + client = discoveryengine_v1alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + inline_source = discoveryengine_v1alpha.InlineSource() + inline_source.user_events.event_type = "event_type_value" + inline_source.user_events.user_pseudo_id = "user_pseudo_id_value" + + request = discoveryengine_v1alpha.ImportUserEventsRequest( + inline_source=inline_source, + parent="parent_value", + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.ImportUserEventsRequest, dict]]): + The request object. Request message for the + ImportUserEvents request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1alpha.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is + returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + request = import_config.ImportUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_user_events, + default_retry=retries.Retry( +initial=1.0,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_config.ImportUserEventsResponse, + metadata_type=import_config.ImportUserEventsMetadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "UserEventServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "UserEventServiceAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/client.py new file mode 100644 index 000000000000..5f25fb05ae1d --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/client.py @@ -0,0 +1,960 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.discoveryengine_v1alpha.types import common +from google.cloud.discoveryengine_v1alpha.types import import_config +from google.cloud.discoveryengine_v1alpha.types import purge_config +from google.cloud.discoveryengine_v1alpha.types import user_event +from google.cloud.discoveryengine_v1alpha.types import user_event_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import UserEventServiceGrpcTransport +from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport +from .transports.rest import UserEventServiceRestTransport + + +class UserEventServiceClientMeta(type): + """Metaclass for the UserEventService 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[UserEventServiceTransport]] + _transport_registry["grpc"] = UserEventServiceGrpcTransport + _transport_registry["grpc_asyncio"] = UserEventServiceGrpcAsyncIOTransport + _transport_registry["rest"] = UserEventServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[UserEventServiceTransport]: + """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 UserEventServiceClient(metaclass=UserEventServiceClientMeta): + """Service for ingesting end user actions on a website to + Discovery Engine API. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceClient: 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: + UserEventServiceClient: 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) -> UserEventServiceTransport: + """Returns the transport used by the client instance. + + Returns: + UserEventServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def data_store_path(project: str,location: str,data_store: str,) -> str: + """Returns a fully-qualified data_store string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) + + @staticmethod + def parse_data_store_path(path: str) -> Dict[str,str]: + """Parses a data_store path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def document_path(project: str,location: str,data_store: str,branch: str,document: str,) -> str: + """Returns a fully-qualified document string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) + + @staticmethod + def parse_document_path(path: str) -> Dict[str,str]: + """Parses a document path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)/documents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, UserEventServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the user event 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 (Union[str, UserEventServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, UserEventServiceTransport): + # transport is a UserEventServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def write_user_event(self, + request: Optional[Union[user_event_service.WriteUserEventRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> user_event.UserEvent: + r"""Writes a single user event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_write_user_event(): + # Create a client + client = discoveryengine_v1alpha.UserEventServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.WriteUserEventRequest( + parent="parent_value", + ) + + # Make the request + response = client.write_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.WriteUserEventRequest, dict]): + The request object. Request message for WriteUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1alpha.types.UserEvent: + UserEvent captures all metadata + information Discovery Engine API needs + to know about how end users interact + with customers' website. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.WriteUserEventRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, user_event_service.WriteUserEventRequest): + request = user_event_service.WriteUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.write_user_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def collect_user_event(self, + request: Optional[Union[user_event_service.CollectUserEventRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> httpbody_pb2.HttpBody: + r"""Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a third-party domain. + + This method is used only by the Discovery Engine API + JavaScript pixel and Google Tag Manager. Users should + not call this method directly. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_collect_user_event(): + # Create a client + client = discoveryengine_v1alpha.UserEventServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = client.collect_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.CollectUserEventRequest, dict]): + The request object. Request message for CollectUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It should only be used for + payload formats that can't be represented as JSON, + such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as + the response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request + fields and also want access to the raw HTTP body. + + Example: + + message GetResourceRequest { + // A unique request id. string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.CollectUserEventRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, user_event_service.CollectUserEventRequest): + request = user_event_service.CollectUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.collect_user_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def purge_user_events(self, + request: Optional[Union[purge_config.PurgeUserEventsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_purge_user_events(): + # Create a client + client = discoveryengine_v1alpha.UserEventServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.PurgeUserEventsRequest, dict]): + The request object. Request message for PurgeUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1alpha.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is + successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a purge_config.PurgeUserEventsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, purge_config.PurgeUserEventsRequest): + request = purge_config.PurgeUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.purge_user_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + purge_config.PurgeUserEventsResponse, + metadata_type=purge_config.PurgeUserEventsMetadata, + ) + + # Done; return the response. + return response + + def import_user_events(self, + request: Optional[Union[import_config.ImportUserEventsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1alpha + + def sample_import_user_events(): + # Create a client + client = discoveryengine_v1alpha.UserEventServiceClient() + + # Initialize request argument(s) + inline_source = discoveryengine_v1alpha.InlineSource() + inline_source.user_events.event_type = "event_type_value" + inline_source.user_events.user_pseudo_id = "user_pseudo_id_value" + + request = discoveryengine_v1alpha.ImportUserEventsRequest( + inline_source=inline_source, + parent="parent_value", + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1alpha.types.ImportUserEventsRequest, dict]): + The request object. Request message for the + ImportUserEvents request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1alpha.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is + returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a import_config.ImportUserEventsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, import_config.ImportUserEventsRequest): + request = import_config.ImportUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_user_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_config.ImportUserEventsResponse, + metadata_type=import_config.ImportUserEventsMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "UserEventServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "UserEventServiceClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/__init__.py new file mode 100644 index 000000000000..bea95d5a9d94 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import UserEventServiceTransport +from .grpc import UserEventServiceGrpcTransport +from .grpc_asyncio import UserEventServiceGrpcAsyncIOTransport +from .rest import UserEventServiceRestTransport +from .rest import UserEventServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] +_transport_registry['grpc'] = UserEventServiceGrpcTransport +_transport_registry['grpc_asyncio'] = UserEventServiceGrpcAsyncIOTransport +_transport_registry['rest'] = UserEventServiceRestTransport + +__all__ = ( + 'UserEventServiceTransport', + 'UserEventServiceGrpcTransport', + 'UserEventServiceGrpcAsyncIOTransport', + 'UserEventServiceRestTransport', + 'UserEventServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/base.py new file mode 100644 index 000000000000..da108380c50f --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/base.py @@ -0,0 +1,226 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.discoveryengine_v1alpha.types import import_config +from google.cloud.discoveryengine_v1alpha.types import purge_config +from google.cloud.discoveryengine_v1alpha.types import user_event +from google.cloud.discoveryengine_v1alpha.types import user_event_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class UserEventServiceTransport(abc.ABC): + """Abstract transport class for UserEventService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'discoveryengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.write_user_event: gapic_v1.method.wrap_method( + self.write_user_event, + default_timeout=None, + client_info=client_info, + ), + self.collect_user_event: gapic_v1.method.wrap_method( + self.collect_user_event, + default_timeout=None, + client_info=client_info, + ), + self.purge_user_events: gapic_v1.method.wrap_method( + self.purge_user_events, + default_timeout=None, + client_info=client_info, + ), + self.import_user_events: gapic_v1.method.wrap_method( + self.import_user_events, + default_retry=retries.Retry( +initial=1.0,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + Union[ + user_event.UserEvent, + Awaitable[user_event.UserEvent] + ]]: + raise NotImplementedError() + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + Union[ + httpbody_pb2.HttpBody, + Awaitable[httpbody_pb2.HttpBody] + ]]: + raise NotImplementedError() + + @property + def purge_user_events(self) -> Callable[ + [purge_config.PurgeUserEventsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'UserEventServiceTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/grpc.py new file mode 100644 index 000000000000..9a9babfa7184 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/grpc.py @@ -0,0 +1,420 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.discoveryengine_v1alpha.types import import_config +from google.cloud.discoveryengine_v1alpha.types import purge_config +from google.cloud.discoveryengine_v1alpha.types import user_event +from google.cloud.discoveryengine_v1alpha.types import user_event_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO + + +class UserEventServiceGrpcTransport(UserEventServiceTransport): + """gRPC backend transport for UserEventService. + + Service for ingesting end user actions on a website to + Discovery Engine 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 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + user_event.UserEvent]: + r"""Return a callable for the write user event method over gRPC. + + Writes a single user event. + + Returns: + Callable[[~.WriteUserEventRequest], + ~.UserEvent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'write_user_event' not in self._stubs: + self._stubs['write_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.UserEventService/WriteUserEvent', + request_serializer=user_event_service.WriteUserEventRequest.serialize, + response_deserializer=user_event.UserEvent.deserialize, + ) + return self._stubs['write_user_event'] + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + httpbody_pb2.HttpBody]: + r"""Return a callable for the collect user event method over gRPC. + + Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a third-party domain. + + This method is used only by the Discovery Engine API + JavaScript pixel and Google Tag Manager. Users should + not call this method directly. + + Returns: + Callable[[~.CollectUserEventRequest], + ~.HttpBody]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'collect_user_event' not in self._stubs: + self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.UserEventService/CollectUserEvent', + request_serializer=user_event_service.CollectUserEventRequest.serialize, + response_deserializer=httpbody_pb2.HttpBody.FromString, + ) + return self._stubs['collect_user_event'] + + @property + def purge_user_events(self) -> Callable[ + [purge_config.PurgeUserEventsRequest], + operations_pb2.Operation]: + r"""Return a callable for the purge user events method over gRPC. + + Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + Returns: + Callable[[~.PurgeUserEventsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'purge_user_events' not in self._stubs: + self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.UserEventService/PurgeUserEvents', + request_serializer=purge_config.PurgeUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['purge_user_events'] + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + operations_pb2.Operation]: + r"""Return a callable for the import user events method over gRPC. + + Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + Returns: + Callable[[~.ImportUserEventsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_user_events' not in self._stubs: + self._stubs['import_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.UserEventService/ImportUserEvents', + request_serializer=import_config.ImportUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_user_events'] + + def close(self): + self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'UserEventServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..594d8c6632ee --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/grpc_asyncio.py @@ -0,0 +1,419 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.discoveryengine_v1alpha.types import import_config +from google.cloud.discoveryengine_v1alpha.types import purge_config +from google.cloud.discoveryengine_v1alpha.types import user_event +from google.cloud.discoveryengine_v1alpha.types import user_event_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import UserEventServiceGrpcTransport + + +class UserEventServiceGrpcAsyncIOTransport(UserEventServiceTransport): + """gRPC AsyncIO backend transport for UserEventService. + + Service for ingesting end user actions on a website to + Discovery Engine 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 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + Awaitable[user_event.UserEvent]]: + r"""Return a callable for the write user event method over gRPC. + + Writes a single user event. + + Returns: + Callable[[~.WriteUserEventRequest], + Awaitable[~.UserEvent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'write_user_event' not in self._stubs: + self._stubs['write_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.UserEventService/WriteUserEvent', + request_serializer=user_event_service.WriteUserEventRequest.serialize, + response_deserializer=user_event.UserEvent.deserialize, + ) + return self._stubs['write_user_event'] + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + Awaitable[httpbody_pb2.HttpBody]]: + r"""Return a callable for the collect user event method over gRPC. + + Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a third-party domain. + + This method is used only by the Discovery Engine API + JavaScript pixel and Google Tag Manager. Users should + not call this method directly. + + Returns: + Callable[[~.CollectUserEventRequest], + Awaitable[~.HttpBody]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'collect_user_event' not in self._stubs: + self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.UserEventService/CollectUserEvent', + request_serializer=user_event_service.CollectUserEventRequest.serialize, + response_deserializer=httpbody_pb2.HttpBody.FromString, + ) + return self._stubs['collect_user_event'] + + @property + def purge_user_events(self) -> Callable[ + [purge_config.PurgeUserEventsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the purge user events method over gRPC. + + Deletes permanently all user events specified by the + filter provided. Depending on the number of events + specified by the filter, this operation could take hours + or days to complete. To test a filter, use the list + command first. + + Returns: + Callable[[~.PurgeUserEventsRequest], + 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 'purge_user_events' not in self._stubs: + self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.UserEventService/PurgeUserEvents', + request_serializer=purge_config.PurgeUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['purge_user_events'] + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import user events method over gRPC. + + Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + Returns: + Callable[[~.ImportUserEventsRequest], + 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 'import_user_events' not in self._stubs: + self._stubs['import_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1alpha.UserEventService/ImportUserEvents', + request_serializer=import_config.ImportUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_user_events'] + + def close(self): + return self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ( + 'UserEventServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/rest.py new file mode 100644 index 000000000000..6050744fbd81 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/rest.py @@ -0,0 +1,1132 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.cloud.location import locations_pb2 # type: ignore +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.discoveryengine_v1alpha.types import import_config +from google.cloud.discoveryengine_v1alpha.types import purge_config +from google.cloud.discoveryengine_v1alpha.types import user_event +from google.cloud.discoveryengine_v1alpha.types import user_event_service +from google.longrunning import operations_pb2 # type: ignore + +from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class UserEventServiceRestInterceptor: + """Interceptor for UserEventService. + + 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 UserEventServiceRestTransport. + + .. code-block:: python + class MyCustomUserEventServiceInterceptor(UserEventServiceRestInterceptor): + def pre_collect_user_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_collect_user_event(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_import_user_events(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_import_user_events(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_purge_user_events(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_purge_user_events(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_write_user_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_write_user_event(self, response): + logging.log(f"Received response: {response}") + return response + + transport = UserEventServiceRestTransport(interceptor=MyCustomUserEventServiceInterceptor()) + client = UserEventServiceClient(transport=transport) + + + """ + def pre_collect_user_event(self, request: user_event_service.CollectUserEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[user_event_service.CollectUserEventRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for collect_user_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserEventService server. + """ + return request, metadata + + def post_collect_user_event(self, response: httpbody_pb2.HttpBody) -> httpbody_pb2.HttpBody: + """Post-rpc interceptor for collect_user_event + + Override in a subclass to manipulate the response + after it is returned by the UserEventService server but before + it is returned to user code. + """ + return response + def pre_import_user_events(self, request: import_config.ImportUserEventsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[import_config.ImportUserEventsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for import_user_events + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserEventService server. + """ + return request, metadata + + def post_import_user_events(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for import_user_events + + Override in a subclass to manipulate the response + after it is returned by the UserEventService server but before + it is returned to user code. + """ + return response + def pre_purge_user_events(self, request: purge_config.PurgeUserEventsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[purge_config.PurgeUserEventsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for purge_user_events + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserEventService server. + """ + return request, metadata + + def post_purge_user_events(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for purge_user_events + + Override in a subclass to manipulate the response + after it is returned by the UserEventService server but before + it is returned to user code. + """ + return response + def pre_write_user_event(self, request: user_event_service.WriteUserEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[user_event_service.WriteUserEventRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for write_user_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserEventService server. + """ + return request, metadata + + def post_write_user_event(self, response: user_event.UserEvent) -> user_event.UserEvent: + """Post-rpc interceptor for write_user_event + + Override in a subclass to manipulate the response + after it is returned by the UserEventService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserEventService 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 UserEventService server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserEventService 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 UserEventService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class UserEventServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: UserEventServiceRestInterceptor + + +class UserEventServiceRestTransport(UserEventServiceTransport): + """REST backend transport for UserEventService. + + Service for ingesting end user actions on a website to + Discovery Engine 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 = 'discoveryengine.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[UserEventServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or UserEventServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1alpha") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CollectUserEvent(UserEventServiceRestStub): + def __hash__(self): + return hash("CollectUserEvent") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "userEvent" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: user_event_service.CollectUserEventRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> httpbody_pb2.HttpBody: + r"""Call the collect user event method over HTTP. + + Args: + request (~.user_event_service.CollectUserEventRequest): + The request object. Request message for CollectUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It + should only be used for payload formats that can't be + represented as JSON, such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as the + response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request fields + and also want access to the raw HTTP body. + + Example: + + :: + + message GetResourceRequest { + // A unique request id. + string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + :: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=projects/*/locations/*/dataStores/*}/userEvents:collect', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{parent=projects/*/locations/*/collections/*/dataStores/*}/userEvents:collect', + }, + ] + request, metadata = self._interceptor.pre_collect_user_event(request, metadata) + pb_request = user_event_service.CollectUserEventRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = httpbody_pb2.HttpBody() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_collect_user_event(resp) + return resp + + class _ImportUserEvents(UserEventServiceRestStub): + def __hash__(self): + return hash("ImportUserEvents") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: import_config.ImportUserEventsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the import user events method over HTTP. + + Args: + request (~.import_config.ImportUserEventsRequest): + The request object. Request message for the + ImportUserEvents request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=projects/*/locations/*/dataStores/*}/userEvents:import', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha/{parent=projects/*/locations/*/collections/*/dataStores/*}/userEvents:import', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_import_user_events(request, metadata) + pb_request = import_config.ImportUserEventsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_import_user_events(resp) + return resp + + class _PurgeUserEvents(UserEventServiceRestStub): + def __hash__(self): + return hash("PurgeUserEvents") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: purge_config.PurgeUserEventsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the purge user events method over HTTP. + + Args: + request (~.purge_config.PurgeUserEventsRequest): + The request object. Request message for PurgeUserEvents + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=projects/*/locations/*/dataStores/*}/userEvents:purge', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha/{parent=projects/*/locations/*/collections/*/dataStores/*}/userEvents:purge', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_purge_user_events(request, metadata) + pb_request = purge_config.PurgeUserEventsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_purge_user_events(resp) + return resp + + class _WriteUserEvent(UserEventServiceRestStub): + def __hash__(self): + return hash("WriteUserEvent") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: user_event_service.WriteUserEventRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> user_event.UserEvent: + r"""Call the write user event method over HTTP. + + Args: + request (~.user_event_service.WriteUserEventRequest): + The request object. Request message for WriteUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.user_event.UserEvent: + UserEvent captures all metadata + information Discovery Engine API needs + to know about how end users interact + with customers' website. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=projects/*/locations/*/dataStores/*}/userEvents:write', + 'body': 'user_event', + }, +{ + 'method': 'post', + 'uri': '/v1alpha/{parent=projects/*/locations/*/collections/*/dataStores/*}/userEvents:write', + 'body': 'user_event', + }, + ] + request, metadata = self._interceptor.pre_write_user_event(request, metadata) + pb_request = user_event_service.WriteUserEventRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = user_event.UserEvent() + pb_resp = user_event.UserEvent.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_write_user_event(resp) + return resp + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + httpbody_pb2.HttpBody]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CollectUserEvent(self._session, self._host, self._interceptor) # type: ignore + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + 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._ImportUserEvents(self._session, self._host, self._interceptor) # type: ignore + + @property + def purge_user_events(self) -> Callable[ + [purge_config.PurgeUserEventsRequest], + 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._PurgeUserEvents(self._session, self._host, self._interceptor) # type: ignore + + @property + def write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + user_event.UserEvent]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._WriteUserEvent(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(UserEventServiceRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(UserEventServiceRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*/locations/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=projects/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'UserEventServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/__init__.py new file mode 100644 index 000000000000..5b503322068e --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/__init__.py @@ -0,0 +1,248 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .common import ( + CustomAttribute, + DoubleList, + Interval, + UserInfo, + IndustryVertical, + SearchAddOn, + SearchTier, + SolutionType, +) +from .completion_service import ( + CompleteQueryRequest, + CompleteQueryResponse, +) +from .conversation import ( + Conversation, + ConversationContext, + ConversationMessage, + Reply, + TextInput, +) +from .conversational_search_service import ( + ConverseConversationRequest, + ConverseConversationResponse, + CreateConversationRequest, + DeleteConversationRequest, + GetConversationRequest, + ListConversationsRequest, + ListConversationsResponse, + UpdateConversationRequest, +) +from .data_store import ( + DataStore, +) +from .data_store_service import ( + CreateDataStoreMetadata, + CreateDataStoreRequest, + DeleteDataStoreMetadata, + DeleteDataStoreRequest, + GetDataStoreRequest, + ListDataStoresRequest, + ListDataStoresResponse, + UpdateDataStoreRequest, +) +from .document import ( + Document, +) +from .document_service import ( + CreateDocumentRequest, + DeleteDocumentRequest, + GetDocumentRequest, + ListDocumentsRequest, + ListDocumentsResponse, + UpdateDocumentRequest, +) +from .engine import ( + Engine, +) +from .engine_service import ( + CreateEngineMetadata, + CreateEngineRequest, + DeleteEngineMetadata, + DeleteEngineRequest, + GetEngineRequest, + ListEnginesRequest, + ListEnginesResponse, + PauseEngineRequest, + ResumeEngineRequest, + TuneEngineMetadata, + TuneEngineRequest, + TuneEngineResponse, + UpdateEngineRequest, +) +from .import_config import ( + BigQuerySource, + GcsSource, + ImportDocumentsMetadata, + ImportDocumentsRequest, + ImportDocumentsResponse, + ImportErrorConfig, + ImportUserEventsMetadata, + ImportUserEventsRequest, + ImportUserEventsResponse, +) +from .purge_config import ( + PurgeDocumentsMetadata, + PurgeDocumentsRequest, + PurgeDocumentsResponse, + PurgeUserEventsMetadata, + PurgeUserEventsRequest, + PurgeUserEventsResponse, +) +from .recommendation_service import ( + RecommendRequest, + RecommendResponse, +) +from .schema import ( + FieldConfig, + Schema, +) +from .schema_service import ( + CreateSchemaMetadata, + CreateSchemaRequest, + DeleteSchemaMetadata, + DeleteSchemaRequest, + GetSchemaRequest, + ListSchemasRequest, + ListSchemasResponse, + UpdateSchemaMetadata, + UpdateSchemaRequest, +) +from .search_service import ( + SearchRequest, + SearchResponse, +) +from .site_search_engine_service import ( + RecrawlUrisMetadata, + RecrawlUrisRequest, + RecrawlUrisResponse, +) +from .user_event import ( + CompletionInfo, + DocumentInfo, + MediaInfo, + PageInfo, + PanelInfo, + SearchInfo, + TransactionInfo, + UserEvent, +) +from .user_event_service import ( + CollectUserEventRequest, + WriteUserEventRequest, +) + +__all__ = ( + 'CustomAttribute', + 'DoubleList', + 'Interval', + 'UserInfo', + 'IndustryVertical', + 'SearchAddOn', + 'SearchTier', + 'SolutionType', + 'CompleteQueryRequest', + 'CompleteQueryResponse', + 'Conversation', + 'ConversationContext', + 'ConversationMessage', + 'Reply', + 'TextInput', + 'ConverseConversationRequest', + 'ConverseConversationResponse', + 'CreateConversationRequest', + 'DeleteConversationRequest', + 'GetConversationRequest', + 'ListConversationsRequest', + 'ListConversationsResponse', + 'UpdateConversationRequest', + 'DataStore', + 'CreateDataStoreMetadata', + 'CreateDataStoreRequest', + 'DeleteDataStoreMetadata', + 'DeleteDataStoreRequest', + 'GetDataStoreRequest', + 'ListDataStoresRequest', + 'ListDataStoresResponse', + 'UpdateDataStoreRequest', + 'Document', + 'CreateDocumentRequest', + 'DeleteDocumentRequest', + 'GetDocumentRequest', + 'ListDocumentsRequest', + 'ListDocumentsResponse', + 'UpdateDocumentRequest', + 'Engine', + 'CreateEngineMetadata', + 'CreateEngineRequest', + 'DeleteEngineMetadata', + 'DeleteEngineRequest', + 'GetEngineRequest', + 'ListEnginesRequest', + 'ListEnginesResponse', + 'PauseEngineRequest', + 'ResumeEngineRequest', + 'TuneEngineMetadata', + 'TuneEngineRequest', + 'TuneEngineResponse', + 'UpdateEngineRequest', + 'BigQuerySource', + 'GcsSource', + 'ImportDocumentsMetadata', + 'ImportDocumentsRequest', + 'ImportDocumentsResponse', + 'ImportErrorConfig', + 'ImportUserEventsMetadata', + 'ImportUserEventsRequest', + 'ImportUserEventsResponse', + 'PurgeDocumentsMetadata', + 'PurgeDocumentsRequest', + 'PurgeDocumentsResponse', + 'PurgeUserEventsMetadata', + 'PurgeUserEventsRequest', + 'PurgeUserEventsResponse', + 'RecommendRequest', + 'RecommendResponse', + 'FieldConfig', + 'Schema', + 'CreateSchemaMetadata', + 'CreateSchemaRequest', + 'DeleteSchemaMetadata', + 'DeleteSchemaRequest', + 'GetSchemaRequest', + 'ListSchemasRequest', + 'ListSchemasResponse', + 'UpdateSchemaMetadata', + 'UpdateSchemaRequest', + 'SearchRequest', + 'SearchResponse', + 'RecrawlUrisMetadata', + 'RecrawlUrisRequest', + 'RecrawlUrisResponse', + 'CompletionInfo', + 'DocumentInfo', + 'MediaInfo', + 'PageInfo', + 'PanelInfo', + 'SearchInfo', + 'TransactionInfo', + 'UserEvent', + 'CollectUserEventRequest', + 'WriteUserEventRequest', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/common.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/common.py new file mode 100644 index 000000000000..5c52f13db40e --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/common.py @@ -0,0 +1,257 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.discoveryengine.v1alpha', + manifest={ + 'IndustryVertical', + 'SolutionType', + 'SearchTier', + 'SearchAddOn', + 'Interval', + 'CustomAttribute', + 'UserInfo', + 'DoubleList', + }, +) + + +class IndustryVertical(proto.Enum): + r"""The industry vertical associated with the + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]. + + Values: + INDUSTRY_VERTICAL_UNSPECIFIED (0): + Value used when unset. + GENERIC (1): + The generic vertical for documents that are + not specific to any industry vertical. + MEDIA (2): + The media industry vertical. + """ + INDUSTRY_VERTICAL_UNSPECIFIED = 0 + GENERIC = 1 + MEDIA = 2 + + +class SolutionType(proto.Enum): + r"""The type of solution. + + Values: + SOLUTION_TYPE_UNSPECIFIED (0): + Default value. + SOLUTION_TYPE_RECOMMENDATION (1): + Used for Recommendations AI. + SOLUTION_TYPE_SEARCH (2): + Used for Discovery Search. + SOLUTION_TYPE_CHAT (3): + Used for use cases related to the Generative + AI agent. + """ + SOLUTION_TYPE_UNSPECIFIED = 0 + SOLUTION_TYPE_RECOMMENDATION = 1 + SOLUTION_TYPE_SEARCH = 2 + SOLUTION_TYPE_CHAT = 3 + + +class SearchTier(proto.Enum): + r"""Tiers of search features. Different tiers might have + different pricing. To learn more, please check the pricing + documentation. + + Values: + SEARCH_TIER_UNSPECIFIED (0): + Default value when the enum is unspecified. + This is invalid to use. + SEARCH_TIER_STANDARD (1): + Standard tier. + SEARCH_TIER_ENTERPRISE (2): + Enterprise tier. + """ + SEARCH_TIER_UNSPECIFIED = 0 + SEARCH_TIER_STANDARD = 1 + SEARCH_TIER_ENTERPRISE = 2 + + +class SearchAddOn(proto.Enum): + r"""Add-on that provides additional functionality for search. + + Values: + SEARCH_ADD_ON_UNSPECIFIED (0): + Default value when the enum is unspecified. + This is invalid to use. + SEARCH_ADD_ON_LLM (1): + Large language model add-on. + """ + SEARCH_ADD_ON_UNSPECIFIED = 0 + SEARCH_ADD_ON_LLM = 1 + + +class Interval(proto.Message): + r"""A floating point interval. + + 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: + minimum (float): + Inclusive lower bound. + + This field is a member of `oneof`_ ``min``. + exclusive_minimum (float): + Exclusive lower bound. + + This field is a member of `oneof`_ ``min``. + maximum (float): + Inclusive upper bound. + + This field is a member of `oneof`_ ``max``. + exclusive_maximum (float): + Exclusive upper bound. + + This field is a member of `oneof`_ ``max``. + """ + + minimum: float = proto.Field( + proto.DOUBLE, + number=1, + oneof='min', + ) + exclusive_minimum: float = proto.Field( + proto.DOUBLE, + number=2, + oneof='min', + ) + maximum: float = proto.Field( + proto.DOUBLE, + number=3, + oneof='max', + ) + exclusive_maximum: float = proto.Field( + proto.DOUBLE, + number=4, + oneof='max', + ) + + +class CustomAttribute(proto.Message): + r"""A custom attribute that is not explicitly modeled in a resource, + e.g. [UserEvent][google.cloud.discoveryengine.v1alpha.UserEvent]. + + Attributes: + text (MutableSequence[str]): + The textual values of this custom attribute. For example, + ``["yellow", "green"]`` when the key is "color". + + Empty string is not allowed. Otherwise, an + ``INVALID_ARGUMENT`` error is returned. + + Exactly one of + [CustomAttribute.text][google.cloud.discoveryengine.v1alpha.CustomAttribute.text] + or + [CustomAttribute.numbers][google.cloud.discoveryengine.v1alpha.CustomAttribute.numbers] + should be set. Otherwise, an ``INVALID_ARGUMENT`` error is + returned. + numbers (MutableSequence[float]): + The numerical values of this custom attribute. For example, + ``[2.3, 15.4]`` when the key is "lengths_cm". + + Exactly one of + [CustomAttribute.text][google.cloud.discoveryengine.v1alpha.CustomAttribute.text] + or + [CustomAttribute.numbers][google.cloud.discoveryengine.v1alpha.CustomAttribute.numbers] + should be set. Otherwise, an ``INVALID_ARGUMENT`` error is + returned. + """ + + text: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + numbers: MutableSequence[float] = proto.RepeatedField( + proto.DOUBLE, + number=2, + ) + + +class UserInfo(proto.Message): + r"""Information of an end user. + + Attributes: + user_id (str): + Highly recommended for logged-in users. Unique identifier + for logged-in user, such as a user name. Don't set for + anonymous users. + + Always use a hashed value for this ID. + + Don't set the field to the same fixed ID for different + users. This mixes the event history of those users together, + which results in degraded model quality. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an ``INVALID_ARGUMENT`` error + is returned. + user_agent (str): + User agent as included in the HTTP header. + + The field must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an ``INVALID_ARGUMENT`` + error is returned. + + This should not be set when using the client side event + reporting with GTM or JavaScript tag in + [UserEventService.CollectUserEvent][google.cloud.discoveryengine.v1alpha.UserEventService.CollectUserEvent] + or if + [UserEvent.direct_user_request][google.cloud.discoveryengine.v1alpha.UserEvent.direct_user_request] + is set. + """ + + user_id: str = proto.Field( + proto.STRING, + number=1, + ) + user_agent: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DoubleList(proto.Message): + r"""Double list. + + Attributes: + values (MutableSequence[float]): + Double values. + """ + + values: MutableSequence[float] = proto.RepeatedField( + proto.DOUBLE, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/completion_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/completion_service.py new file mode 100644 index 000000000000..796a63969cdf --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/completion_service.py @@ -0,0 +1,169 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.discoveryengine.v1alpha', + manifest={ + 'CompleteQueryRequest', + 'CompleteQueryResponse', + }, +) + + +class CompleteQueryRequest(proto.Message): + r"""Request message for + [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1alpha.CompletionService.CompleteQuery] + method. + + Attributes: + data_store (str): + Required. The parent data store resource name for which the + completion is performed, such as + ``projects/*/locations/global/collections/default_collection/dataStores/default_data_store``. + query (str): + Required. The typeahead input used to fetch + suggestions. Maximum length is 128 characters. + query_model (str): + Selects data model of query suggestions for serving. + Currently supported values: + + - ``document`` - Using suggestions generated from + user-imported documents. + - ``search-history`` - Using suggestions generated from the + past history of + [SearchService.Search][google.cloud.discoveryengine.v1alpha.SearchService.Search] + API calls. Do not use it when there is no traffic for + Search API. + - ``user-event`` - Using suggestions generated from + user-imported search events. + - ``document-completable`` - Using suggestions taken + directly from user-imported document fields marked as + completable. + + Default values: + + - ``document`` is the default model for regular dataStores. + - ``search-history`` is the default model for site search + dataStores. + user_pseudo_id (str): + A unique identifier for tracking visitors. For example, this + could be implemented with an HTTP cookie, which should be + able to uniquely identify a visitor on a single device. This + unique identifier should not change if the visitor logs in + or out of the website. + + This field should NOT have a fixed value such as + ``unknown_visitor``. + + This should be the same identifier as + [UserEvent.user_pseudo_id][google.cloud.discoveryengine.v1alpha.UserEvent.user_pseudo_id] + and + [SearchRequest.user_pseudo_id][google.cloud.discoveryengine.v1alpha.SearchRequest.user_pseudo_id]. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an ``INVALID_ARGUMENT`` error + is returned. + include_tail_suggestions (bool): + Indicates if tail suggestions should be + returned if there are no suggestions that match + the full query. Even if set to true, if there + are suggestions that match the full query, those + are returned and no tail suggestions are + returned. + """ + + data_store: str = proto.Field( + proto.STRING, + number=1, + ) + query: str = proto.Field( + proto.STRING, + number=2, + ) + query_model: str = proto.Field( + proto.STRING, + number=3, + ) + user_pseudo_id: str = proto.Field( + proto.STRING, + number=4, + ) + include_tail_suggestions: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class CompleteQueryResponse(proto.Message): + r"""Response message for + [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1alpha.CompletionService.CompleteQuery] + method. + + Attributes: + query_suggestions (MutableSequence[google.cloud.discoveryengine_v1alpha.types.CompleteQueryResponse.QuerySuggestion]): + Results of the matched query suggestions. The + result list is ordered and the first result is a + top suggestion. + tail_match_triggered (bool): + True if the returned suggestions are all tail suggestions. + + For tail matching to be triggered, include_tail_suggestions + in the request must be true and there must be no suggestions + that match the full query. + """ + + class QuerySuggestion(proto.Message): + r"""Suggestions as search queries. + + Attributes: + suggestion (str): + The suggestion for the query. + completable_field_paths (MutableSequence[str]): + The unique document field paths that serve as + the source of this suggestion if it was + generated from completable fields. + + This field is only populated for the + document-completable model. + """ + + suggestion: str = proto.Field( + proto.STRING, + number=1, + ) + completable_field_paths: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + query_suggestions: MutableSequence[QuerySuggestion] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=QuerySuggestion, + ) + tail_match_triggered: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/conversation.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/conversation.py new file mode 100644 index 000000000000..61a669ad6236 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/conversation.py @@ -0,0 +1,248 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import search_service +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1alpha', + manifest={ + 'Conversation', + 'Reply', + 'ConversationContext', + 'TextInput', + 'ConversationMessage', + }, +) + + +class Conversation(proto.Message): + r"""External conversation proto definition. + + Attributes: + name (str): + Immutable. Fully qualified name + ``project/*/locations/global/collections/{collection}/dataStore/*/conversations/*`` + state (google.cloud.discoveryengine_v1alpha.types.Conversation.State): + The state of the Conversation. + user_pseudo_id (str): + A unique identifier for tracking users. + messages (MutableSequence[google.cloud.discoveryengine_v1alpha.types.ConversationMessage]): + Conversation messages. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the conversation + started. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the conversation + finished. + """ + class State(proto.Enum): + r"""Enumeration of the state of the conversation. + + Values: + STATE_UNSPECIFIED (0): + Unknown. + IN_PROGRESS (1): + Conversation is currently open. + COMPLETED (2): + Conversation has been completed. + """ + STATE_UNSPECIFIED = 0 + IN_PROGRESS = 1 + COMPLETED = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + state: State = proto.Field( + proto.ENUM, + number=2, + enum=State, + ) + user_pseudo_id: str = proto.Field( + proto.STRING, + number=3, + ) + messages: MutableSequence['ConversationMessage'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='ConversationMessage', + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + + +class Reply(proto.Message): + r"""Defines a reply message to user. + + Attributes: + reply (str): + DEPRECATED: use ``summary`` instead. Text reply. + references (MutableSequence[google.cloud.discoveryengine_v1alpha.types.Reply.Reference]): + References in the reply. + summary (google.cloud.discoveryengine_v1alpha.types.SearchResponse.Summary): + Summary based on search results. + """ + + class Reference(proto.Message): + r"""Defines reference in reply. + + Attributes: + uri (str): + URI link reference. + anchor_text (str): + Anchor text. + start (int): + Anchor text start index. + end (int): + Anchor text end index. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + anchor_text: str = proto.Field( + proto.STRING, + number=2, + ) + start: int = proto.Field( + proto.INT32, + number=3, + ) + end: int = proto.Field( + proto.INT32, + number=4, + ) + + reply: str = proto.Field( + proto.STRING, + number=1, + ) + references: MutableSequence[Reference] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Reference, + ) + summary: search_service.SearchResponse.Summary = proto.Field( + proto.MESSAGE, + number=3, + message=search_service.SearchResponse.Summary, + ) + + +class ConversationContext(proto.Message): + r"""Defines context of the conversation + + Attributes: + context_documents (MutableSequence[str]): + The current list of documents the user is + seeing. It contains the document resource + references. + active_document (str): + The current active document the user opened. + It contains the document resource reference. + """ + + context_documents: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + active_document: str = proto.Field( + proto.STRING, + number=2, + ) + + +class TextInput(proto.Message): + r"""Defines text input. + + Attributes: + input (str): + Text input. + context (google.cloud.discoveryengine_v1alpha.types.ConversationContext): + Conversation context of the input. + """ + + input: str = proto.Field( + proto.STRING, + number=1, + ) + context: 'ConversationContext' = proto.Field( + proto.MESSAGE, + number=2, + message='ConversationContext', + ) + + +class ConversationMessage(proto.Message): + r"""Defines a conversation 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: + user_input (google.cloud.discoveryengine_v1alpha.types.TextInput): + User text input. + + This field is a member of `oneof`_ ``message``. + reply (google.cloud.discoveryengine_v1alpha.types.Reply): + Search reply. + + This field is a member of `oneof`_ ``message``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Message creation timestamp. + """ + + user_input: 'TextInput' = proto.Field( + proto.MESSAGE, + number=1, + oneof='message', + message='TextInput', + ) + reply: 'Reply' = proto.Field( + proto.MESSAGE, + number=2, + oneof='message', + message='Reply', + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/conversational_search_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/conversational_search_service.py new file mode 100644 index 000000000000..22d4345b045d --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/conversational_search_service.py @@ -0,0 +1,328 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import conversation as gcd_conversation +from google.cloud.discoveryengine_v1alpha.types import search_service +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1alpha', + manifest={ + 'ConverseConversationRequest', + 'ConverseConversationResponse', + 'CreateConversationRequest', + 'UpdateConversationRequest', + 'DeleteConversationRequest', + 'GetConversationRequest', + 'ListConversationsRequest', + 'ListConversationsResponse', + }, +) + + +class ConverseConversationRequest(proto.Message): + r"""Request message for + [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1alpha.ConversationalSearchService.ConverseConversation] + method. + + Attributes: + name (str): + Required. The resource name of the Conversation to get. + Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}``. + Use + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/-`` + to activate auto session mode, which automatically creates a + new conversation inside a ConverseConversation session. + query (google.cloud.discoveryengine_v1alpha.types.TextInput): + Required. Current user input. + serving_config (str): + The resource name of the Serving Config to use. Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/servingConfigs/{serving_config_id}`` + If this is not set, the default serving config will be used. + conversation (google.cloud.discoveryengine_v1alpha.types.Conversation): + The conversation to be used by auto session + only. The name field will be ignored as we + automatically assign new name for the + conversation in auto session. + safe_search (bool): + Whether to turn on safe search. + user_labels (MutableMapping[str, str]): + The user labels applied to a resource must meet the + following requirements: + + - Each resource can have multiple labels, up to a maximum + of 64. + - Each label must be a key-value pair. + - Keys have a minimum length of 1 character and a maximum + length of 63 characters and cannot be empty. Values can + be empty and have a maximum length of 63 characters. + - Keys and values can contain only lowercase letters, + numeric characters, underscores, and dashes. All + characters must use UTF-8 encoding, and international + characters are allowed. + - The key portion of a label must be unique. However, you + can use the same key with multiple resources. + - Keys must start with a lowercase letter or international + character. + + See `Google Cloud + Document `__ + for more details. + summary_spec (google.cloud.discoveryengine_v1alpha.types.SearchRequest.ContentSearchSpec.SummarySpec): + A specification for configuring the summary + returned in the response. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + query: gcd_conversation.TextInput = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_conversation.TextInput, + ) + serving_config: str = proto.Field( + proto.STRING, + number=3, + ) + conversation: gcd_conversation.Conversation = proto.Field( + proto.MESSAGE, + number=5, + message=gcd_conversation.Conversation, + ) + safe_search: bool = proto.Field( + proto.BOOL, + number=6, + ) + user_labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + summary_spec: search_service.SearchRequest.ContentSearchSpec.SummarySpec = proto.Field( + proto.MESSAGE, + number=8, + message=search_service.SearchRequest.ContentSearchSpec.SummarySpec, + ) + + +class ConverseConversationResponse(proto.Message): + r"""Response message for + [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1alpha.ConversationalSearchService.ConverseConversation] + method. + + Attributes: + reply (google.cloud.discoveryengine_v1alpha.types.Reply): + Answer to the current query. + conversation (google.cloud.discoveryengine_v1alpha.types.Conversation): + Updated conversation including the answer. + related_questions (MutableSequence[str]): + Suggested related questions. + search_results (MutableSequence[google.cloud.discoveryengine_v1alpha.types.SearchResponse.SearchResult]): + Search Results. + """ + + reply: gcd_conversation.Reply = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_conversation.Reply, + ) + conversation: gcd_conversation.Conversation = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_conversation.Conversation, + ) + related_questions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + search_results: MutableSequence[search_service.SearchResponse.SearchResult] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=search_service.SearchResponse.SearchResult, + ) + + +class CreateConversationRequest(proto.Message): + r"""Request for CreateConversation method. + + Attributes: + parent (str): + Required. Full resource name of parent data store. Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` + conversation (google.cloud.discoveryengine_v1alpha.types.Conversation): + Required. The conversation to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + conversation: gcd_conversation.Conversation = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_conversation.Conversation, + ) + + +class UpdateConversationRequest(proto.Message): + r"""Request for UpdateConversation method. + + Attributes: + conversation (google.cloud.discoveryengine_v1alpha.types.Conversation): + Required. The Conversation to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] + to update. The following are NOT supported: + + - [conversation.name][] + + If not set or empty, all supported fields are updated. + """ + + conversation: gcd_conversation.Conversation = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_conversation.Conversation, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteConversationRequest(proto.Message): + r"""Request for DeleteConversation method. + + Attributes: + name (str): + Required. The resource name of the Conversation to delete. + Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetConversationRequest(proto.Message): + r"""Request for GetConversation method. + + Attributes: + name (str): + Required. The resource name of the Conversation to get. + Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListConversationsRequest(proto.Message): + r"""Request for ListConversations method. + + Attributes: + parent (str): + Required. The data store resource name. Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` + page_size (int): + Maximum number of results to return. If + unspecified, defaults to 50. Max allowed value + is 1000. + page_token (str): + A page token, received from a previous ``ListConversations`` + call. Provide this to retrieve the subsequent page. + filter (str): + A filter to apply on the list results. The supported + features are: user_pseudo_id, state. + + Example: "user_pseudo_id = some_id". + order_by (str): + A comma-separated list of fields to order by, sorted in + ascending order. Use "desc" after a field name for + descending. Supported fields: + + - ``update_time`` + - ``create_time`` + - ``conversation_name`` + + Example: "update_time desc" "create_time". + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListConversationsResponse(proto.Message): + r"""Response for ListConversations method. + + Attributes: + conversations (MutableSequence[google.cloud.discoveryengine_v1alpha.types.Conversation]): + All the Conversations for a given data store. + next_page_token (str): + Pagination token, if not returned indicates + the last page. + """ + + @property + def raw_page(self): + return self + + conversations: MutableSequence[gcd_conversation.Conversation] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_conversation.Conversation, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/data_store.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/data_store.py new file mode 100644 index 000000000000..6c7de7410189 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/data_store.py @@ -0,0 +1,132 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import common +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1alpha', + manifest={ + 'DataStore', + }, +) + + +class DataStore(proto.Message): + r"""DataStore captures global settings and configs at the + DataStore level. + + Attributes: + name (str): + Immutable. The full resource name of the data store. Format: + ``projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}``. + + This field must be a UTF-8 encoded string with a length + limit of 1024 characters. + display_name (str): + Required. The data store display name. + + This field must be a UTF-8 encoded string with a length + limit of 128 characters. Otherwise, an INVALID_ARGUMENT + error is returned. + industry_vertical (google.cloud.discoveryengine_v1alpha.types.IndustryVertical): + Immutable. The industry vertical that the + data store registers. + solution_types (MutableSequence[google.cloud.discoveryengine_v1alpha.types.SolutionType]): + The solutions that the data store enrolls. Available + solutions for each + [industry_vertical][google.cloud.discoveryengine.v1alpha.DataStore.industry_vertical]: + + - ``MEDIA``: ``SOLUTION_TYPE_RECOMMENDATION`` and + ``SOLUTION_TYPE_SEARCH``. + - ``SITE_SEARCH``: ``SOLUTION_TYPE_SEARCH`` is + automatically enrolled. Other solutions cannot be + enrolled. + default_schema_id (str): + Output only. The id of the default + [Schema][google.cloud.discoveryengine.v1alpha.Schema] + asscociated to this data store. + content_config (google.cloud.discoveryengine_v1alpha.types.DataStore.ContentConfig): + Immutable. The content config of the data store. If this + field is unset, the server behavior defaults to + [ContentConfig.NO_CONTENT][google.cloud.discoveryengine.v1alpha.DataStore.ContentConfig.NO_CONTENT]. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp the + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore] + was created at. + """ + class ContentConfig(proto.Enum): + r"""Content config of the data store. + + Values: + CONTENT_CONFIG_UNSPECIFIED (0): + Default value. + NO_CONTENT (1): + Only contains documents without any + [Document.content][google.cloud.discoveryengine.v1alpha.Document.content]. + CONTENT_REQUIRED (2): + Only contains documents with + [Document.content][google.cloud.discoveryengine.v1alpha.Document.content]. + PUBLIC_WEBSITE (3): + The data store is used for public website + search. + """ + CONTENT_CONFIG_UNSPECIFIED = 0 + NO_CONTENT = 1 + CONTENT_REQUIRED = 2 + PUBLIC_WEBSITE = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + industry_vertical: common.IndustryVertical = proto.Field( + proto.ENUM, + number=3, + enum=common.IndustryVertical, + ) + solution_types: MutableSequence[common.SolutionType] = proto.RepeatedField( + proto.ENUM, + number=5, + enum=common.SolutionType, + ) + default_schema_id: str = proto.Field( + proto.STRING, + number=7, + ) + content_config: ContentConfig = proto.Field( + proto.ENUM, + number=6, + enum=ContentConfig, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/data_store_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/data_store_service.py new file mode 100644 index 000000000000..a35ac9c474c7 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/data_store_service.py @@ -0,0 +1,326 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import data_store as gcd_data_store +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1alpha', + manifest={ + 'CreateDataStoreRequest', + 'GetDataStoreRequest', + 'CreateDataStoreMetadata', + 'ListDataStoresRequest', + 'ListDataStoresResponse', + 'DeleteDataStoreRequest', + 'UpdateDataStoreRequest', + 'DeleteDataStoreMetadata', + }, +) + + +class CreateDataStoreRequest(proto.Message): + r"""Request for + [DataStoreService.CreateDataStore][google.cloud.discoveryengine.v1alpha.DataStoreService.CreateDataStore] + method. + + Attributes: + parent (str): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}``. + data_store (google.cloud.discoveryengine_v1alpha.types.DataStore): + Required. The + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore] + to create. + data_store_id (str): + Required. The ID to use for the + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore], + which will become the final component of the + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]'s + resource name. + + This field must conform to + `RFC-1034 `__ standard + with a length limit of 63 characters. Otherwise, an + INVALID_ARGUMENT error is returned. + create_advanced_site_search (bool): + A boolean flag indicating whether user want to directly + create an advanced data store for site search. If the data + store is not configured as site search (GENERIC vertical and + PUBLIC_WEBSITE content_config), this flag will be ignored. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + data_store: gcd_data_store.DataStore = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_data_store.DataStore, + ) + data_store_id: str = proto.Field( + proto.STRING, + number=3, + ) + create_advanced_site_search: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class GetDataStoreRequest(proto.Message): + r"""Request message for + [DataStoreService.GetDataStore][google.cloud.discoveryengine.v1alpha.DataStoreService.GetDataStore] + method. + + Attributes: + name (str): + Required. Full resource name of + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore], + such as + ``projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}``. + + If the caller does not have permission to access the + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore], + regardless of whether or not it exists, a PERMISSION_DENIED + error is returned. + + If the requested + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore] + does not exist, a NOT_FOUND error is returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateDataStoreMetadata(proto.Message): + r"""Metadata related to the progress of the + [DataStoreService.CreateDataStore][google.cloud.discoveryengine.v1alpha.DataStoreService.CreateDataStore] + operation. This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class ListDataStoresRequest(proto.Message): + r"""Request message for + [DataStoreService.ListDataStores][google.cloud.discoveryengine.v1alpha.DataStoreService.ListDataStores] + method. + + Attributes: + parent (str): + Required. The parent branch resource name, such as + ``projects/{project}/locations/{location}/collections/{collection_id}``. + + If the caller does not have permission to list + [DataStores][]s under this location, regardless of whether + or not this data store exists, a PERMISSION_DENIED error is + returned. + page_size (int): + Maximum number of + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]s + to return. If unspecified, defaults to 10. The maximum + allowed value is 50. Values above 50 will be coerced to 50. + + If this field is negative, an INVALID_ARGUMENT is returned. + page_token (str): + A page token + [ListDataStoresResponse.next_page_token][google.cloud.discoveryengine.v1alpha.ListDataStoresResponse.next_page_token], + received from a previous + [DataStoreService.ListDataStores][google.cloud.discoveryengine.v1alpha.DataStoreService.ListDataStores] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [DataStoreService.ListDataStores][google.cloud.discoveryengine.v1alpha.DataStoreService.ListDataStores] + must match the call that provided the page token. Otherwise, + an INVALID_ARGUMENT error is returned. + filter (str): + Filter by solution type. For example: filter = + 'solution_type:SOLUTION_TYPE_SEARCH' + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListDataStoresResponse(proto.Message): + r"""Response message for + [DataStoreService.ListDataStores][google.cloud.discoveryengine.v1alpha.DataStoreService.ListDataStores] + method. + + Attributes: + data_stores (MutableSequence[google.cloud.discoveryengine_v1alpha.types.DataStore]): + All the customer's + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]s. + next_page_token (str): + A token that can be sent as + [ListDataStoresRequest.page_token][google.cloud.discoveryengine.v1alpha.ListDataStoresRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + data_stores: MutableSequence[gcd_data_store.DataStore] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_data_store.DataStore, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteDataStoreRequest(proto.Message): + r"""Request message for + [DataStoreService.DeleteDataStore][google.cloud.discoveryengine.v1alpha.DataStoreService.DeleteDataStore] + method. + + Attributes: + name (str): + Required. Full resource name of + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore], + such as + ``projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}``. + + If the caller does not have permission to delete the + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore], + regardless of whether or not it exists, a PERMISSION_DENIED + error is returned. + + If the + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore] + to delete does not exist, a NOT_FOUND error is returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateDataStoreRequest(proto.Message): + r"""Request message for + [DataStoreService.UpdateDataStore][google.cloud.discoveryengine.v1alpha.DataStoreService.UpdateDataStore] + method. + + Attributes: + data_store (google.cloud.discoveryengine_v1alpha.types.DataStore): + Required. The + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore] + to update. + + If the caller does not have permission to update the + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore], + regardless of whether or not it exists, a PERMISSION_DENIED + error is returned. + + If the + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore] + to update does not exist, a NOT_FOUND error is returned. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore] + to update. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + """ + + data_store: gcd_data_store.DataStore = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_data_store.DataStore, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteDataStoreMetadata(proto.Message): + r"""Metadata related to the progress of the + [DataStoreService.DeleteDataStore][google.cloud.discoveryengine.v1alpha.DataStoreService.DeleteDataStore] + operation. This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/document.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/document.py new file mode 100644 index 000000000000..3e2c807e54d6 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/document.py @@ -0,0 +1,189 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1alpha', + manifest={ + 'Document', + }, +) + + +class Document(proto.Message): + r"""Document captures all raw metadata information of items to be + recommended or searched. + + 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: + struct_data (google.protobuf.struct_pb2.Struct): + The structured JSON data for the document. It should conform + to the registered + [Schema][google.cloud.discoveryengine.v1alpha.Schema] or an + ``INVALID_ARGUMENT`` error is thrown. + + This field is a member of `oneof`_ ``data``. + json_data (str): + The JSON string representation of the document. It should + conform to the registered + [Schema][google.cloud.discoveryengine.v1alpha.Schema] or an + ``INVALID_ARGUMENT`` error is thrown. + + This field is a member of `oneof`_ ``data``. + name (str): + Immutable. The full resource name of the document. Format: + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document_id}``. + + This field must be a UTF-8 encoded string with a length + limit of 1024 characters. + id (str): + Immutable. The identifier of the document. + + Id should conform to + `RFC-1034 `__ standard + with a length limit of 63 characters. + schema_id (str): + The identifier of the schema located in the + same data store. + content (google.cloud.discoveryengine_v1alpha.types.Document.Content): + The unstructured data linked to this document. Content must + be set if this document is under a ``CONTENT_REQUIRED`` data + store. + parent_document_id (str): + The identifier of the parent document. Currently supports at + most two level document hierarchy. + + Id should conform to + `RFC-1034 `__ standard + with a length limit of 63 characters. + derived_struct_data (google.protobuf.struct_pb2.Struct): + Output only. This field is OUTPUT_ONLY. It contains derived + data that are not in the original input document. + """ + + class Content(proto.Message): + r"""Unstructured data linked to this document. + + 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: + raw_bytes (bytes): + The content represented as a stream of bytes. The maximum + length is 1,000,000 bytes (1 MB / ~0.95 MiB). + + Note: As with all ``bytes`` fields, this field is + represented as pure binary in Protocol Buffers and + base64-encoded string in JSON. For example, + ``abc123!?$*&()'-=@~`` should be represented as + ``YWJjMTIzIT8kKiYoKSctPUB+`` in JSON. See + https://developers.google.com/protocol-buffers/docs/proto3#json. + + This field is a member of `oneof`_ ``content``. + uri (str): + The URI of the content. Only Cloud Storage URIs (e.g. + ``gs://bucket-name/path/to/file``) are supported. The + maximum file size is 100 MB. + + This field is a member of `oneof`_ ``content``. + mime_type (str): + The MIME type of the content. Supported types: + + - ``application/pdf`` (PDF, only native PDFs are supported + for now) + - ``text/html`` (HTML) + - ``application/vnd.openxmlformats-officedocument.wordprocessingml.document`` + (DOCX) + - ``application/vnd.openxmlformats-officedocument.presentationml.presentation`` + (PPTX) + - ``text/plain`` (TXT) + + See + https://www.iana.org/assignments/media-types/media-types.xhtml. + """ + + raw_bytes: bytes = proto.Field( + proto.BYTES, + number=2, + oneof='content', + ) + uri: str = proto.Field( + proto.STRING, + number=3, + oneof='content', + ) + mime_type: str = proto.Field( + proto.STRING, + number=1, + ) + + struct_data: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=4, + oneof='data', + message=struct_pb2.Struct, + ) + json_data: str = proto.Field( + proto.STRING, + number=5, + oneof='data', + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + id: str = proto.Field( + proto.STRING, + number=2, + ) + schema_id: str = proto.Field( + proto.STRING, + number=3, + ) + content: Content = proto.Field( + proto.MESSAGE, + number=10, + message=Content, + ) + parent_document_id: str = proto.Field( + proto.STRING, + number=7, + ) + derived_struct_data: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=6, + message=struct_pb2.Struct, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/document_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/document_service.py new file mode 100644 index 000000000000..22a55cdb5c53 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/document_service.py @@ -0,0 +1,266 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import document as gcd_document + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1alpha', + manifest={ + 'GetDocumentRequest', + 'ListDocumentsRequest', + 'ListDocumentsResponse', + 'CreateDocumentRequest', + 'UpdateDocumentRequest', + 'DeleteDocumentRequest', + }, +) + + +class GetDocumentRequest(proto.Message): + r"""Request message for + [DocumentService.GetDocument][google.cloud.discoveryengine.v1alpha.DocumentService.GetDocument] + method. + + Attributes: + name (str): + Required. Full resource name of + [Document][google.cloud.discoveryengine.v1alpha.Document], + such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. + + If the caller does not have permission to access the + [Document][google.cloud.discoveryengine.v1alpha.Document], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the requested + [Document][google.cloud.discoveryengine.v1alpha.Document] + does not exist, a ``NOT_FOUND`` error is returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListDocumentsRequest(proto.Message): + r"""Request message for + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.ListDocuments] + method. + + Attributes: + parent (str): + Required. The parent branch resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. + Use ``default_branch`` as the branch ID, to list documents + under the default branch. + + If the caller does not have permission to list + [Document][google.cloud.discoveryengine.v1alpha.Document]s + under this branch, regardless of whether or not this branch + exists, a ``PERMISSION_DENIED`` error is returned. + page_size (int): + Maximum number of + [Document][google.cloud.discoveryengine.v1alpha.Document]s + to return. If unspecified, defaults to 100. The maximum + allowed value is 1000. Values above 1000 will be coerced to + 1000. + + If this field is negative, an ``INVALID_ARGUMENT`` error is + returned. + page_token (str): + A page token + [ListDocumentsResponse.next_page_token][google.cloud.discoveryengine.v1alpha.ListDocumentsResponse.next_page_token], + received from a previous + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.ListDocuments] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.ListDocuments] + must match the call that provided the page token. Otherwise, + an ``INVALID_ARGUMENT`` error is returned. + """ + + 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 ListDocumentsResponse(proto.Message): + r"""Response message for + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.ListDocuments] + method. + + Attributes: + documents (MutableSequence[google.cloud.discoveryengine_v1alpha.types.Document]): + The + [Document][google.cloud.discoveryengine.v1alpha.Document]s. + next_page_token (str): + A token that can be sent as + [ListDocumentsRequest.page_token][google.cloud.discoveryengine.v1alpha.ListDocumentsRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + documents: MutableSequence[gcd_document.Document] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_document.Document, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateDocumentRequest(proto.Message): + r"""Request message for + [DocumentService.CreateDocument][google.cloud.discoveryengine.v1alpha.DocumentService.CreateDocument] + method. + + Attributes: + parent (str): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. + document (google.cloud.discoveryengine_v1alpha.types.Document): + Required. The + [Document][google.cloud.discoveryengine.v1alpha.Document] to + create. + document_id (str): + Required. The ID to use for the + [Document][google.cloud.discoveryengine.v1alpha.Document], + which will become the final component of the + [Document.name][google.cloud.discoveryengine.v1alpha.Document.name]. + + If the caller does not have permission to create the + [Document][google.cloud.discoveryengine.v1alpha.Document], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + This field must be unique among all + [Document][google.cloud.discoveryengine.v1alpha.Document]s + with the same + [parent][google.cloud.discoveryengine.v1alpha.CreateDocumentRequest.parent]. + Otherwise, an ``ALREADY_EXISTS`` error is returned. + + This field must conform to + `RFC-1034 `__ standard + with a length limit of 63 characters. Otherwise, an + ``INVALID_ARGUMENT`` error is returned. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + document: gcd_document.Document = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_document.Document, + ) + document_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateDocumentRequest(proto.Message): + r"""Request message for + [DocumentService.UpdateDocument][google.cloud.discoveryengine.v1alpha.DocumentService.UpdateDocument] + method. + + Attributes: + document (google.cloud.discoveryengine_v1alpha.types.Document): + Required. The document to update/create. + + If the caller does not have permission to update the + [Document][google.cloud.discoveryengine.v1alpha.Document], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [Document][google.cloud.discoveryengine.v1alpha.Document] to + update does not exist and + [allow_missing][google.cloud.discoveryengine.v1alpha.UpdateDocumentRequest.allow_missing] + is not set, a ``NOT_FOUND`` error is returned. + allow_missing (bool): + If set to true, and the + [Document][google.cloud.discoveryengine.v1alpha.Document] is + not found, a new + [Document][google.cloud.discoveryengine.v1alpha.Document] + will be created. + """ + + document: gcd_document.Document = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_document.Document, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class DeleteDocumentRequest(proto.Message): + r"""Request message for + [DocumentService.DeleteDocument][google.cloud.discoveryengine.v1alpha.DocumentService.DeleteDocument] + method. + + Attributes: + name (str): + Required. Full resource name of + [Document][google.cloud.discoveryengine.v1alpha.Document], + such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. + + If the caller does not have permission to delete the + [Document][google.cloud.discoveryengine.v1alpha.Document], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [Document][google.cloud.discoveryengine.v1alpha.Document] to + delete does not exist, a ``NOT_FOUND`` error is returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/engine.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/engine.py new file mode 100644 index 000000000000..7847214528b9 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/engine.py @@ -0,0 +1,570 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import common +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1alpha', + manifest={ + 'Engine', + }, +) + + +class Engine(proto.Message): + r"""Metadata that describes the training and serving parameters of an + [Engine][google.cloud.discoveryengine.v1alpha.Engine]. + + 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: + similar_documents_config (google.cloud.discoveryengine_v1alpha.types.Engine.SimilarDocumentsEngineConfig): + Additional config specs for a ``similar-items`` engine. + + This field is a member of `oneof`_ ``engine_config``. + chat_engine_config (google.cloud.discoveryengine_v1alpha.types.Engine.ChatEngineConfig): + Configurations for the Chat Engine. Only applicable if + [solution_type][google.cloud.discoveryengine.v1alpha.Engine.solution_type] + is + [SOLUTION_TYPE_CHAT][google.cloud.discoveryengine.v1alpha.SolutionType.SOLUTION_TYPE_CHAT]. + + This field is a member of `oneof`_ ``engine_config``. + search_engine_config (google.cloud.discoveryengine_v1alpha.types.Engine.SearchEngineConfig): + Configurations for the Search Engine. Only applicable if + [solution_type][google.cloud.discoveryengine.v1alpha.Engine.solution_type] + is + [SOLUTION_TYPE_SEARCH][google.cloud.discoveryengine.v1alpha.SolutionType.SOLUTION_TYPE_SEARCH]. + + This field is a member of `oneof`_ ``engine_config``. + media_recommendation_engine_config (google.cloud.discoveryengine_v1alpha.types.Engine.MediaRecommendationEngineConfig): + Configurations for the Media Engine. Only applicable on the + data stores with + [solution_type][google.cloud.discoveryengine.v1alpha.Engine.solution_type] + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.discoveryengine.v1alpha.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + and + [IndustryVertical.MEDIA][google.cloud.discoveryengine.v1alpha.IndustryVertical.MEDIA] + vertical. + + This field is a member of `oneof`_ ``engine_config``. + recommendation_metadata (google.cloud.discoveryengine_v1alpha.types.Engine.RecommendationMetadata): + Output only. Additional information of a recommendation + engine. Only applicable if + [solution_type][google.cloud.discoveryengine.v1alpha.Engine.solution_type] + is + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.discoveryengine.v1alpha.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. + + This field is a member of `oneof`_ ``engine_metadata``. + chat_engine_metadata (google.cloud.discoveryengine_v1alpha.types.Engine.ChatEngineMetadata): + Output only. Additional information of the Chat Engine. Only + applicable if + [solution_type][google.cloud.discoveryengine.v1alpha.Engine.solution_type] + is + [SOLUTION_TYPE_CHAT][google.cloud.discoveryengine.v1alpha.SolutionType.SOLUTION_TYPE_CHAT]. + + This field is a member of `oneof`_ ``engine_metadata``. + name (str): + Immutable. The fully qualified resource name of the engine. + + This field must be a UTF-8 encoded string with a length + limit of 1024 characters. + + Format: + ``projects/{project_number}/locations/{location}/collections/{collection}/engines/{engine}`` + engine should be 1-63 characters, and valid characters are + /[a-z0-9][a-z0-9-_]*/. Otherwise, an INVALID_ARGUMENT error + is returned. + display_name (str): + Required. The display name of the engine. + Should be human readable. UTF-8 encoded string + with limit of 1024 characters. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp the Recommendation + Engine was created at. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp the Recommendation + Engine was last updated. + data_store_ids (MutableSequence[str]): + The data stores associated with this engine. + + For + [SOLUTION_TYPE_SEARCH][google.cloud.discoveryengine.v1alpha.SolutionType.SOLUTION_TYPE_SEARCH] + and + [SOLUTION_TYPE_RECOMMENDATION][google.cloud.discoveryengine.v1alpha.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + type of engines, they can only associate with at most one + data store. + + If + [solution_type][google.cloud.discoveryengine.v1alpha.Engine.solution_type] + is + [SOLUTION_TYPE_CHAT][google.cloud.discoveryengine.v1alpha.SolutionType.SOLUTION_TYPE_CHAT], + multiple + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]s + in the same + [Collection][google.cloud.discoveryengine.v1alpha.Collection] + can be associated here. + + Note that when used in + [CreateEngineRequest][google.cloud.discoveryengine.v1alpha.CreateEngineRequest], + one DataStore id must be provided as the system will use it + for necessary intializations. + solution_type (google.cloud.discoveryengine_v1alpha.types.SolutionType): + Required. The solutions of the engine. + industry_vertical (google.cloud.discoveryengine_v1alpha.types.IndustryVertical): + The industry vertical that the engine registers. The + restriction of the Engine industry vertical is based on + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]: + If unspecified, default to ``GENERIC``. Vertical on Engine + has to match vertical of the DataStore liniked to the + engine. + common_config (google.cloud.discoveryengine_v1alpha.types.Engine.CommonConfig): + Common config spec that specifies the + metadata of the engine. + """ + + class SearchEngineConfig(proto.Message): + r"""Configurations for a Search Engine. + + Attributes: + search_tier (google.cloud.discoveryengine_v1alpha.types.SearchTier): + The search feature tier of this engine. + + Different tiers might have different pricing. To learn more, + please check the pricing documentation. + + Defaults to + [SearchTier.SEARCH_TIER_STANDARD][google.cloud.discoveryengine.v1alpha.SearchTier.SEARCH_TIER_STANDARD] + if not specified. + search_add_ons (MutableSequence[google.cloud.discoveryengine_v1alpha.types.SearchAddOn]): + The add-on that this search engine enables. + """ + + search_tier: common.SearchTier = proto.Field( + proto.ENUM, + number=1, + enum=common.SearchTier, + ) + search_add_ons: MutableSequence[common.SearchAddOn] = proto.RepeatedField( + proto.ENUM, + number=2, + enum=common.SearchAddOn, + ) + + class SimilarDocumentsEngineConfig(proto.Message): + r"""Additional config specs for a ``similar-items`` engine. + """ + + class MediaRecommendationEngineConfig(proto.Message): + r"""Additional config specs for a Media Recommendation engine. + + Attributes: + type_ (str): + Required. The type of engine e.g. ``recommended-for-you``. + + This field together with + [optimization_objective][Engine.optimization_objective] + describe engine metadata to use to control engine training + and serving. + + Currently supported values: ``recommended-for-you``, + ``others-you-may-like``, ``more-like-this``, + ``most-popular-items``. + optimization_objective (str): + The optimization objective e.g. ``cvr``. + + This field together with + [optimization_objective][google.cloud.discoveryengine.v1alpha.Engine.MediaRecommendationEngineConfig.type] + describe engine metadata to use to control engine training + and serving. + + Currently supported values: ``ctr``, ``cvr``. + + If not specified, we choose default based on engine type. + Default depends on type of recommendation: + + ``recommended-for-you`` => ``ctr`` + + ``others-you-may-like`` => ``ctr`` + optimization_objective_config (google.cloud.discoveryengine_v1alpha.types.Engine.MediaRecommendationEngineConfig.OptimizationObjectiveConfig): + Name and value of the custom threshold for cvr + optimization_objective. For target_field ``watch-time``, + target_field_value must be an integer value indicating the + media progress time in seconds between (0, 86400] (excludes + 0, includes 86400) (e.g., 90). For target_field + ``watch-percentage``, the target_field_value must be a valid + float value between (0, 1.0] (excludes 0, includes 1.0) + (e.g., 0.5). + training_state (google.cloud.discoveryengine_v1alpha.types.Engine.MediaRecommendationEngineConfig.TrainingState): + The training state that the engine is in (e.g. ``TRAINING`` + or ``PAUSED``). + + Since part of the cost of running the service is frequency + of training - this can be used to determine when to train + engine in order to control cost. If not specified: the + default value for ``CreateEngine`` method is ``TRAINING``. + The default value for ``UpdateEngine`` method is to keep the + state the same as before. + """ + class TrainingState(proto.Enum): + r"""The training state of the engine. + + Values: + TRAINING_STATE_UNSPECIFIED (0): + Unspecified training state. + PAUSED (1): + The engine training is paused. + TRAINING (2): + The engine is training. + """ + TRAINING_STATE_UNSPECIFIED = 0 + PAUSED = 1 + TRAINING = 2 + + class OptimizationObjectiveConfig(proto.Message): + r"""Custom threshold for ``cvr`` optimization_objective. + + Attributes: + target_field (str): + Required. The name of the field to target. Currently + supported values: ``watch-percentage``, ``watch-time``. + target_field_value_float (float): + Required. The threshold to be applied to the + target (e.g., 0.5). + """ + + target_field: str = proto.Field( + proto.STRING, + number=1, + ) + target_field_value_float: float = proto.Field( + proto.FLOAT, + number=2, + ) + + type_: str = proto.Field( + proto.STRING, + number=1, + ) + optimization_objective: str = proto.Field( + proto.STRING, + number=2, + ) + optimization_objective_config: 'Engine.MediaRecommendationEngineConfig.OptimizationObjectiveConfig' = proto.Field( + proto.MESSAGE, + number=3, + message='Engine.MediaRecommendationEngineConfig.OptimizationObjectiveConfig', + ) + training_state: 'Engine.MediaRecommendationEngineConfig.TrainingState' = proto.Field( + proto.ENUM, + number=4, + enum='Engine.MediaRecommendationEngineConfig.TrainingState', + ) + + class ChatEngineConfig(proto.Message): + r"""Configurations for a Chat Engine. + + Attributes: + agent_creation_config (google.cloud.discoveryengine_v1alpha.types.Engine.ChatEngineConfig.AgentCreationConfig): + The configurationt generate the Dialogflow agent that is + associated to this Engine. + + Note that these configurations are one-time consumed by and + passed to Dialogflow service. It means they cannot be + retrieved using + [EngineService.GetEngine][google.cloud.discoveryengine.v1alpha.EngineService.GetEngine] + or + [EngineService.ListEngines][google.cloud.discoveryengine.v1alpha.EngineService.ListEngines] + API after engine creation. + dialogflow_agent_to_link (str): + The resource name of an exist Dialogflow agent to link to + this Chat Engine. Customers can either provide + ``agent_creation_config`` to create agent or provide an + agent name that links the agent with the Chat engine. + + Format: + ``projects//locations//agents/``. + + Note that the ``dialogflow_agent_to_link`` are one-time + consumed by and passed to Dialogflow service. It means they + cannot be retrieved using + [EngineService.GetEngine][google.cloud.discoveryengine.v1alpha.EngineService.GetEngine] + or + [EngineService.ListEngines][google.cloud.discoveryengine.v1alpha.EngineService.ListEngines] + API after engine creation. Please use + [chat_engine_metadata.dialogflow_agent][] for actual agent + association after Engine is created. + """ + + class AgentCreationConfig(proto.Message): + r"""Configurations for generating a Dialogflow agent. + + Note that these configurations are one-time consumed by and passed + to Dialogflow service. It means they cannot be retrieved using + [EngineService.GetEngine][google.cloud.discoveryengine.v1alpha.EngineService.GetEngine] + or + [EngineService.ListEngines][google.cloud.discoveryengine.v1alpha.EngineService.ListEngines] + API after engine creation. + + Attributes: + business (str): + Name of the company, organization or other + entity that the agent represents. Used for + knowledge connector LLM prompt and for knowledge + search. + default_language_code (str): + Required. The default language of the agent as a language + tag. See `Language + Support `__ + for a list of the currently supported language codes. + time_zone (str): + Required. The time zone of the agent from the `time zone + database `__, e.g., + America/New_York, Europe/Paris. + """ + + business: str = proto.Field( + proto.STRING, + number=1, + ) + default_language_code: str = proto.Field( + proto.STRING, + number=2, + ) + time_zone: str = proto.Field( + proto.STRING, + number=3, + ) + + agent_creation_config: 'Engine.ChatEngineConfig.AgentCreationConfig' = proto.Field( + proto.MESSAGE, + number=1, + message='Engine.ChatEngineConfig.AgentCreationConfig', + ) + dialogflow_agent_to_link: str = proto.Field( + proto.STRING, + number=2, + ) + + class CommonConfig(proto.Message): + r"""Common configurations for an Engine. + + Attributes: + company_name (str): + The name of the company, business or entity + that is associated with the engine. Setting this + may help improve LLM related features. + """ + + company_name: str = proto.Field( + proto.STRING, + number=1, + ) + + class RecommendationMetadata(proto.Message): + r"""Additional information of a recommendation engine. + + Attributes: + serving_state (google.cloud.discoveryengine_v1alpha.types.Engine.RecommendationMetadata.ServingState): + Output only. The serving state of the engine: ``ACTIVE``, + ``NOT_ACTIVE``. + data_state (google.cloud.discoveryengine_v1alpha.types.Engine.RecommendationMetadata.DataState): + Output only. The state of data requirements for this engine: + ``DATA_OK`` and ``DATA_ERROR``. + + Engine cannot be trained if the data is in ``DATA_ERROR`` + state. Engine can have ``DATA_ERROR`` state even if serving + state is ``ACTIVE``: engines were trained successfully + before, but cannot be refreshed because the underlying + engine no longer has sufficient data for training. + last_tune_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the latest + successful tune finished. Only applicable on + Media Recommendation engines. + tuning_operation (str): + Output only. The latest tune operation id + associated with the engine. Only applicable on + Media Recommendation engines. + + If present, this operation id can be used to + determine if there is an ongoing tune for this + engine. To check the operation status, send the + GetOperation request with this operation id in + the engine resource format. If no tuning has + happened for this engine, the string is empty. + """ + class ServingState(proto.Enum): + r"""The serving state of the recommendation engine. + + Values: + SERVING_STATE_UNSPECIFIED (0): + Unspecified serving state. + INACTIVE (1): + The engine is not serving. + ACTIVE (2): + The engine is serving and can be queried. + TUNED (3): + The engine is trained on tuned + hyperparameters and can be queried. + """ + SERVING_STATE_UNSPECIFIED = 0 + INACTIVE = 1 + ACTIVE = 2 + TUNED = 3 + + class DataState(proto.Enum): + r"""Describes whether this engine have sufficient training data + to be continuously trained. + + Values: + DATA_STATE_UNSPECIFIED (0): + Unspecified default value, should never be + explicitly set. + DATA_OK (1): + The engine has sufficient training data. + DATA_ERROR (2): + The engine does not have sufficient training + data. Error messages can be queried via + Stackdriver. + """ + DATA_STATE_UNSPECIFIED = 0 + DATA_OK = 1 + DATA_ERROR = 2 + + serving_state: 'Engine.RecommendationMetadata.ServingState' = proto.Field( + proto.ENUM, + number=1, + enum='Engine.RecommendationMetadata.ServingState', + ) + data_state: 'Engine.RecommendationMetadata.DataState' = proto.Field( + proto.ENUM, + number=2, + enum='Engine.RecommendationMetadata.DataState', + ) + last_tune_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + tuning_operation: str = proto.Field( + proto.STRING, + number=4, + ) + + class ChatEngineMetadata(proto.Message): + r"""Additional information of a Chat Engine. + Fields in this message are output only. + + Attributes: + dialogflow_agent (str): + The resource name of a Dialogflow agent, that this Chat + Engine refers to. + + Format: + ``projects//locations//agents/``. + """ + + dialogflow_agent: str = proto.Field( + proto.STRING, + number=1, + ) + + similar_documents_config: SimilarDocumentsEngineConfig = proto.Field( + proto.MESSAGE, + number=9, + oneof='engine_config', + message=SimilarDocumentsEngineConfig, + ) + chat_engine_config: ChatEngineConfig = proto.Field( + proto.MESSAGE, + number=11, + oneof='engine_config', + message=ChatEngineConfig, + ) + search_engine_config: SearchEngineConfig = proto.Field( + proto.MESSAGE, + number=13, + oneof='engine_config', + message=SearchEngineConfig, + ) + media_recommendation_engine_config: MediaRecommendationEngineConfig = proto.Field( + proto.MESSAGE, + number=14, + oneof='engine_config', + message=MediaRecommendationEngineConfig, + ) + recommendation_metadata: RecommendationMetadata = proto.Field( + proto.MESSAGE, + number=10, + oneof='engine_metadata', + message=RecommendationMetadata, + ) + chat_engine_metadata: ChatEngineMetadata = proto.Field( + proto.MESSAGE, + number=12, + oneof='engine_metadata', + message=ChatEngineMetadata, + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + data_store_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + solution_type: common.SolutionType = proto.Field( + proto.ENUM, + number=6, + enum=common.SolutionType, + ) + industry_vertical: common.IndustryVertical = proto.Field( + proto.ENUM, + number=16, + enum=common.IndustryVertical, + ) + common_config: CommonConfig = proto.Field( + proto.MESSAGE, + number=15, + message=CommonConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/engine_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/engine_service.py new file mode 100644 index 000000000000..7462beedf5dd --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/engine_service.py @@ -0,0 +1,356 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import engine as gcd_engine +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1alpha', + manifest={ + 'CreateEngineRequest', + 'CreateEngineMetadata', + 'DeleteEngineRequest', + 'DeleteEngineMetadata', + 'GetEngineRequest', + 'ListEnginesRequest', + 'ListEnginesResponse', + 'UpdateEngineRequest', + 'PauseEngineRequest', + 'ResumeEngineRequest', + 'TuneEngineRequest', + 'TuneEngineMetadata', + 'TuneEngineResponse', + }, +) + + +class CreateEngineRequest(proto.Message): + r"""Request for + [EngineService.CreateEngine][google.cloud.discoveryengine.v1alpha.EngineService.CreateEngine] + method. + + Attributes: + parent (str): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}``. + engine (google.cloud.discoveryengine_v1alpha.types.Engine): + Required. The + [Engine][google.cloud.discoveryengine.v1alpha.Engine] to + create. + engine_id (str): + Required. The ID to use for the + [Engine][google.cloud.discoveryengine.v1alpha.Engine], which + will become the final component of the + [Engine][google.cloud.discoveryengine.v1alpha.Engine]'s + resource name. + + This field must conform to + `RFC-1034 `__ standard + with a length limit of 63 characters. Otherwise, an + INVALID_ARGUMENT error is returned. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + engine: gcd_engine.Engine = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_engine.Engine, + ) + engine_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class CreateEngineMetadata(proto.Message): + r"""Metadata related to the progress of the + [EngineService.CreateEngine][google.cloud.discoveryengine.v1alpha.EngineService.CreateEngine] + operation. This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class DeleteEngineRequest(proto.Message): + r"""Request message for + [EngineService.DeleteEngine][google.cloud.discoveryengine.v1alpha.EngineService.DeleteEngine] + method. + + Attributes: + name (str): + Required. Full resource name of + [Engine][google.cloud.discoveryengine.v1alpha.Engine], such + as + ``projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}``. + + If the caller does not have permission to delete the + [Engine][google.cloud.discoveryengine.v1alpha.Engine], + regardless of whether or not it exists, a PERMISSION_DENIED + error is returned. + + If the [Engine][google.cloud.discoveryengine.v1alpha.Engine] + to delete does not exist, a NOT_FOUND error is returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteEngineMetadata(proto.Message): + r"""Metadata related to the progress of the + [EngineService.DeleteEngine][google.cloud.discoveryengine.v1alpha.EngineService.DeleteEngine] + operation. This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class GetEngineRequest(proto.Message): + r"""Request message for + [EngineService.GetEngine][google.cloud.discoveryengine.v1alpha.EngineService.GetEngine] + method. + + Attributes: + name (str): + Required. Full resource name of + [Engine][google.cloud.discoveryengine.v1alpha.Engine], such + as + ``projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListEnginesRequest(proto.Message): + r"""Request message for + [EngineService.ListEngines][google.cloud.discoveryengine.v1alpha.EngineService.ListEngines] + method. + + Attributes: + parent (str): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}/collections/{collection_id}``. + page_size (int): + Optional. Not supported. + page_token (str): + Optional. Not supported. + filter (str): + Optional. Filter by solution type. For example: + solution_type=SOLUTION_TYPE_SEARCH + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListEnginesResponse(proto.Message): + r"""Response message for + [EngineService.ListEngines][google.cloud.discoveryengine.v1alpha.EngineService.ListEngines] + method. + + Attributes: + engines (MutableSequence[google.cloud.discoveryengine_v1alpha.types.Engine]): + All the customer's + [Engine][google.cloud.discoveryengine.v1alpha.Engine]s. + next_page_token (str): + Not supported. + """ + + @property + def raw_page(self): + return self + + engines: MutableSequence[gcd_engine.Engine] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_engine.Engine, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateEngineRequest(proto.Message): + r"""Request message for + [EngineService.UpdateEngine][google.cloud.discoveryengine.v1alpha.EngineService.UpdateEngine] + method. + + Attributes: + engine (google.cloud.discoveryengine_v1alpha.types.Engine): + Required. The + [Engine][google.cloud.discoveryengine.v1alpha.Engine] to + update. + + If the caller does not have permission to update the + [Engine][google.cloud.discoveryengine.v1alpha.Engine], + regardless of whether or not it exists, a PERMISSION_DENIED + error is returned. + + If the [Engine][google.cloud.discoveryengine.v1alpha.Engine] + to update does not exist, a NOT_FOUND error is returned. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [Engine][google.cloud.discoveryengine.v1alpha.Engine] to + update. + + If an unsupported or unknown field is provided, an + INVALID_ARGUMENT error is returned. + """ + + engine: gcd_engine.Engine = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_engine.Engine, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class PauseEngineRequest(proto.Message): + r"""Request for pausing training of an engine. + + Attributes: + name (str): + Required. The name of the engine to pause. Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/engines/{engine_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ResumeEngineRequest(proto.Message): + r"""Request for resuming training of an engine. + + Attributes: + name (str): + Required. The name of the engine to resume. Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/engines/{engine_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class TuneEngineRequest(proto.Message): + r"""Request to manually start a tuning process now (instead of + waiting for the periodically scheduled tuning to happen). + + Attributes: + name (str): + Required. The resource name of the engine to tune. Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/engines/{engine_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class TuneEngineMetadata(proto.Message): + r"""Metadata associated with a tune operation. + + Attributes: + engine (str): + Required. The resource name of the engine that this tune + applies to. Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection_id}/engines/{engine_id}`` + """ + + engine: str = proto.Field( + proto.STRING, + number=1, + ) + + +class TuneEngineResponse(proto.Message): + r"""Response associated with a tune operation. + """ + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/import_config.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/import_config.py new file mode 100644 index 000000000000..34ef54f35016 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/import_config.py @@ -0,0 +1,607 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import document +from google.cloud.discoveryengine_v1alpha.types import user_event +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import date_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1alpha', + manifest={ + 'GcsSource', + 'BigQuerySource', + 'ImportErrorConfig', + 'ImportUserEventsRequest', + 'ImportUserEventsResponse', + 'ImportUserEventsMetadata', + 'ImportDocumentsMetadata', + 'ImportDocumentsRequest', + 'ImportDocumentsResponse', + }, +) + + +class GcsSource(proto.Message): + r"""Cloud Storage location for input content. + + Attributes: + input_uris (MutableSequence[str]): + Required. Cloud Storage URIs to input files. URI can be up + to 2000 characters long. URIs can match the full object path + (for example, ``gs://bucket/directory/object.json``) or a + pattern matching one or more files, such as + ``gs://bucket/directory/*.json``. + + A request can contain at most 100 files (or 100,000 files if + ``data_schema`` is ``content``). Each file can be up to 2 GB + (or 100 MB if ``data_schema`` is ``content``). + data_schema (str): + The schema to use when parsing the data from the source. + + Supported values for document imports: + + - ``document`` (default): One JSON + [Document][google.cloud.discoveryengine.v1alpha.Document] + per line. Each document must have a valid + [Document.id][google.cloud.discoveryengine.v1alpha.Document.id]. + - ``content``: Unstructured data (e.g. PDF, HTML). Each + file matched by ``input_uris`` becomes a document, with + the ID set to the first 128 bits of SHA256(URI) encoded + as a hex string. + - ``custom``: One custom data JSON per row in arbitrary + format that conforms to the defined + [Schema][google.cloud.discoveryengine.v1alpha.Schema] of + the data store. This can only be used by Gen App Builder. + - ``csv``: A CSV file with header conforming to the defined + [Schema][google.cloud.discoveryengine.v1alpha.Schema] of + the data store. Each entry after the header is imported + as a Document. This can only be used by Gen App Builder. + + Supported values for user even imports: + + - ``user_event`` (default): One JSON + [UserEvent][google.cloud.discoveryengine.v1alpha.UserEvent] + per line. + """ + + input_uris: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + data_schema: str = proto.Field( + proto.STRING, + number=2, + ) + + +class BigQuerySource(proto.Message): + r"""BigQuery source import data from. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + partition_date (google.type.date_pb2.Date): + BigQuery time partitioned table's \_PARTITIONDATE in + YYYY-MM-DD format. + + This field is a member of `oneof`_ ``partition``. + project_id (str): + The project ID (can be project # or ID) that + the BigQuery source is in with a length limit of + 128 characters. If not specified, inherits the + project ID from the parent request. + dataset_id (str): + Required. The BigQuery data set to copy the + data from with a length limit of 1,024 + characters. + table_id (str): + Required. The BigQuery table to copy the data + from with a length limit of 1,024 characters. + gcs_staging_dir (str): + Intermediate Cloud Storage directory used for + the import with a length limit of 2,000 + characters. Can be specified if one wants to + have the BigQuery export to a specific Cloud + Storage directory. + data_schema (str): + The schema to use when parsing the data from the source. + + Supported values for user event imports: + + - ``user_event`` (default): One + [UserEvent][google.cloud.discoveryengine.v1alpha.UserEvent] + per row. + + Supported values for document imports: + + - ``document`` (default): One + [Document][google.cloud.discoveryengine.v1alpha.Document] + format per row. Each document must have a valid + [Document.id][google.cloud.discoveryengine.v1alpha.Document.id] + and one of + [Document.json_data][google.cloud.discoveryengine.v1alpha.Document.json_data] + or + [Document.struct_data][google.cloud.discoveryengine.v1alpha.Document.struct_data]. + - ``custom``: One custom data per row in arbitrary format + that conforms to the defined + [Schema][google.cloud.discoveryengine.v1alpha.Schema] of + the data store. This can only be used by Gen App Builder. + """ + + partition_date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=5, + oneof='partition', + message=date_pb2.Date, + ) + project_id: str = proto.Field( + proto.STRING, + number=1, + ) + dataset_id: str = proto.Field( + proto.STRING, + number=2, + ) + table_id: str = proto.Field( + proto.STRING, + number=3, + ) + gcs_staging_dir: str = proto.Field( + proto.STRING, + number=4, + ) + data_schema: str = proto.Field( + proto.STRING, + number=6, + ) + + +class ImportErrorConfig(proto.Message): + r"""Configuration of destination for Import related errors. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_prefix (str): + Cloud Storage prefix for import errors. This must be an + empty, existing Cloud Storage directory. Import errors are + written to sharded files in this directory, one per line, as + a JSON-encoded ``google.rpc.Status`` message. + + This field is a member of `oneof`_ ``destination``. + """ + + gcs_prefix: str = proto.Field( + proto.STRING, + number=1, + oneof='destination', + ) + + +class ImportUserEventsRequest(proto.Message): + r"""Request message for the ImportUserEvents request. + + 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: + inline_source (google.cloud.discoveryengine_v1alpha.types.ImportUserEventsRequest.InlineSource): + The Inline source for the input content for + UserEvents. + + This field is a member of `oneof`_ ``source``. + gcs_source (google.cloud.discoveryengine_v1alpha.types.GcsSource): + Cloud Storage location for the input content. + + This field is a member of `oneof`_ ``source``. + bigquery_source (google.cloud.discoveryengine_v1alpha.types.BigQuerySource): + BigQuery input source. + + This field is a member of `oneof`_ ``source``. + parent (str): + Required. Parent DataStore resource name, of the form + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}`` + error_config (google.cloud.discoveryengine_v1alpha.types.ImportErrorConfig): + The desired location of errors incurred + during the Import. Cannot be set for inline user + event imports. + """ + + class InlineSource(proto.Message): + r"""The inline source for the input config for ImportUserEvents + method. + + Attributes: + user_events (MutableSequence[google.cloud.discoveryengine_v1alpha.types.UserEvent]): + Required. A list of user events to import. + Recommended max of 10k items. + """ + + user_events: MutableSequence[user_event.UserEvent] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=user_event.UserEvent, + ) + + inline_source: InlineSource = proto.Field( + proto.MESSAGE, + number=2, + oneof='source', + message=InlineSource, + ) + gcs_source: 'GcsSource' = proto.Field( + proto.MESSAGE, + number=3, + oneof='source', + message='GcsSource', + ) + bigquery_source: 'BigQuerySource' = proto.Field( + proto.MESSAGE, + number=4, + oneof='source', + message='BigQuerySource', + ) + parent: str = proto.Field( + proto.STRING, + number=1, + ) + error_config: 'ImportErrorConfig' = proto.Field( + proto.MESSAGE, + number=5, + message='ImportErrorConfig', + ) + + +class ImportUserEventsResponse(proto.Message): + r"""Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is returned by the + google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (MutableSequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + error_config (google.cloud.discoveryengine_v1alpha.types.ImportErrorConfig): + Echoes the destination for the complete + errors if this field was set in the request. + joined_events_count (int): + Count of user events imported with complete + existing Documents. + unjoined_events_count (int): + Count of user events imported, but with + Document information not found in the existing + Branch. + """ + + error_samples: MutableSequence[status_pb2.Status] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + error_config: 'ImportErrorConfig' = proto.Field( + proto.MESSAGE, + number=2, + message='ImportErrorConfig', + ) + joined_events_count: int = proto.Field( + proto.INT64, + number=3, + ) + unjoined_events_count: int = proto.Field( + proto.INT64, + number=4, + ) + + +class ImportUserEventsMetadata(proto.Message): + r"""Metadata related to the progress of the Import operation. + This is returned by the google.longrunning.Operation.metadata + field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + success_count (int): + Count of entries that were processed + successfully. + failure_count (int): + Count of entries that encountered errors + while processing. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + success_count: int = proto.Field( + proto.INT64, + number=3, + ) + failure_count: int = proto.Field( + proto.INT64, + number=4, + ) + + +class ImportDocumentsMetadata(proto.Message): + r"""Metadata related to the progress of the ImportDocuments + operation. This is returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + success_count (int): + Count of entries that were processed + successfully. + failure_count (int): + Count of entries that encountered errors + while processing. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + success_count: int = proto.Field( + proto.INT64, + number=3, + ) + failure_count: int = proto.Field( + proto.INT64, + number=4, + ) + + +class ImportDocumentsRequest(proto.Message): + r"""Request message for Import methods. + + 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: + inline_source (google.cloud.discoveryengine_v1alpha.types.ImportDocumentsRequest.InlineSource): + The Inline source for the input content for + documents. + + This field is a member of `oneof`_ ``source``. + gcs_source (google.cloud.discoveryengine_v1alpha.types.GcsSource): + Cloud Storage location for the input content. + + This field is a member of `oneof`_ ``source``. + bigquery_source (google.cloud.discoveryengine_v1alpha.types.BigQuerySource): + BigQuery input source. + + This field is a member of `oneof`_ ``source``. + parent (str): + Required. The parent branch resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. + Requires create/update permission. + error_config (google.cloud.discoveryengine_v1alpha.types.ImportErrorConfig): + The desired location of errors incurred + during the Import. + reconciliation_mode (google.cloud.discoveryengine_v1alpha.types.ImportDocumentsRequest.ReconciliationMode): + The mode of reconciliation between existing documents and + the documents to be imported. Defaults to + [ReconciliationMode.INCREMENTAL][google.cloud.discoveryengine.v1alpha.ImportDocumentsRequest.ReconciliationMode.INCREMENTAL]. + auto_generate_ids (bool): + Whether to automatically generate IDs for the documents if + absent. + + If set to ``true``, + [Document.id][google.cloud.discoveryengine.v1alpha.Document.id]s + are automatically generated based on the hash of the + payload, where IDs may not be consistent during multiple + imports. In which case + [ReconciliationMode.FULL][google.cloud.discoveryengine.v1alpha.ImportDocumentsRequest.ReconciliationMode.FULL] + is highly recommended to avoid duplicate contents. If unset + or set to ``false``, + [Document.id][google.cloud.discoveryengine.v1alpha.Document.id]s + have to be specified using + [id_field][google.cloud.discoveryengine.v1alpha.ImportDocumentsRequest.id_field], + otherwise, documents without IDs fail to be imported. + + Only set this field when using + [GcsSource][google.cloud.discoveryengine.v1alpha.GcsSource] + or + [BigQuerySource][google.cloud.discoveryengine.v1alpha.BigQuerySource], + and when + [GcsSource.data_schema][google.cloud.discoveryengine.v1alpha.GcsSource.data_schema] + or + [BigQuerySource.data_schema][google.cloud.discoveryengine.v1alpha.BigQuerySource.data_schema] + is ``custom`` or ``csv``. Otherwise, an INVALID_ARGUMENT + error is thrown. + id_field (str): + The field in the Cloud Storage and BigQuery sources that + indicates the unique IDs of the documents. + + For + [GcsSource][google.cloud.discoveryengine.v1alpha.GcsSource] + it is the key of the JSON field. For instance, ``my_id`` for + JSON ``{"my_id": "some_uuid"}``. For + [BigQuerySource][google.cloud.discoveryengine.v1alpha.BigQuerySource] + it is the column name of the BigQuery table where the unique + ids are stored. + + The values of the JSON field or the BigQuery column are used + as the + [Document.id][google.cloud.discoveryengine.v1alpha.Document.id]s. + The JSON field or the BigQuery column must be of string + type, and the values must be set as valid strings conform to + `RFC-1034 `__ with 1-63 + characters. Otherwise, documents without valid IDs fail to + be imported. + + Only set this field when using + [GcsSource][google.cloud.discoveryengine.v1alpha.GcsSource] + or + [BigQuerySource][google.cloud.discoveryengine.v1alpha.BigQuerySource], + and when + [GcsSource.data_schema][google.cloud.discoveryengine.v1alpha.GcsSource.data_schema] + or + [BigQuerySource.data_schema][google.cloud.discoveryengine.v1alpha.BigQuerySource.data_schema] + is ``custom``. And only set this field when + [auto_generate_ids][google.cloud.discoveryengine.v1alpha.ImportDocumentsRequest.auto_generate_ids] + is unset or set as ``false``. Otherwise, an INVALID_ARGUMENT + error is thrown. + + If it is unset, a default value ``_id`` is used when + importing from the allowed data sources. + """ + class ReconciliationMode(proto.Enum): + r"""Indicates how imported documents are reconciled with the + existing documents created or imported before. + + Values: + RECONCILIATION_MODE_UNSPECIFIED (0): + Defaults to ``INCREMENTAL``. + INCREMENTAL (1): + Inserts new documents or updates existing + documents. + FULL (2): + Calculates diff and replaces the entire + document dataset. Existing documents may be + deleted if they are not present in the source + location. + """ + RECONCILIATION_MODE_UNSPECIFIED = 0 + INCREMENTAL = 1 + FULL = 2 + + class InlineSource(proto.Message): + r"""The inline source for the input config for ImportDocuments + method. + + Attributes: + documents (MutableSequence[google.cloud.discoveryengine_v1alpha.types.Document]): + Required. A list of documents to update/create. Each + document must have a valid + [Document.id][google.cloud.discoveryengine.v1alpha.Document.id]. + Recommended max of 100 items. + """ + + documents: MutableSequence[document.Document] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=document.Document, + ) + + inline_source: InlineSource = proto.Field( + proto.MESSAGE, + number=2, + oneof='source', + message=InlineSource, + ) + gcs_source: 'GcsSource' = proto.Field( + proto.MESSAGE, + number=3, + oneof='source', + message='GcsSource', + ) + bigquery_source: 'BigQuerySource' = proto.Field( + proto.MESSAGE, + number=4, + oneof='source', + message='BigQuerySource', + ) + parent: str = proto.Field( + proto.STRING, + number=1, + ) + error_config: 'ImportErrorConfig' = proto.Field( + proto.MESSAGE, + number=5, + message='ImportErrorConfig', + ) + reconciliation_mode: ReconciliationMode = proto.Field( + proto.ENUM, + number=6, + enum=ReconciliationMode, + ) + auto_generate_ids: bool = proto.Field( + proto.BOOL, + number=8, + ) + id_field: str = proto.Field( + proto.STRING, + number=9, + ) + + +class ImportDocumentsResponse(proto.Message): + r"""Response of the + [ImportDocumentsRequest][google.cloud.discoveryengine.v1alpha.ImportDocumentsRequest]. + If the long running operation is done, then this message is returned + by the google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (MutableSequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + error_config (google.cloud.discoveryengine_v1alpha.types.ImportErrorConfig): + Echoes the destination for the complete + errors in the request if set. + """ + + error_samples: MutableSequence[status_pb2.Status] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + error_config: 'ImportErrorConfig' = proto.Field( + proto.MESSAGE, + number=2, + message='ImportErrorConfig', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/purge_config.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/purge_config.py new file mode 100644 index 000000000000..8356f4a59877 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/purge_config.py @@ -0,0 +1,247 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1alpha', + manifest={ + 'PurgeUserEventsRequest', + 'PurgeUserEventsResponse', + 'PurgeUserEventsMetadata', + 'PurgeDocumentsRequest', + 'PurgeDocumentsResponse', + 'PurgeDocumentsMetadata', + }, +) + + +class PurgeUserEventsRequest(proto.Message): + r"""Request message for PurgeUserEvents method. + + Attributes: + parent (str): + Required. The resource name of the catalog under which the + events are created. The format is + ``projects/${projectId}/locations/global/collections/{$collectionId}/dataStores/${dataStoreId}`` + filter (str): + Required. The filter string to specify the events to be + deleted with a length limit of 5,000 characters. The + eligible fields for filtering are: + + - ``eventType``: Double quoted + [UserEvent.event_type][google.cloud.discoveryengine.v1alpha.UserEvent.event_type] + string. + - ``eventTime``: in ISO 8601 "zulu" format. + - ``userPseudoId``: Double quoted string. Specifying this + will delete all events associated with a visitor. + - ``userId``: Double quoted string. Specifying this will + delete all events associated with a user. + + Examples: + + - Deleting all events in a time range: + ``eventTime > "2012-04-23T18:25:43.511Z" eventTime < "2012-04-23T18:30:43.511Z"`` + - Deleting specific eventType: ``eventType = "search"`` + - Deleting all events for a specific visitor: + ``userPseudoId = "visitor1024"`` + - Deleting all events inside a DataStore: ``*`` + + The filtering fields are assumed to have an implicit AND. + force (bool): + The ``force`` field is currently not supported. Purge user + event requests will permanently delete all purgeable events. + Once the development is complete: If ``force`` is set to + false, the method will return the expected purge count + without deleting any user events. This field will default to + false if not included in the request. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + force: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class PurgeUserEventsResponse(proto.Message): + r"""Response of the PurgeUserEventsRequest. If the long running + operation is successfully done, then this message is returned by + the google.longrunning.Operations.response field. + + Attributes: + purge_count (int): + The total count of events purged as a result + of the operation. + """ + + purge_count: int = proto.Field( + proto.INT64, + number=1, + ) + + +class PurgeUserEventsMetadata(proto.Message): + r"""Metadata related to the progress of the PurgeUserEvents + operation. This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + success_count (int): + Count of entries that were deleted + successfully. + failure_count (int): + Count of entries that encountered errors + while processing. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + success_count: int = proto.Field( + proto.INT64, + number=3, + ) + failure_count: int = proto.Field( + proto.INT64, + number=4, + ) + + +class PurgeDocumentsRequest(proto.Message): + r"""Request message for + [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.PurgeDocuments] + method. + + Attributes: + parent (str): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. + filter (str): + Required. Filter matching documents to purge. Only currently + supported value is ``*`` (all items). + force (bool): + Actually performs the purge. If ``force`` is set to false, + return the expected purge count without deleting any + documents. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + force: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class PurgeDocumentsResponse(proto.Message): + r"""Response message for + [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.PurgeDocuments] + method. If the long running operation is successfully done, then + this message is returned by the + google.longrunning.Operations.response field. + + Attributes: + purge_count (int): + The total count of documents purged as a + result of the operation. + purge_sample (MutableSequence[str]): + A sample of document names that will be deleted. Only + populated if ``force`` is set to false. A max of 100 names + will be returned and the names are chosen at random. + """ + + purge_count: int = proto.Field( + proto.INT64, + number=1, + ) + purge_sample: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class PurgeDocumentsMetadata(proto.Message): + r"""Metadata related to the progress of the PurgeDocuments + operation. This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + success_count (int): + Count of entries that were deleted + successfully. + failure_count (int): + Count of entries that encountered errors + while processing. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + success_count: int = proto.Field( + proto.INT64, + number=3, + ) + failure_count: int = proto.Field( + proto.INT64, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/recommendation_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/recommendation_service.py new file mode 100644 index 000000000000..7aec69ccc590 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/recommendation_service.py @@ -0,0 +1,287 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import document as gcd_document +from google.cloud.discoveryengine_v1alpha.types import user_event as gcd_user_event +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1alpha', + manifest={ + 'RecommendRequest', + 'RecommendResponse', + }, +) + + +class RecommendRequest(proto.Message): + r"""Request message for Recommend method. + + Attributes: + serving_config (str): + Required. Full resource name of a + [ServingConfig][google.cloud.discoveryengine.v1alpha.ServingConfig]: + ``projects/*/locations/global/collections/*/engines/*/servingConfigs/*``, + or + ``projects/*/locations/global/collections/*/dataStores/*/servingConfigs/*`` + + One default serving config is created along with your + recommendation engine creation. The engine ID will be used + as the ID of the default serving config. For example, for + Engine + ``projects/*/locations/global/collections/*/engines/my-engine``, + you can use + ``projects/*/locations/global/collections/*/engines/my-engine/servingConfigs/my-engine`` + for your [Recommend][] requests. + user_event (google.cloud.discoveryengine_v1alpha.types.UserEvent): + Required. Context about the user, what they are looking at + and what action they took to trigger the Recommend request. + Note that this user event detail won't be ingested to + userEvent logs. Thus, a separate userEvent write request is + required for event logging. + + Don't set + [UserEvent.user_pseudo_id][google.cloud.discoveryengine.v1alpha.UserEvent.user_pseudo_id] + or + [UserEvent.user_info.user_id][google.cloud.discoveryengine.v1alpha.UserInfo.user_id] + to the same fixed ID for different users. If you are trying + to receive non-personalized recommendations (not + recommended; this can negatively impact model performance), + instead set + [UserEvent.user_pseudo_id][google.cloud.discoveryengine.v1alpha.UserEvent.user_pseudo_id] + to a random unique ID and leave + [UserEvent.user_info.user_id][google.cloud.discoveryengine.v1alpha.UserInfo.user_id] + unset. + page_size (int): + Maximum number of results to return. Set this + property to the number of recommendation results + needed. If zero, the service will choose a + reasonable default. The maximum allowed value is + 100. Values above 100 will be coerced to 100. + filter (str): + Filter for restricting recommendation results with a length + limit of 5,000 characters. Currently, only filter + expressions on the ``filter_tags`` attribute is supported. + + Examples: + + - ``(filter_tags: ANY("Red", "Blue") OR filter_tags: ANY("Hot", "Cold"))`` + - ``(filter_tags: ANY("Red", "Blue")) AND NOT (filter_tags: ANY("Green"))`` + + If ``attributeFilteringSyntax`` is set to true under the + ``params`` field, then attribute-based expressions are + expected instead of the above described tag-based syntax. + Examples: + + - (launguage: ANY("en", "es")) AND NOT (categories: + ANY("Movie")) + - (available: true) AND (launguage: ANY("en", "es")) OR + (categories: ANY("Movie")) + + If your filter blocks all results, the API will return + generic (unfiltered) popular Documents. If you only want + results strictly matching the filters, set + ``strictFiltering`` to True in + [RecommendRequest.params][google.cloud.discoveryengine.v1alpha.RecommendRequest.params] + to receive empty results instead. + + Note that the API will never return + [Document][google.cloud.discoveryengine.v1alpha.Document]s + with ``storageStatus`` of ``EXPIRED`` or ``DELETED`` + regardless of filter choices. + validate_only (bool): + Use validate only mode for this + recommendation query. If set to true, a fake + model will be used that returns arbitrary + Document IDs. Note that the validate only mode + should only be used for testing the API, or if + the model is not ready. + params (MutableMapping[str, google.protobuf.struct_pb2.Value]): + Additional domain specific parameters for the + recommendations. + + Allowed values: + + - ``returnDocument``: Boolean. If set to true, the + associated Document object will be returned in + [RecommendResponse.RecommendationResult.document][google.cloud.discoveryengine.v1alpha.RecommendResponse.RecommendationResult.document]. + - ``returnScore``: Boolean. If set to true, the + recommendation 'score' corresponding to each returned + Document will be set in + [RecommendResponse.RecommendationResult.metadata][google.cloud.discoveryengine.v1alpha.RecommendResponse.RecommendationResult.metadata]. + The given 'score' indicates the probability of a Document + conversion given the user's context and history. + - ``strictFiltering``: Boolean. True by default. If set to + false, the service will return generic (unfiltered) + popular Documents instead of empty if your filter blocks + all recommendation results. + - ``diversityLevel``: String. Default empty. If set to be + non-empty, then it needs to be one of: + + - ``no-diversity`` + - ``low-diversity`` + - ``medium-diversity`` + - ``high-diversity`` + - ``auto-diversity`` This gives request-level control + and adjusts recommendation results based on Document + category. + + - ``attributeFilteringSyntax``: Boolean. False by default. + If set to true, the ``filter`` field is interpreted + according to the new, attribute-based syntax. + user_labels (MutableMapping[str, str]): + The user labels applied to a resource must meet the + following requirements: + + - Each resource can have multiple labels, up to a maximum + of 64. + - Each label must be a key-value pair. + - Keys have a minimum length of 1 character and a maximum + length of 63 characters and cannot be empty. Values can + be empty and have a maximum length of 63 characters. + - Keys and values can contain only lowercase letters, + numeric characters, underscores, and dashes. All + characters must use UTF-8 encoding, and international + characters are allowed. + - The key portion of a label must be unique. However, you + can use the same key with multiple resources. + - Keys must start with a lowercase letter or international + character. + + See `Requirements for + labels `__ + for more details. + """ + + serving_config: str = proto.Field( + proto.STRING, + number=1, + ) + user_event: gcd_user_event.UserEvent = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_user_event.UserEvent, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=5, + ) + params: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=6, + message=struct_pb2.Value, + ) + user_labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=8, + ) + + +class RecommendResponse(proto.Message): + r"""Response message for Recommend method. + + Attributes: + results (MutableSequence[google.cloud.discoveryengine_v1alpha.types.RecommendResponse.RecommendationResult]): + A list of recommended Documents. The order + represents the ranking (from the most relevant + Document to the least). + attribution_token (str): + A unique attribution token. This should be included in the + [UserEvent][google.cloud.discoveryengine.v1alpha.UserEvent] + logs resulting from this recommendation, which enables + accurate attribution of recommendation model performance. + missing_ids (MutableSequence[str]): + IDs of documents in the request that were + missing from the default Branch associated with + the requested ServingConfig. + validate_only (bool): + True if + [RecommendRequest.validate_only][google.cloud.discoveryengine.v1alpha.RecommendRequest.validate_only] + was set. + """ + + class RecommendationResult(proto.Message): + r"""RecommendationResult represents a generic recommendation + result with associated metadata. + + Attributes: + id (str): + Resource ID of the recommended Document. + document (google.cloud.discoveryengine_v1alpha.types.Document): + Set if ``returnDocument`` is set to true in + [RecommendRequest.params][google.cloud.discoveryengine.v1alpha.RecommendRequest.params]. + metadata (MutableMapping[str, google.protobuf.struct_pb2.Value]): + Additional Document metadata / annotations. + + Possible values: + + - ``score``: Recommendation score in double value. Is set + if ``returnScore`` is set to true in + [RecommendRequest.params][google.cloud.discoveryengine.v1alpha.RecommendRequest.params]. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + document: gcd_document.Document = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_document.Document, + ) + metadata: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=3, + message=struct_pb2.Value, + ) + + results: MutableSequence[RecommendationResult] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=RecommendationResult, + ) + attribution_token: str = proto.Field( + proto.STRING, + number=2, + ) + missing_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/schema.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/schema.py new file mode 100644 index 000000000000..6907d55e59d8 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/schema.py @@ -0,0 +1,413 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1alpha', + manifest={ + 'Schema', + 'FieldConfig', + }, +) + + +class Schema(proto.Message): + r"""Defines the structure and layout of a type of document data. + + 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: + struct_schema (google.protobuf.struct_pb2.Struct): + The structured representation of the schema. + + This field is a member of `oneof`_ ``schema``. + json_schema (str): + The JSON representation of the schema. + + This field is a member of `oneof`_ ``schema``. + name (str): + Immutable. The full resource name of the schema, in the + format of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. + + This field must be a UTF-8 encoded string with a length + limit of 1024 characters. + field_configs (MutableSequence[google.cloud.discoveryengine_v1alpha.types.FieldConfig]): + Output only. Configurations for fields of the + schema. + """ + + struct_schema: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=2, + oneof='schema', + message=struct_pb2.Struct, + ) + json_schema: str = proto.Field( + proto.STRING, + number=3, + oneof='schema', + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + field_configs: MutableSequence['FieldConfig'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='FieldConfig', + ) + + +class FieldConfig(proto.Message): + r"""Configurations for fields of a schema. For example, + configuring a field is indexable, or searchable. + + Attributes: + field_path (str): + Required. Field path of the schema field. For example: + ``title``, ``description``, ``release_info.release_year``. + field_type (google.cloud.discoveryengine_v1alpha.types.FieldConfig.FieldType): + Output only. Raw type of the field. + indexable_option (google.cloud.discoveryengine_v1alpha.types.FieldConfig.IndexableOption): + If + [indexable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.indexable_option] + is + [INDEXABLE_ENABLED][google.cloud.discoveryengine.v1alpha.FieldConfig.IndexableOption.INDEXABLE_ENABLED], + field values are indexed so that it can be filtered or + faceted in + [SearchService.Search][google.cloud.discoveryengine.v1alpha.SearchService.Search]. + + If + [indexable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.indexable_option] + is unset, the server behavior defaults to + [INDEXABLE_DISABLED][google.cloud.discoveryengine.v1alpha.FieldConfig.IndexableOption.INDEXABLE_DISABLED] + for fields that support setting indexable options. For those + fields that do not support setting indexable options, such + as ``object`` and ``boolean`` and key properties, the server + will skip + [indexable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.indexable_option] + setting, and setting + [indexable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.indexable_option] + for those fields will throw ``INVALID_ARGUMENT`` error. + dynamic_facetable_option (google.cloud.discoveryengine_v1alpha.types.FieldConfig.DynamicFacetableOption): + If + [dynamic_facetable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.dynamic_facetable_option] + is + [DYNAMIC_FACETABLE_ENABLED][google.cloud.discoveryengine.v1alpha.FieldConfig.DynamicFacetableOption.DYNAMIC_FACETABLE_ENABLED], + field values are available for dynamic facet. Could only be + [DYNAMIC_FACETABLE_DISABLED][google.cloud.discoveryengine.v1alpha.FieldConfig.DynamicFacetableOption.DYNAMIC_FACETABLE_DISABLED] + if + [FieldConfig.indexable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.indexable_option] + is + [INDEXABLE_DISABLED][google.cloud.discoveryengine.v1alpha.FieldConfig.IndexableOption.INDEXABLE_DISABLED]. + Otherwise, an ``INVALID_ARGUMENT`` error will be returned. + + If + [dynamic_facetable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.dynamic_facetable_option] + is unset, the server behavior defaults to + [DYNAMIC_FACETABLE_DISABLED][google.cloud.discoveryengine.v1alpha.FieldConfig.DynamicFacetableOption.DYNAMIC_FACETABLE_DISABLED] + for fields that support setting dynamic facetable options. + For those fields that do not support setting dynamic + facetable options, such as ``object`` and ``boolean``, the + server will skip dynamic facetable option setting, and + setting + [dynamic_facetable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.dynamic_facetable_option] + for those fields will throw ``INVALID_ARGUMENT`` error. + searchable_option (google.cloud.discoveryengine_v1alpha.types.FieldConfig.SearchableOption): + If + [searchable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.searchable_option] + is + [SEARCHABLE_ENABLED][google.cloud.discoveryengine.v1alpha.FieldConfig.SearchableOption.SEARCHABLE_ENABLED], + field values are searchable by text queries in + [SearchService.Search][google.cloud.discoveryengine.v1alpha.SearchService.Search]. + + If + [SEARCHABLE_ENABLED][google.cloud.discoveryengine.v1alpha.FieldConfig.SearchableOption.SEARCHABLE_ENABLED] + but field type is numerical, field values will not be + searchable by text queries in + [SearchService.Search][google.cloud.discoveryengine.v1alpha.SearchService.Search], + as there are no text values associated to numerical fields. + + If + [searchable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.searchable_option] + is unset, the server behavior defaults to + [SEARCHABLE_DISABLED][google.cloud.discoveryengine.v1alpha.FieldConfig.SearchableOption.SEARCHABLE_DISABLED] + for fields that support setting searchable options. Only + ``string`` fields that have no key property mapping support + setting + [searchable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.searchable_option]. + + For those fields that do not support setting searchable + options, the server will skip searchable option setting, and + setting + [searchable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.searchable_option] + for those fields will throw ``INVALID_ARGUMENT`` error. + retrievable_option (google.cloud.discoveryengine_v1alpha.types.FieldConfig.RetrievableOption): + If + [retrievable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.retrievable_option] + is + [RETRIEVABLE_ENABLED][google.cloud.discoveryengine.v1alpha.FieldConfig.RetrievableOption.RETRIEVABLE_ENABLED], + field values are included in the search results. + + If + [retrievable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.retrievable_option] + is unset, the server behavior defaults to + [RETRIEVABLE_DISABLED][google.cloud.discoveryengine.v1alpha.FieldConfig.RetrievableOption.RETRIEVABLE_DISABLED] + for fields that support setting retrievable options. For + those fields that do not support setting retrievable + options, such as ``object`` and ``boolean``, the server will + skip retrievable option setting, and setting + [retrievable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.retrievable_option] + for those fields will throw ``INVALID_ARGUMENT`` error. + completable_option (google.cloud.discoveryengine_v1alpha.types.FieldConfig.CompletableOption): + If + [completable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.completable_option] + is + [COMPLETABLE_ENABLED][google.cloud.discoveryengine.v1alpha.FieldConfig.CompletableOption.COMPLETABLE_ENABLED], + field values are directly used and returned as suggestions + for Autocomplete in + [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1alpha.CompletionService.CompleteQuery]. + + If + [completable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.completable_option] + is unset, the server behavior defaults to + [COMPLETABLE_DISABLED][google.cloud.discoveryengine.v1alpha.FieldConfig.CompletableOption.COMPLETABLE_DISABLED] + for fields that support setting completable options, which + are just ``string`` fields. For those fields that do not + support setting completable options, the server will skip + completable option setting, and setting + [completable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.completable_option] + for those fields will throw ``INVALID_ARGUMENT`` error. + recs_filterable_option (google.cloud.discoveryengine_v1alpha.types.FieldConfig.FilterableOption): + If + [recs_filterable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.recs_filterable_option] + is + [FILTERABLE_ENABLED][google.cloud.discoveryengine.v1alpha.FieldConfig.FilterableOption.FILTERABLE_ENABLED], + field values are filterable by filter expression in + [RecommendationService.Recommend][google.cloud.discoveryengine.v1alpha.RecommendationService.Recommend]. + + If + [FILTERABLE_ENABLED][google.cloud.discoveryengine.v1alpha.FieldConfig.FilterableOption.FILTERABLE_ENABLED] + but the field type is numerical, field values are not + filterable by text queries in + [RecommendationService.Recommend][google.cloud.discoveryengine.v1alpha.RecommendationService.Recommend]. + Only textual fields are supported. + + If + [recs_filterable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.recs_filterable_option] + is unset, the default setting is + [FILTERABLE_DISABLED][google.cloud.discoveryengine.v1alpha.FieldConfig.FilterableOption.FILTERABLE_DISABLED] + for fields that support setting filterable options. + + When a field set to [FILTERABLE_DISABLED] is filtered, a + warning is generated and an empty result is returned. + key_property_type (str): + Output only. Type of the key property that this field is + mapped to. Empty string if this is not annotated as mapped + to a key property. + + Example types are ``title``, ``description``. Full list is + defined by ``keyPropertyMapping`` in the schema field + annotation. + + If the schema field has a ``KeyPropertyMapping`` annotation, + ``indexable_option`` and ``searchable_option`` of this field + cannot be modified. + """ + class FieldType(proto.Enum): + r"""Field value type in the Schema. + + Values: + FIELD_TYPE_UNSPECIFIED (0): + Field type is unspecified. + OBJECT (1): + Field value type is Object. + STRING (2): + Field value type is String. + NUMBER (3): + Field value type is Number. + INTEGER (4): + Field value type is Integer. + BOOLEAN (5): + Field value type is Boolean. + GEOLOCATION (6): + Field value type is Geolocation. + """ + FIELD_TYPE_UNSPECIFIED = 0 + OBJECT = 1 + STRING = 2 + NUMBER = 3 + INTEGER = 4 + BOOLEAN = 5 + GEOLOCATION = 6 + + class IndexableOption(proto.Enum): + r"""The setting of Indexable options in schema. + + Values: + INDEXABLE_OPTION_UNSPECIFIED (0): + Value used when unset. + INDEXABLE_ENABLED (1): + Indexable option enabled for a schema field. + INDEXABLE_DISABLED (2): + Indexable option disabled for a schema field. + """ + INDEXABLE_OPTION_UNSPECIFIED = 0 + INDEXABLE_ENABLED = 1 + INDEXABLE_DISABLED = 2 + + class DynamicFacetableOption(proto.Enum): + r"""The status of the dynamic facetable option of a schema field. + + Values: + DYNAMIC_FACETABLE_OPTION_UNSPECIFIED (0): + Value used when unset. + DYNAMIC_FACETABLE_ENABLED (1): + Dynamic facetable option enabled for a schema + field. + DYNAMIC_FACETABLE_DISABLED (2): + Dynamic facetable option disabled for a + schema field. + """ + DYNAMIC_FACETABLE_OPTION_UNSPECIFIED = 0 + DYNAMIC_FACETABLE_ENABLED = 1 + DYNAMIC_FACETABLE_DISABLED = 2 + + class SearchableOption(proto.Enum): + r"""The setting of Searchable options in schema. + + Values: + SEARCHABLE_OPTION_UNSPECIFIED (0): + Value used when unset. + SEARCHABLE_ENABLED (1): + Searchable option enabled for a schema field. + SEARCHABLE_DISABLED (2): + Searchable option disabled for a schema + field. + """ + SEARCHABLE_OPTION_UNSPECIFIED = 0 + SEARCHABLE_ENABLED = 1 + SEARCHABLE_DISABLED = 2 + + class RetrievableOption(proto.Enum): + r"""The setting of Retrievable options in schema. + + Values: + RETRIEVABLE_OPTION_UNSPECIFIED (0): + Value used when unset. + RETRIEVABLE_ENABLED (1): + Retrievable option enabled for a schema + field. + RETRIEVABLE_DISABLED (2): + Retrievable option disabled for a schema + field. + """ + RETRIEVABLE_OPTION_UNSPECIFIED = 0 + RETRIEVABLE_ENABLED = 1 + RETRIEVABLE_DISABLED = 2 + + class CompletableOption(proto.Enum): + r"""The setting of Completable options in schema. + + Values: + COMPLETABLE_OPTION_UNSPECIFIED (0): + Value used when unset. + COMPLETABLE_ENABLED (1): + Completable option enabled for a schema + field. + COMPLETABLE_DISABLED (2): + Completable option disabled for a schema + field. + """ + COMPLETABLE_OPTION_UNSPECIFIED = 0 + COMPLETABLE_ENABLED = 1 + COMPLETABLE_DISABLED = 2 + + class FilterableOption(proto.Enum): + r"""Sets the filterable option for schema fields. + + Values: + FILTERABLE_OPTION_UNSPECIFIED (0): + Value used when unset. + FILTERABLE_ENABLED (1): + Filterable option enabled for a schema field. + FILTERABLE_DISABLED (2): + Filterable option disabled for a schema + field. + """ + FILTERABLE_OPTION_UNSPECIFIED = 0 + FILTERABLE_ENABLED = 1 + FILTERABLE_DISABLED = 2 + + field_path: str = proto.Field( + proto.STRING, + number=1, + ) + field_type: FieldType = proto.Field( + proto.ENUM, + number=2, + enum=FieldType, + ) + indexable_option: IndexableOption = proto.Field( + proto.ENUM, + number=3, + enum=IndexableOption, + ) + dynamic_facetable_option: DynamicFacetableOption = proto.Field( + proto.ENUM, + number=4, + enum=DynamicFacetableOption, + ) + searchable_option: SearchableOption = proto.Field( + proto.ENUM, + number=5, + enum=SearchableOption, + ) + retrievable_option: RetrievableOption = proto.Field( + proto.ENUM, + number=6, + enum=RetrievableOption, + ) + completable_option: CompletableOption = proto.Field( + proto.ENUM, + number=8, + enum=CompletableOption, + ) + recs_filterable_option: FilterableOption = proto.Field( + proto.ENUM, + number=9, + enum=FilterableOption, + ) + key_property_type: str = proto.Field( + proto.STRING, + number=7, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/schema_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/schema_service.py new file mode 100644 index 000000000000..0e7a35f7482a --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/schema_service.py @@ -0,0 +1,291 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import schema as gcd_schema +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1alpha', + manifest={ + 'GetSchemaRequest', + 'ListSchemasRequest', + 'ListSchemasResponse', + 'CreateSchemaRequest', + 'UpdateSchemaRequest', + 'DeleteSchemaRequest', + 'CreateSchemaMetadata', + 'UpdateSchemaMetadata', + 'DeleteSchemaMetadata', + }, +) + + +class GetSchemaRequest(proto.Message): + r"""Request message for + [SchemaService.GetSchema][google.cloud.discoveryengine.v1alpha.SchemaService.GetSchema] + method. + + Attributes: + name (str): + Required. The full resource name of the schema, in the + format of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListSchemasRequest(proto.Message): + r"""Request message for + [SchemaService.ListSchemas][google.cloud.discoveryengine.v1alpha.SchemaService.ListSchemas] + method. + + Attributes: + parent (str): + Required. The parent data store resource name, in the format + of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. + page_size (int): + The maximum number of + [Schema][google.cloud.discoveryengine.v1alpha.Schema]s to + return. The service may return fewer than this value. + + If unspecified, at most 100 + [Schema][google.cloud.discoveryengine.v1alpha.Schema]s will + be returned. + + The maximum value is 1000; values above 1000 will be coerced + to 1000. + page_token (str): + A page token, received from a previous + [SchemaService.ListSchemas][google.cloud.discoveryengine.v1alpha.SchemaService.ListSchemas] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [SchemaService.ListSchemas][google.cloud.discoveryengine.v1alpha.SchemaService.ListSchemas] + 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 ListSchemasResponse(proto.Message): + r"""Response message for + [SchemaService.ListSchemas][google.cloud.discoveryengine.v1alpha.SchemaService.ListSchemas] + method. + + Attributes: + schemas (MutableSequence[google.cloud.discoveryengine_v1alpha.types.Schema]): + The [Schema][google.cloud.discoveryengine.v1alpha.Schema]s. + next_page_token (str): + A token that can be sent as + [ListSchemasRequest.page_token][google.cloud.discoveryengine.v1alpha.ListSchemasRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + schemas: MutableSequence[gcd_schema.Schema] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_schema.Schema, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateSchemaRequest(proto.Message): + r"""Request message for + [SchemaService.CreateSchema][google.cloud.discoveryengine.v1alpha.SchemaService.CreateSchema] + method. + + Attributes: + parent (str): + Required. The parent data store resource name, in the format + of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. + schema (google.cloud.discoveryengine_v1alpha.types.Schema): + Required. The + [Schema][google.cloud.discoveryengine.v1alpha.Schema] to + create. + schema_id (str): + Required. The ID to use for the + [Schema][google.cloud.discoveryengine.v1alpha.Schema], which + will become the final component of the + [Schema.name][google.cloud.discoveryengine.v1alpha.Schema.name]. + + This field should conform to + `RFC-1034 `__ standard + with a length limit of 63 characters. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + schema: gcd_schema.Schema = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_schema.Schema, + ) + schema_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateSchemaRequest(proto.Message): + r"""Request message for + [SchemaService.UpdateSchema][google.cloud.discoveryengine.v1alpha.SchemaService.UpdateSchema] + method. + + Attributes: + schema (google.cloud.discoveryengine_v1alpha.types.Schema): + Required. The + [Schema][google.cloud.discoveryengine.v1alpha.Schema] to + update. + allow_missing (bool): + If set to true, and the + [Schema][google.cloud.discoveryengine.v1alpha.Schema] is not + found, a new + [Schema][google.cloud.discoveryengine.v1alpha.Schema] will + be created. In this situation, ``update_mask`` is ignored. + """ + + schema: gcd_schema.Schema = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_schema.Schema, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class DeleteSchemaRequest(proto.Message): + r"""Request message for + [SchemaService.DeleteSchema][google.cloud.discoveryengine.v1alpha.SchemaService.DeleteSchema] + method. + + Attributes: + name (str): + Required. The full resource name of the schema, in the + format of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateSchemaMetadata(proto.Message): + r"""Metadata for Create Schema LRO. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class UpdateSchemaMetadata(proto.Message): + r"""Metadata for UpdateSchema LRO. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class DeleteSchemaMetadata(proto.Message): + r"""Metadata for DeleteSchema LRO. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/search_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/search_service.py new file mode 100644 index 000000000000..c8a300511f68 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/search_service.py @@ -0,0 +1,1365 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import common +from google.cloud.discoveryengine_v1alpha.types import document as gcd_document +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1alpha', + manifest={ + 'SearchRequest', + 'SearchResponse', + }, +) + + +class SearchRequest(proto.Message): + r"""Request message for + [SearchService.Search][google.cloud.discoveryengine.v1alpha.SearchService.Search] + method. + + Attributes: + serving_config (str): + Required. The resource name of the Search serving config, + such as + ``projects/*/locations/global/collections/default_collection/engines/*/servingConfigs/default_serving_config``, + or + ``projects/*/locations/global/collections/default_collection/dataStores/default_data_store/servingConfigs/default_serving_config``. + This field is used to identify the serving configuration + name, set of models used to make the search. + branch (str): + The branch resource name, such as + ``projects/*/locations/global/collections/default_collection/dataStores/default_data_store/branches/0``. + + Use ``default_branch`` as the branch ID or leave this field + empty, to search documents under the default branch. + query (str): + Raw search query. + image_query (google.cloud.discoveryengine_v1alpha.types.SearchRequest.ImageQuery): + Raw image query. + page_size (int): + Maximum number of + [Document][google.cloud.discoveryengine.v1alpha.Document]s + to return. If unspecified, defaults to a reasonable value. + The maximum allowed value is 100. Values above 100 are + coerced to 100. + + If this field is negative, an ``INVALID_ARGUMENT`` is + returned. + page_token (str): + A page token received from a previous + [SearchService.Search][google.cloud.discoveryengine.v1alpha.SearchService.Search] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [SearchService.Search][google.cloud.discoveryengine.v1alpha.SearchService.Search] + must match the call that provided the page token. Otherwise, + an ``INVALID_ARGUMENT`` error is returned. + offset (int): + A 0-indexed integer that specifies the current offset (that + is, starting result location, amongst the + [Document][google.cloud.discoveryengine.v1alpha.Document]s + deemed by the API as relevant) in search results. This field + is only considered if + [page_token][google.cloud.discoveryengine.v1alpha.SearchRequest.page_token] + is unset. + + If this field is negative, an ``INVALID_ARGUMENT`` is + returned. + filter (str): + The filter syntax consists of an expression language for + constructing a predicate from one or more fields of the + documents being filtered. Filter expression is + case-sensitive. + + If this field is unrecognizable, an ``INVALID_ARGUMENT`` is + returned. + + Filtering in Vertex AI Search is done by mapping the LHS + filter key to a key property defined in the Vertex AI Search + backend -- this mapping is defined by the customer in their + schema. For example a media customer might have a field + 'name' in their schema. In this case the filter would look + like this: filter --> name:'ANY("king kong")' + + For more information about filtering including syntax and + filter operators, see + `Filter `__ + order_by (str): + The order in which documents are returned. Documents can be + ordered by a field in an + [Document][google.cloud.discoveryengine.v1alpha.Document] + object. Leave it unset if ordered by relevance. ``order_by`` + expression is case-sensitive. For more information on + ordering, see + `Ordering `__ + + If this field is unrecognizable, an ``INVALID_ARGUMENT`` is + returned. + user_info (google.cloud.discoveryengine_v1alpha.types.UserInfo): + Information about the end user. Highly recommended for + analytics. + [UserInfo.user_agent][google.cloud.discoveryengine.v1alpha.UserInfo.user_agent] + is used to deduce ``device_type`` for analytics. + facet_specs (MutableSequence[google.cloud.discoveryengine_v1alpha.types.SearchRequest.FacetSpec]): + Facet specifications for faceted search. If empty, no facets + are returned. + + A maximum of 100 values are allowed. Otherwise, an + ``INVALID_ARGUMENT`` error is returned. + boost_spec (google.cloud.discoveryengine_v1alpha.types.SearchRequest.BoostSpec): + Boost specification to boost certain documents. For more + information on boosting, see + `Boosting `__ + params (MutableMapping[str, google.protobuf.struct_pb2.Value]): + Additional search parameters. + + For public website search only, supported values are: + + - ``user_country_code``: string. Default empty. If set to + non-empty, results are restricted or boosted based on the + location provided. Example: user_country_code: "au" + + For available codes see `Country + Codes `__ + + - ``search_type``: double. Default empty. Enables + non-webpage searching depending on the value. The only + valid non-default value is 1, which enables image + searching. Example: search_type: 1 + query_expansion_spec (google.cloud.discoveryengine_v1alpha.types.SearchRequest.QueryExpansionSpec): + The query expansion specification that + specifies the conditions under which query + expansion occurs. + spell_correction_spec (google.cloud.discoveryengine_v1alpha.types.SearchRequest.SpellCorrectionSpec): + The spell correction specification that + specifies the mode under which spell correction + takes effect. + user_pseudo_id (str): + A unique identifier for tracking visitors. For example, this + could be implemented with an HTTP cookie, which should be + able to uniquely identify a visitor on a single device. This + unique identifier should not change if the visitor logs in + or out of the website. + + This field should NOT have a fixed value such as + ``unknown_visitor``. + + This should be the same identifier as + [UserEvent.user_pseudo_id][google.cloud.discoveryengine.v1alpha.UserEvent.user_pseudo_id] + and + [CompleteQueryRequest.user_pseudo_id][google.cloud.discoveryengine.v1alpha.CompleteQueryRequest.user_pseudo_id] + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an ``INVALID_ARGUMENT`` error + is returned. + content_search_spec (google.cloud.discoveryengine_v1alpha.types.SearchRequest.ContentSearchSpec): + A specification for configuring the behavior + of content search. + embedding_spec (google.cloud.discoveryengine_v1alpha.types.SearchRequest.EmbeddingSpec): + Uses the provided embedding to do additional semantic + document retrieval. The retrieval is based on the dot + product of + [SearchRequest.embedding_spec.embedding_vectors.vector][] + and the document embedding that is provided in + [SearchRequest.embedding_spec.embedding_vectors.field_path][]. + + If + [SearchRequest.embedding_spec.embedding_vectors.field_path][] + is not provided, it will use + [ServingConfig.embedding_config.field_paths][]. + ranking_expression (str): + The ranking expression controls the customized ranking on + retrieval documents. This overrides + [ServingConfig.ranking_expression][google.cloud.discoveryengine.v1alpha.ServingConfig.ranking_expression]. + The ranking expression is a single function or multiple + functions that are joint by "+". + + - ranking_expression = function, { " + ", function }; + Supported functions: + - double \* relevance_score + - double \* dotProduct(embedding_field_path) Function + variables: ``relevance_score``: pre-defined keywords, + used for measure relevance between query and document. + ``embedding_field_path``: the document embedding field + used with query embedding vector. ``dotProduct``: + embedding function between embedding_field_path and query + embedding vector. + + Example ranking expression: If document has an embedding + field doc_embedding, the ranking expression could be + ``0.5 * relevance_score + 0.3 * dotProduct(doc_embedding)``. + safe_search (bool): + Whether to turn on safe search. This is only + supported for website search. + user_labels (MutableMapping[str, str]): + The user labels applied to a resource must meet the + following requirements: + + - Each resource can have multiple labels, up to a maximum + of 64. + - Each label must be a key-value pair. + - Keys have a minimum length of 1 character and a maximum + length of 63 characters and cannot be empty. Values can + be empty and have a maximum length of 63 characters. + - Keys and values can contain only lowercase letters, + numeric characters, underscores, and dashes. All + characters must use UTF-8 encoding, and international + characters are allowed. + - The key portion of a label must be unique. However, you + can use the same key with multiple resources. + - Keys must start with a lowercase letter or international + character. + + See `Google Cloud + Document `__ + for more details. + """ + + class ImageQuery(proto.Message): + r"""Specifies the image query input. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + image_bytes (str): + Base64 encoded image bytes. Supported image + formats: JPEG, PNG, and BMP. + + This field is a member of `oneof`_ ``image``. + """ + + image_bytes: str = proto.Field( + proto.STRING, + number=1, + oneof='image', + ) + + class FacetSpec(proto.Message): + r"""A facet specification to perform faceted search. + + Attributes: + facet_key (google.cloud.discoveryengine_v1alpha.types.SearchRequest.FacetSpec.FacetKey): + Required. The facet key specification. + limit (int): + Maximum of facet values that should be returned for this + facet. If unspecified, defaults to 20. The maximum allowed + value is 300. Values above 300 are coerced to 300. + + If this field is negative, an ``INVALID_ARGUMENT`` is + returned. + excluded_filter_keys (MutableSequence[str]): + List of keys to exclude when faceting. + + By default, + [FacetKey.key][google.cloud.discoveryengine.v1alpha.SearchRequest.FacetSpec.FacetKey.key] + is not excluded from the filter unless it is listed in this + field. + + Listing a facet key in this field allows its values to + appear as facet results, even when they are filtered out of + search results. Using this field does not affect what search + results are returned. + + For example, suppose there are 100 documents with the color + facet "Red" and 200 documents with the color facet "Blue". A + query containing the filter "color:ANY("Red")" and having + "color" as + [FacetKey.key][google.cloud.discoveryengine.v1alpha.SearchRequest.FacetSpec.FacetKey.key] + would by default return only "Red" documents in the search + results, and also return "Red" with count 100 as the only + color facet. Although there are also blue documents + available, "Blue" would not be shown as an available facet + value. + + If "color" is listed in "excludedFilterKeys", then the query + returns the facet values "Red" with count 100 and "Blue" + with count 200, because the "color" key is now excluded from + the filter. Because this field doesn't affect search + results, the search results are still correctly filtered to + return only "Red" documents. + + A maximum of 100 values are allowed. Otherwise, an + ``INVALID_ARGUMENT`` error is returned. + enable_dynamic_position (bool): + Enables dynamic position for this facet. If set to true, the + position of this facet among all facets in the response is + determined automatically. If dynamic facets are enabled, it + is ordered together. If set to false, the position of this + facet in the response is the same as in the request, and it + is ranked before the facets with dynamic position enable and + all dynamic facets. + + For example, you may always want to have rating facet + returned in the response, but it's not necessarily to always + display the rating facet at the top. In that case, you can + set enable_dynamic_position to true so that the position of + rating facet in response is determined automatically. + + Another example, assuming you have the following facets in + the request: + + - "rating", enable_dynamic_position = true + + - "price", enable_dynamic_position = false + + - "brands", enable_dynamic_position = false + + And also you have a dynamic facets enabled, which generates + a facet ``gender``. Then the final order of the facets in + the response can be ("price", "brands", "rating", "gender") + or ("price", "brands", "gender", "rating") depends on how + API orders "gender" and "rating" facets. However, notice + that "price" and "brands" are always ranked at first and + second position because their enable_dynamic_position is + false. + """ + + class FacetKey(proto.Message): + r"""Specifies how a facet is computed. + + Attributes: + key (str): + Required. Supported textual and numerical facet keys in + [Document][google.cloud.discoveryengine.v1alpha.Document] + object, over which the facet values are computed. Facet key + is case-sensitive. + intervals (MutableSequence[google.cloud.discoveryengine_v1alpha.types.Interval]): + Set only if values should be bucketed into + intervals. Must be set for facets with numerical + values. Must not be set for facet with text + values. Maximum number of intervals is 30. + restricted_values (MutableSequence[str]): + Only get facet for the given restricted values. Only + supported on textual fields. For example, suppose "category" + has three values "Action > 2022", "Action > 2021" and + "Sci-Fi > 2022". If set "restricted_values" to "Action > + 2022", the "category" facet only contains "Action > 2022". + Only supported on textual fields. Maximum is 10. + prefixes (MutableSequence[str]): + Only get facet values that start with the + given string prefix. For example, suppose + "category" has three values "Action > 2022", + "Action > 2021" and "Sci-Fi > 2022". If set + "prefixes" to "Action", the "category" facet + only contains "Action > 2022" and "Action > + 2021". Only supported on textual fields. Maximum + is 10. + contains (MutableSequence[str]): + Only get facet values that contains the given + strings. For example, suppose "category" has + three values "Action > 2022", "Action > 2021" + and "Sci-Fi > 2022". If set "contains" to + "2022", the "category" facet only contains + "Action > 2022" and "Sci-Fi > 2022". Only + supported on textual fields. Maximum is 10. + case_insensitive (bool): + True to make facet keys case insensitive when + getting faceting values with prefixes or + contains; false otherwise. + order_by (str): + The order in which documents are returned. + + Allowed values are: + + - "count desc", which means order by + [SearchResponse.Facet.values.count][google.cloud.discoveryengine.v1alpha.SearchResponse.Facet.FacetValue.count] + descending. + + - "value desc", which means order by + [SearchResponse.Facet.values.value][google.cloud.discoveryengine.v1alpha.SearchResponse.Facet.FacetValue.value] + descending. Only applies to textual facets. + + If not set, textual values are sorted in `natural + order `__; + numerical intervals are sorted in the order given by + [FacetSpec.FacetKey.intervals][google.cloud.discoveryengine.v1alpha.SearchRequest.FacetSpec.FacetKey.intervals]. + """ + + key: str = proto.Field( + proto.STRING, + number=1, + ) + intervals: MutableSequence[common.Interval] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=common.Interval, + ) + restricted_values: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + prefixes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + contains: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + case_insensitive: bool = proto.Field( + proto.BOOL, + number=6, + ) + order_by: str = proto.Field( + proto.STRING, + number=7, + ) + + facet_key: 'SearchRequest.FacetSpec.FacetKey' = proto.Field( + proto.MESSAGE, + number=1, + message='SearchRequest.FacetSpec.FacetKey', + ) + limit: int = proto.Field( + proto.INT32, + number=2, + ) + excluded_filter_keys: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + enable_dynamic_position: bool = proto.Field( + proto.BOOL, + number=4, + ) + + class BoostSpec(proto.Message): + r"""Boost specification to boost certain documents. + + Attributes: + condition_boost_specs (MutableSequence[google.cloud.discoveryengine_v1alpha.types.SearchRequest.BoostSpec.ConditionBoostSpec]): + Condition boost specifications. If a document + matches multiple conditions in the + specifictions, boost scores from these + specifications are all applied and combined in a + non-linear way. Maximum number of specifications + is 20. + """ + + class ConditionBoostSpec(proto.Message): + r"""Boost applies to documents which match a condition. + + Attributes: + condition (str): + An expression which specifies a boost condition. The syntax + and supported fields are the same as a filter expression. + See + [SearchRequest.filter][google.cloud.discoveryengine.v1alpha.SearchRequest.filter] + for detail syntax and limitations. + + Examples: + + - To boost documents with document ID "doc_1" or "doc_2", + and color "Red" or "Blue": + + - (id: ANY("doc_1", "doc_2")) AND (color: + ANY("Red","Blue")) + boost (float): + Strength of the condition boost, which should be in [-1, 1]. + Negative boost means demotion. Default is 0.0. + + Setting to 1.0 gives the document a big promotion. However, + it does not necessarily mean that the boosted document will + be the top result at all times, nor that other documents + will be excluded. Results could still be shown even when + none of them matches the condition. And results that are + significantly more relevant to the search query can still + trump your heavily favored but irrelevant documents. + + Setting to -1.0 gives the document a big demotion. However, + results that are deeply relevant might still be shown. The + document will have an upstream battle to get a fairly high + ranking, but it is not blocked out completely. + + Setting to 0.0 means no boost applied. The boosting + condition is ignored. + """ + + condition: str = proto.Field( + proto.STRING, + number=1, + ) + boost: float = proto.Field( + proto.FLOAT, + number=2, + ) + + condition_boost_specs: MutableSequence['SearchRequest.BoostSpec.ConditionBoostSpec'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SearchRequest.BoostSpec.ConditionBoostSpec', + ) + + class QueryExpansionSpec(proto.Message): + r"""Specification to determine under which conditions query + expansion should occur. + + Attributes: + condition (google.cloud.discoveryengine_v1alpha.types.SearchRequest.QueryExpansionSpec.Condition): + The condition under which query expansion should occur. + Default to + [Condition.DISABLED][google.cloud.discoveryengine.v1alpha.SearchRequest.QueryExpansionSpec.Condition.DISABLED]. + pin_unexpanded_results (bool): + Whether to pin unexpanded results. If this + field is set to true, unexpanded products are + always at the top of the search results, + followed by the expanded results. + """ + class Condition(proto.Enum): + r"""Enum describing under which condition query expansion should + occur. + + Values: + CONDITION_UNSPECIFIED (0): + Unspecified query expansion condition. In this case, server + behavior defaults to + [Condition.DISABLED][google.cloud.discoveryengine.v1alpha.SearchRequest.QueryExpansionSpec.Condition.DISABLED]. + DISABLED (1): + Disabled query expansion. Only the exact search query is + used, even if + [SearchResponse.total_size][google.cloud.discoveryengine.v1alpha.SearchResponse.total_size] + is zero. + AUTO (2): + Automatic query expansion built by the Search + API. + """ + CONDITION_UNSPECIFIED = 0 + DISABLED = 1 + AUTO = 2 + + condition: 'SearchRequest.QueryExpansionSpec.Condition' = proto.Field( + proto.ENUM, + number=1, + enum='SearchRequest.QueryExpansionSpec.Condition', + ) + pin_unexpanded_results: bool = proto.Field( + proto.BOOL, + number=2, + ) + + class SpellCorrectionSpec(proto.Message): + r"""The specification for query spell correction. + + Attributes: + mode (google.cloud.discoveryengine_v1alpha.types.SearchRequest.SpellCorrectionSpec.Mode): + The mode under which spell correction should take effect to + replace the original search query. Default to + [Mode.AUTO][google.cloud.discoveryengine.v1alpha.SearchRequest.SpellCorrectionSpec.Mode.AUTO]. + """ + class Mode(proto.Enum): + r"""Enum describing under which mode spell correction should + occur. + + Values: + MODE_UNSPECIFIED (0): + Unspecified spell correction mode. In this case, server + behavior defaults to + [Mode.AUTO][google.cloud.discoveryengine.v1alpha.SearchRequest.SpellCorrectionSpec.Mode.AUTO]. + SUGGESTION_ONLY (1): + Search API will try to find a spell suggestion if there is + any and put in the + [SearchResponse.corrected_query][google.cloud.discoveryengine.v1alpha.SearchResponse.corrected_query]. + The spell suggestion will not be used as the search query. + AUTO (2): + Automatic spell correction built by the + Search API. Search will be based on the + corrected query if found. + """ + MODE_UNSPECIFIED = 0 + SUGGESTION_ONLY = 1 + AUTO = 2 + + mode: 'SearchRequest.SpellCorrectionSpec.Mode' = proto.Field( + proto.ENUM, + number=1, + enum='SearchRequest.SpellCorrectionSpec.Mode', + ) + + class ContentSearchSpec(proto.Message): + r"""A specification for configuring the behavior of content + search. + + Attributes: + snippet_spec (google.cloud.discoveryengine_v1alpha.types.SearchRequest.ContentSearchSpec.SnippetSpec): + If ``snippetSpec`` is not specified, snippets are not + included in the search response. + summary_spec (google.cloud.discoveryengine_v1alpha.types.SearchRequest.ContentSearchSpec.SummarySpec): + If ``summarySpec`` is not specified, summaries are not + included in the search response. + extractive_content_spec (google.cloud.discoveryengine_v1alpha.types.SearchRequest.ContentSearchSpec.ExtractiveContentSpec): + If there is no extractive_content_spec provided, there will + be no extractive answer in the search response. + """ + + class SnippetSpec(proto.Message): + r"""A specification for configuring snippets in a search + response. + + Attributes: + max_snippet_count (int): + [DEPRECATED] This field is deprecated. To control snippet + return, use ``return_snippet`` field. For backwards + compatibility, we will return snippet if max_snippet_count > + 0. + reference_only (bool): + [DEPRECATED] This field is deprecated and will have no + affect on the snippet. + return_snippet (bool): + If ``true``, then return snippet. If no snippet can be + generated, we return "No snippet is available for this + page." A ``snippet_status`` with ``SUCCESS`` or + ``NO_SNIPPET_AVAILABLE`` will also be returned. + """ + + max_snippet_count: int = proto.Field( + proto.INT32, + number=1, + ) + reference_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + return_snippet: bool = proto.Field( + proto.BOOL, + number=3, + ) + + class SummarySpec(proto.Message): + r"""A specification for configuring a summary returned in a + search response. + + Attributes: + summary_result_count (int): + The number of top results to generate the summary from. If + the number of results returned is less than + ``summaryResultCount``, the summary is generated from all of + the results. + + At most five results can be used to generate a summary. + include_citations (bool): + Specifies whether to include citations in the summary. The + default value is ``false``. + + When this field is set to ``true``, summaries include + in-line citation numbers. + + Example summary including citations: + + BigQuery is Google Cloud's fully managed and completely + serverless enterprise data warehouse [1]. BigQuery supports + all data types, works across clouds, and has built-in + machine learning and business intelligence, all within a + unified platform [2, 3]. + + The citation numbers refer to the returned search results + and are 1-indexed. For example, [1] means that the sentence + is attributed to the first search result. [2, 3] means that + the sentence is attributed to both the second and third + search results. + ignore_adversarial_query (bool): + Specifies whether to filter out adversarial queries. The + default value is ``false``. + + Google employs search-query classification to detect + adversarial queries. No summary is returned if the search + query is classified as an adversarial query. For example, a + user might ask a question regarding negative comments about + the company or submit a query designed to generate unsafe, + policy-violating output. If this field is set to ``true``, + we skip generating summaries for adversarial queries and + return fallback messages instead. + ignore_non_summary_seeking_query (bool): + Specifies whether to filter out queries that are not + summary-seeking. The default value is ``false``. + + Google employs search-query classification to detect + summary-seeking queries. No summary is returned if the + search query is classified as a non-summary seeking query. + For example, ``why is the sky blue`` and + ``Who is the best soccer player in the world?`` are + summary-seeking queries, but ``SFO airport`` and + ``world cup 2026`` are not. They are most likely + navigational queries. If this field is set to ``true``, we + skip generating summaries for non-summary seeking queries + and return fallback messages instead. + language_code (str): + Language code for Summary. Use language tags defined by + `BCP47 `__. + Note: This is an experimental feature. + """ + + summary_result_count: int = proto.Field( + proto.INT32, + number=1, + ) + include_citations: bool = proto.Field( + proto.BOOL, + number=2, + ) + ignore_adversarial_query: bool = proto.Field( + proto.BOOL, + number=3, + ) + ignore_non_summary_seeking_query: bool = proto.Field( + proto.BOOL, + number=4, + ) + language_code: str = proto.Field( + proto.STRING, + number=6, + ) + + class ExtractiveContentSpec(proto.Message): + r"""A specification for configuring the extractive content in a + search response. + + Attributes: + max_extractive_answer_count (int): + The maximum number of extractive answers returned in each + search result. + + An extractive answer is a verbatim answer extracted from the + original document, which provides a precise and contextually + relevant answer to the search query. + + If the number of matching answers is less than the + ``max_extractive_answer_count``, return all of the answers. + Otherwise, return the ``max_extractive_answer_count``. + + At most one answer is returned for each + [SearchResult][google.cloud.discoveryengine.v1alpha.SearchResponse.SearchResult]. + max_extractive_segment_count (int): + The max number of extractive segments returned in each + search result. Only applied if the + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore] + is set to + [DataStore.ContentConfig.CONTENT_REQUIRED][google.cloud.discoveryengine.v1alpha.DataStore.ContentConfig.CONTENT_REQUIRED] + or + [DataStore.solution_types][google.cloud.discoveryengine.v1alpha.DataStore.solution_types] + is + [SOLUTION_TYPE_CHAT][google.cloud.discoveryengine.v1alpha.SolutionType.SOLUTION_TYPE_CHAT]. + + An extractive segment is a text segment extracted from the + original document that is relevant to the search query, and, + in general, more verbose than an extractive answer. The + segment could then be used as input for LLMs to generate + summaries and answers. + + If the number of matching segments is less than + ``max_extractive_segment_count``, return all of the + segments. Otherwise, return the + ``max_extractive_segment_count``. + return_extractive_segment_score (bool): + Specifies whether to return the confidence score from the + extractive segments in each search result. The default value + is ``false``. + + Note: this is a priavte preview feature and only works for + allowlisted users, please reach out to Cloud Support team if + you want to use it. + num_previous_segments (int): + Specifies whether to also include the adjacent from each + selected segments. Return at most ``num_previous_segments`` + segments before each selected segments. + num_next_segments (int): + Return at most ``num_next_segments`` segments after each + selected segments. + """ + + max_extractive_answer_count: int = proto.Field( + proto.INT32, + number=1, + ) + max_extractive_segment_count: int = proto.Field( + proto.INT32, + number=2, + ) + return_extractive_segment_score: bool = proto.Field( + proto.BOOL, + number=3, + ) + num_previous_segments: int = proto.Field( + proto.INT32, + number=4, + ) + num_next_segments: int = proto.Field( + proto.INT32, + number=5, + ) + + snippet_spec: 'SearchRequest.ContentSearchSpec.SnippetSpec' = proto.Field( + proto.MESSAGE, + number=1, + message='SearchRequest.ContentSearchSpec.SnippetSpec', + ) + summary_spec: 'SearchRequest.ContentSearchSpec.SummarySpec' = proto.Field( + proto.MESSAGE, + number=2, + message='SearchRequest.ContentSearchSpec.SummarySpec', + ) + extractive_content_spec: 'SearchRequest.ContentSearchSpec.ExtractiveContentSpec' = proto.Field( + proto.MESSAGE, + number=3, + message='SearchRequest.ContentSearchSpec.ExtractiveContentSpec', + ) + + class EmbeddingSpec(proto.Message): + r"""The specification that uses customized query embedding vector + to do semantic document retrieval. + + Attributes: + embedding_vectors (MutableSequence[google.cloud.discoveryengine_v1alpha.types.SearchRequest.EmbeddingSpec.EmbeddingVector]): + The embedding vector used for retrieval. + Limit to 1. + """ + + class EmbeddingVector(proto.Message): + r"""Embedding vector. + + Attributes: + field_path (str): + Embedding field path in schema. + vector (MutableSequence[float]): + Query embedding vector. + """ + + field_path: str = proto.Field( + proto.STRING, + number=1, + ) + vector: MutableSequence[float] = proto.RepeatedField( + proto.FLOAT, + number=2, + ) + + embedding_vectors: MutableSequence['SearchRequest.EmbeddingSpec.EmbeddingVector'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SearchRequest.EmbeddingSpec.EmbeddingVector', + ) + + serving_config: str = proto.Field( + proto.STRING, + number=1, + ) + branch: str = proto.Field( + proto.STRING, + number=2, + ) + query: str = proto.Field( + proto.STRING, + number=3, + ) + image_query: ImageQuery = proto.Field( + proto.MESSAGE, + number=19, + message=ImageQuery, + ) + page_size: int = proto.Field( + proto.INT32, + number=4, + ) + page_token: str = proto.Field( + proto.STRING, + number=5, + ) + offset: int = proto.Field( + proto.INT32, + number=6, + ) + filter: str = proto.Field( + proto.STRING, + number=7, + ) + order_by: str = proto.Field( + proto.STRING, + number=8, + ) + user_info: common.UserInfo = proto.Field( + proto.MESSAGE, + number=21, + message=common.UserInfo, + ) + facet_specs: MutableSequence[FacetSpec] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message=FacetSpec, + ) + boost_spec: BoostSpec = proto.Field( + proto.MESSAGE, + number=10, + message=BoostSpec, + ) + params: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=11, + message=struct_pb2.Value, + ) + query_expansion_spec: QueryExpansionSpec = proto.Field( + proto.MESSAGE, + number=13, + message=QueryExpansionSpec, + ) + spell_correction_spec: SpellCorrectionSpec = proto.Field( + proto.MESSAGE, + number=14, + message=SpellCorrectionSpec, + ) + user_pseudo_id: str = proto.Field( + proto.STRING, + number=15, + ) + content_search_spec: ContentSearchSpec = proto.Field( + proto.MESSAGE, + number=24, + message=ContentSearchSpec, + ) + embedding_spec: EmbeddingSpec = proto.Field( + proto.MESSAGE, + number=23, + message=EmbeddingSpec, + ) + ranking_expression: str = proto.Field( + proto.STRING, + number=26, + ) + safe_search: bool = proto.Field( + proto.BOOL, + number=20, + ) + user_labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=22, + ) + + +class SearchResponse(proto.Message): + r"""Response message for + [SearchService.Search][google.cloud.discoveryengine.v1alpha.SearchService.Search] + method. + + Attributes: + results (MutableSequence[google.cloud.discoveryengine_v1alpha.types.SearchResponse.SearchResult]): + A list of matched documents. The order + represents the ranking. + facets (MutableSequence[google.cloud.discoveryengine_v1alpha.types.SearchResponse.Facet]): + Results of facets requested by user. + guided_search_result (google.cloud.discoveryengine_v1alpha.types.SearchResponse.GuidedSearchResult): + Guided search result. + total_size (int): + The estimated total count of matched items irrespective of + pagination. The count of + [results][google.cloud.discoveryengine.v1alpha.SearchResponse.results] + returned by pagination may be less than the + [total_size][google.cloud.discoveryengine.v1alpha.SearchResponse.total_size] + that matches. + attribution_token (str): + A unique search token. This should be included in the + [UserEvent][google.cloud.discoveryengine.v1alpha.UserEvent] + logs resulting from this search, which enables accurate + attribution of search model performance. + redirect_uri (str): + The URI of a customer-defined redirect page. If redirect + action is triggered, no search is performed, and only + [redirect_uri][google.cloud.discoveryengine.v1alpha.SearchResponse.redirect_uri] + and + [attribution_token][google.cloud.discoveryengine.v1alpha.SearchResponse.attribution_token] + are set in the response. + next_page_token (str): + A token that can be sent as + [SearchRequest.page_token][google.cloud.discoveryengine.v1alpha.SearchRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + corrected_query (str): + Contains the spell corrected query, if found. If the spell + correction type is AUTOMATIC, then the search results are + based on corrected_query. Otherwise the original query is + used for search. + summary (google.cloud.discoveryengine_v1alpha.types.SearchResponse.Summary): + A summary as part of the search results. This field is only + returned if + [SearchRequest.ContentSearchSpec.summary_spec][google.cloud.discoveryengine.v1alpha.SearchRequest.ContentSearchSpec.summary_spec] + is set. + applied_controls (MutableSequence[str]): + Controls applied as part of the Control + service. + geo_search_debug_info (MutableSequence[google.cloud.discoveryengine_v1alpha.types.SearchResponse.GeoSearchDebugInfo]): + + query_expansion_info (google.cloud.discoveryengine_v1alpha.types.SearchResponse.QueryExpansionInfo): + Query expansion information for the returned + results. + """ + + class SearchResult(proto.Message): + r"""Represents the search results. + + Attributes: + id (str): + [Document.id][google.cloud.discoveryengine.v1alpha.Document.id] + of the searched + [Document][google.cloud.discoveryengine.v1alpha.Document]. + document (google.cloud.discoveryengine_v1alpha.types.Document): + The document data snippet in the search + response. Only fields that are marked as + retrievable are populated. + model_scores (MutableMapping[str, google.cloud.discoveryengine_v1alpha.types.DoubleList]): + Google provided available scores. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + document: gcd_document.Document = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_document.Document, + ) + model_scores: MutableMapping[str, common.DoubleList] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=4, + message=common.DoubleList, + ) + + class Facet(proto.Message): + r"""A facet result. + + Attributes: + key (str): + The key for this facet. E.g., "colors" or "price". It + matches + [SearchRequest.FacetSpec.FacetKey.key][google.cloud.discoveryengine.v1alpha.SearchRequest.FacetSpec.FacetKey.key]. + values (MutableSequence[google.cloud.discoveryengine_v1alpha.types.SearchResponse.Facet.FacetValue]): + The facet values for this field. + dynamic_facet (bool): + Whether the facet is dynamically generated. + """ + + class FacetValue(proto.Message): + r"""A facet value which contains value names and their count. + + 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: + value (str): + Text value of a facet, such as "Black" for + facet "colors". + + This field is a member of `oneof`_ ``facet_value``. + interval (google.cloud.discoveryengine_v1alpha.types.Interval): + Interval value for a facet, such as [10, 20) for facet + "price". It matches + [SearchRequest.FacetSpec.FacetKey.intervals][google.cloud.discoveryengine.v1alpha.SearchRequest.FacetSpec.FacetKey.intervals]. + + This field is a member of `oneof`_ ``facet_value``. + count (int): + Number of items that have this facet value. + """ + + value: str = proto.Field( + proto.STRING, + number=1, + oneof='facet_value', + ) + interval: common.Interval = proto.Field( + proto.MESSAGE, + number=2, + oneof='facet_value', + message=common.Interval, + ) + count: int = proto.Field( + proto.INT64, + number=3, + ) + + key: str = proto.Field( + proto.STRING, + number=1, + ) + values: MutableSequence['SearchResponse.Facet.FacetValue'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='SearchResponse.Facet.FacetValue', + ) + dynamic_facet: bool = proto.Field( + proto.BOOL, + number=3, + ) + + class GuidedSearchResult(proto.Message): + r"""Guided search result. The guided search helps user to refine + the search results and narrow down to the real needs from a + broaded search results. + + Attributes: + refinement_attributes (MutableSequence[google.cloud.discoveryengine_v1alpha.types.SearchResponse.GuidedSearchResult.RefinementAttribute]): + A list of ranked refinement attributes. + follow_up_questions (MutableSequence[str]): + Suggested follow-up questions. + """ + + class RefinementAttribute(proto.Message): + r"""Useful attribute for search result refinements. + + Attributes: + attribute_key (str): + Attribute key used to refine the results e.g. 'movie_type'. + attribute_value (str): + Attribute value used to refine the results + e.g. 'drama'. + """ + + attribute_key: str = proto.Field( + proto.STRING, + number=1, + ) + attribute_value: str = proto.Field( + proto.STRING, + number=2, + ) + + refinement_attributes: MutableSequence['SearchResponse.GuidedSearchResult.RefinementAttribute'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SearchResponse.GuidedSearchResult.RefinementAttribute', + ) + follow_up_questions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + class Summary(proto.Message): + r"""Summary of the top N search result specified by the summary + spec. + + Attributes: + summary_text (str): + The summary content. + summary_skipped_reasons (MutableSequence[google.cloud.discoveryengine_v1alpha.types.SearchResponse.Summary.SummarySkippedReason]): + Additional summary-skipped reasons. This + provides the reason for ignored cases. If + nothing is skipped, this field is not set. + safety_attributes (google.cloud.discoveryengine_v1alpha.types.SearchResponse.Summary.SafetyAttributes): + A collection of Safety Attribute categories + and their associated confidence scores. + """ + class SummarySkippedReason(proto.Enum): + r"""An Enum for summary-skipped reasons. + + Values: + SUMMARY_SKIPPED_REASON_UNSPECIFIED (0): + Default value. The summary skipped reason is + not specified. + ADVERSARIAL_QUERY_IGNORED (1): + The adversarial query ignored case. + + Only populated when + [SummarySpec.ignore_adversarial_query][google.cloud.discoveryengine.v1alpha.SearchRequest.ContentSearchSpec.SummarySpec.ignore_adversarial_query] + is set to ``true``. + NON_SUMMARY_SEEKING_QUERY_IGNORED (2): + The non-summary seeking query ignored case. + + Only populated when + [SummarySpec.ignore_non_summary_seeking_query][google.cloud.discoveryengine.v1alpha.SearchRequest.ContentSearchSpec.SummarySpec.ignore_non_summary_seeking_query] + is set to ``true``. + OUT_OF_DOMAIN_QUERY_IGNORED (3): + The out-of-domain query ignored case. + + Google skips the summary if there are no + high-relevance search results. For example, the + data store contains facts about company A but + the user query is asking questions about company + B. + POTENTIAL_POLICY_VIOLATION (4): + The potential policy violation case. + + Google skips the summary if there is a potential + policy violation detected. This includes content + that may be violent or toxic. + LLM_ADDON_NOT_ENABLED (5): + The LLM addon not enabled case. + + Google skips the summary if the LLM addon is not + enabled. + """ + SUMMARY_SKIPPED_REASON_UNSPECIFIED = 0 + ADVERSARIAL_QUERY_IGNORED = 1 + NON_SUMMARY_SEEKING_QUERY_IGNORED = 2 + OUT_OF_DOMAIN_QUERY_IGNORED = 3 + POTENTIAL_POLICY_VIOLATION = 4 + LLM_ADDON_NOT_ENABLED = 5 + + class SafetyAttributes(proto.Message): + r"""Safety Attribute categories and their associated confidence + scores. + + Attributes: + categories (MutableSequence[str]): + The display names of Safety Attribute + categories associated with the generated + content. Order matches the Scores. + scores (MutableSequence[float]): + The confidence scores of the each category, + higher value means higher confidence. Order + matches the Categories. + """ + + categories: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + scores: MutableSequence[float] = proto.RepeatedField( + proto.FLOAT, + number=2, + ) + + summary_text: str = proto.Field( + proto.STRING, + number=1, + ) + summary_skipped_reasons: MutableSequence['SearchResponse.Summary.SummarySkippedReason'] = proto.RepeatedField( + proto.ENUM, + number=2, + enum='SearchResponse.Summary.SummarySkippedReason', + ) + safety_attributes: 'SearchResponse.Summary.SafetyAttributes' = proto.Field( + proto.MESSAGE, + number=3, + message='SearchResponse.Summary.SafetyAttributes', + ) + + class GeoSearchDebugInfo(proto.Message): + r"""Debug information specifically related to forward geocoding + issues arising from Geolocation Search. + + Attributes: + original_address_query (str): + The address from which forward geocoding + ingestion produced issues. + error_message (str): + The error produced. + """ + + original_address_query: str = proto.Field( + proto.STRING, + number=1, + ) + error_message: str = proto.Field( + proto.STRING, + number=2, + ) + + class QueryExpansionInfo(proto.Message): + r"""Information describing query expansion including whether + expansion has occurred. + + Attributes: + expanded_query (bool): + Bool describing whether query expansion has + occurred. + pinned_result_count (int): + Number of pinned results. This field will only be set when + expansion happens and + [SearchRequest.QueryExpansionSpec.pin_unexpanded_results][google.cloud.discoveryengine.v1alpha.SearchRequest.QueryExpansionSpec.pin_unexpanded_results] + is set to true. + """ + + expanded_query: bool = proto.Field( + proto.BOOL, + number=1, + ) + pinned_result_count: int = proto.Field( + proto.INT64, + number=2, + ) + + @property + def raw_page(self): + return self + + results: MutableSequence[SearchResult] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=SearchResult, + ) + facets: MutableSequence[Facet] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Facet, + ) + guided_search_result: GuidedSearchResult = proto.Field( + proto.MESSAGE, + number=8, + message=GuidedSearchResult, + ) + total_size: int = proto.Field( + proto.INT32, + number=3, + ) + attribution_token: str = proto.Field( + proto.STRING, + number=4, + ) + redirect_uri: str = proto.Field( + proto.STRING, + number=12, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=5, + ) + corrected_query: str = proto.Field( + proto.STRING, + number=7, + ) + summary: Summary = proto.Field( + proto.MESSAGE, + number=9, + message=Summary, + ) + applied_controls: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=10, + ) + geo_search_debug_info: MutableSequence[GeoSearchDebugInfo] = proto.RepeatedField( + proto.MESSAGE, + number=16, + message=GeoSearchDebugInfo, + ) + query_expansion_info: QueryExpansionInfo = proto.Field( + proto.MESSAGE, + number=14, + message=QueryExpansionInfo, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/site_search_engine_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/site_search_engine_service.py new file mode 100644 index 000000000000..55d34ab5fbbd --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/site_search_engine_service.py @@ -0,0 +1,211 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1alpha', + manifest={ + 'RecrawlUrisRequest', + 'RecrawlUrisResponse', + 'RecrawlUrisMetadata', + }, +) + + +class RecrawlUrisRequest(proto.Message): + r"""Request message for + [SiteSearchEngineService.RecrawlUris][google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.RecrawlUris] + method. + + Attributes: + site_search_engine (str): + Required. Full resource name of the + [SiteSearchEngine][google.cloud.discoveryengine.v1alpha.SiteSearchEngine], + such as + ``projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine``. + uris (MutableSequence[str]): + Required. List of URIs to crawl. At most 10K URIs are + supported, otherwise an INVALID_ARGUMENT error is thrown. + Each URI should match at least one + [TargetSite][google.cloud.discoveryengine.v1alpha.TargetSite] + in ``site_search_engine``. + """ + + site_search_engine: str = proto.Field( + proto.STRING, + number=1, + ) + uris: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class RecrawlUrisResponse(proto.Message): + r"""Response message for + [SiteSearchEngineService.RecrawlUris][google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.RecrawlUris] + method. + + Attributes: + failure_samples (MutableSequence[google.cloud.discoveryengine_v1alpha.types.RecrawlUrisResponse.FailureInfo]): + Details for a sample of up to 10 ``failed_uris``. + failed_uris (MutableSequence[str]): + URIs that were not crawled before the LRO + terminated. + """ + + class FailureInfo(proto.Message): + r"""Details about why a particular URI failed to be crawled. Each + FailureInfo contains one FailureReason per CorpusType. + + Attributes: + uri (str): + URI that failed to be crawled. + failure_reasons (MutableSequence[google.cloud.discoveryengine_v1alpha.types.RecrawlUrisResponse.FailureInfo.FailureReason]): + List of failure reasons by corpus type (e.g. + desktop, mobile). + """ + + class FailureReason(proto.Message): + r"""Details about why crawling failed for a particular + CorpusType, e.g. DESKTOP and MOBILE crawling may fail for + different reasons. + + Attributes: + corpus_type (google.cloud.discoveryengine_v1alpha.types.RecrawlUrisResponse.FailureInfo.FailureReason.CorpusType): + DESKTOP, MOBILE, or CORPUS_TYPE_UNSPECIFIED. + error_message (str): + Reason why the URI was not crawled. + """ + class CorpusType(proto.Enum): + r"""CorpusType for the failed crawling operation. + + Values: + CORPUS_TYPE_UNSPECIFIED (0): + Default value. + DESKTOP (1): + Denotes a crawling attempt for the desktop + version of a page. + MOBILE (2): + Denotes a crawling attempt for the mobile + version of a page. + """ + CORPUS_TYPE_UNSPECIFIED = 0 + DESKTOP = 1 + MOBILE = 2 + + corpus_type: 'RecrawlUrisResponse.FailureInfo.FailureReason.CorpusType' = proto.Field( + proto.ENUM, + number=1, + enum='RecrawlUrisResponse.FailureInfo.FailureReason.CorpusType', + ) + error_message: str = proto.Field( + proto.STRING, + number=2, + ) + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + failure_reasons: MutableSequence['RecrawlUrisResponse.FailureInfo.FailureReason'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='RecrawlUrisResponse.FailureInfo.FailureReason', + ) + + failure_samples: MutableSequence[FailureInfo] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=FailureInfo, + ) + failed_uris: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class RecrawlUrisMetadata(proto.Message): + r"""Metadata related to the progress of the + [SiteSearchEngineService.RecrawlUris][google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.RecrawlUris] + operation. This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + invalid_uris (MutableSequence[str]): + Unique URIs in the request that don't match + any TargetSite in the DataStore, only match + TargetSites that haven't been fully indexed, or + match a TargetSite with type EXCLUDE. + valid_uris_count (int): + Total number of unique URIs in the request that are not in + invalid_uris. + success_count (int): + Total number of URIs that have been crawled + so far. + pending_count (int): + Total number of URIs that have yet to be + crawled. + quota_exceeded_count (int): + Total number of URIs that were rejected due + to insufficient indexing resources. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + invalid_uris: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + valid_uris_count: int = proto.Field( + proto.INT32, + number=4, + ) + success_count: int = proto.Field( + proto.INT32, + number=5, + ) + pending_count: int = proto.Field( + proto.INT32, + number=6, + ) + quota_exceeded_count: int = proto.Field( + proto.INT32, + number=7, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/user_event.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/user_event.py new file mode 100644 index 000000000000..a0276c22fc7e --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/user_event.py @@ -0,0 +1,761 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import common +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1alpha', + manifest={ + 'UserEvent', + 'PageInfo', + 'SearchInfo', + 'CompletionInfo', + 'TransactionInfo', + 'DocumentInfo', + 'PanelInfo', + 'MediaInfo', + }, +) + + +class UserEvent(proto.Message): + r"""UserEvent captures all metadata information Discovery Engine + API needs to know about how end users interact with customers' + website. + + Attributes: + event_type (str): + Required. User event type. Allowed values are: + + Generic values: + + - ``search``: Search for Documents. + - ``view-item``: Detailed page view of a Document. + - ``view-item-list``: View of a panel or ordered list of + Documents. + - ``view-home-page``: View of the home page. + - ``view-category-page``: View of a category page, e.g. + Home > Men > Jeans + + Retail-related values: + + - ``add-to-cart``: Add an item(s) to cart, e.g. in Retail + online shopping + - ``purchase``: Purchase an item(s) + + Media-related values: + + - ``media-play``: Start/resume watching a video, playing a + song, etc. + - ``media-complete``: Finished or stopped midway through a + video, song, etc. + user_pseudo_id (str): + Required. A unique identifier for tracking visitors. + + For example, this could be implemented with an HTTP cookie, + which should be able to uniquely identify a visitor on a + single device. This unique identifier should not change if + the visitor log in/out of the website. + + Do not set the field to the same fixed ID for different + users. This mixes the event history of those users together, + which results in degraded model quality. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an ``INVALID_ARGUMENT`` error + is returned. + + The field should not contain PII or user-data. We recommend + to use Google Analytics `Client + ID `__ + for this field. + event_time (google.protobuf.timestamp_pb2.Timestamp): + Only required for + [UserEventService.ImportUserEvents][google.cloud.discoveryengine.v1alpha.UserEventService.ImportUserEvents] + method. Timestamp of when the user event happened. + user_info (google.cloud.discoveryengine_v1alpha.types.UserInfo): + Information about the end user. + direct_user_request (bool): + Should set to true if the request is made directly from the + end user, in which case the + [UserEvent.user_info.user_agent][google.cloud.discoveryengine.v1alpha.UserInfo.user_agent] + can be populated from the HTTP request. + + This flag should be set only if the API request is made + directly from the end user such as a mobile app (and not if + a gateway or a server is processing and pushing the user + events). + + This should not be set when using the JavaScript tag in + [UserEventService.CollectUserEvent][google.cloud.discoveryengine.v1alpha.UserEventService.CollectUserEvent]. + session_id (str): + A unique identifier for tracking a visitor session with a + length limit of 128 bytes. A session is an aggregation of an + end user behavior in a time span. + + A general guideline to populate the session_id: + + 1. If user has no activity for 30 min, a new session_id + should be assigned. + 2. The session_id should be unique across users, suggest use + uuid or add + [UserEvent.user_pseudo_id][google.cloud.discoveryengine.v1alpha.UserEvent.user_pseudo_id] + as prefix. + page_info (google.cloud.discoveryengine_v1alpha.types.PageInfo): + Page metadata such as categories and other critical + information for certain event types such as + ``view-category-page``. + attribution_token (str): + Token to attribute an API response to user action(s) to + trigger the event. + + Highly recommended for user events that are the result of + [RecommendationService.Recommend][google.cloud.discoveryengine.v1alpha.RecommendationService.Recommend]. + This field enables accurate attribution of recommendation + model performance. + + The value must be one of: + + - [RecommendResponse.attribution_token][google.cloud.discoveryengine.v1alpha.RecommendResponse.attribution_token] + for events that are the result of + [RecommendationService.Recommend][google.cloud.discoveryengine.v1alpha.RecommendationService.Recommend]. + - [SearchResponse.attribution_token][google.cloud.discoveryengine.v1alpha.SearchResponse.attribution_token] + for events that are the result of + [SearchService.Search][google.cloud.discoveryengine.v1alpha.SearchService.Search]. + + This token enables us to accurately attribute page view or + conversion completion back to the event and the particular + predict response containing this clicked/purchased product. + If user clicks on product K in the recommendation results, + pass + [RecommendResponse.attribution_token][google.cloud.discoveryengine.v1alpha.RecommendResponse.attribution_token] + as a URL parameter to product K's page. When recording + events on product K's page, log the + [RecommendResponse.attribution_token][google.cloud.discoveryengine.v1alpha.RecommendResponse.attribution_token] + to this field. + filter (str): + The filter syntax consists of an expression language for + constructing a predicate from one or more fields of the + documents being filtered. + + One example is for ``search`` events, the associated + [SearchRequest][google.cloud.discoveryengine.v1alpha.SearchRequest] + may contain a filter expression in + [SearchRequest.filter][google.cloud.discoveryengine.v1alpha.SearchRequest.filter] + conforming to https://google.aip.dev/160#filtering. + + Similarly, for ``view-item-list`` events that are generated + from a [RecommendationService.RecommendRequest][], this + field may be populated directly from + [RecommendationService.RecommendRequest.filter][] conforming + to https://google.aip.dev/160#filtering. + + The value must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an ``INVALID_ARGUMENT`` + error is returned. + documents (MutableSequence[google.cloud.discoveryengine_v1alpha.types.DocumentInfo]): + List of + [Document][google.cloud.discoveryengine.v1alpha.Document]s + associated with this user event. + + This field is optional except for the following event types: + + - ``view-item`` + - ``add-to-cart`` + - ``purchase`` + - ``media-play`` + - ``media-complete`` + + In a ``search`` event, this field represents the documents + returned to the end user on the current page (the end user + may have not finished browsing the whole page yet). When a + new page is returned to the end user, after + pagination/filtering/ordering even for the same query, a new + ``search`` event with different + [UserEvent.documents][google.cloud.discoveryengine.v1alpha.UserEvent.documents] + is desired. + panel (google.cloud.discoveryengine_v1alpha.types.PanelInfo): + Panel metadata associated with this user + event. + search_info (google.cloud.discoveryengine_v1alpha.types.SearchInfo): + [SearchService.Search][google.cloud.discoveryengine.v1alpha.SearchService.Search] + details related to the event. + + This field should be set for ``search`` event. + completion_info (google.cloud.discoveryengine_v1alpha.types.CompletionInfo): + [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1alpha.CompletionService.CompleteQuery] + details related to the event. + + This field should be set for ``search`` event when + autocomplete function is enabled and the user clicks a + suggestion for search. + transaction_info (google.cloud.discoveryengine_v1alpha.types.TransactionInfo): + The transaction metadata (if any) associated + with this user event. + tag_ids (MutableSequence[str]): + A list of identifiers for the independent + experiment groups this user event belongs to. + This is used to distinguish between user events + associated with different experiment setups on + the customer end. + promotion_ids (MutableSequence[str]): + The promotion IDs if this is an event + associated with promotions. Currently, this + field is restricted to at most one ID. + attributes (MutableMapping[str, google.cloud.discoveryengine_v1alpha.types.CustomAttribute]): + Extra user event features to include in the recommendation + model. These attributes must NOT contain data that needs to + be parsed or processed further, e.g. JSON or other + encodings. + + If you provide custom attributes for ingested user events, + also include them in the user events that you associate with + prediction requests. Custom attribute formatting must be + consistent between imported events and events provided with + prediction requests. This lets the Discovery Engine API use + those custom attributes when training models and serving + predictions, which helps improve recommendation quality. + + This field needs to pass all below criteria, otherwise an + ``INVALID_ARGUMENT`` error is returned: + + - The key must be a UTF-8 encoded string with a length + limit of 5,000 characters. + - For text attributes, at most 400 values are allowed. + Empty values are not allowed. Each value must be a UTF-8 + encoded string with a length limit of 256 characters. + - For number attributes, at most 400 values are allowed. + + For product recommendations, an example of extra user + information is ``traffic_channel``, which is how a user + arrives at the site. Users can arrive at the site by coming + to the site directly, coming through Google search, or in + other ways. + media_info (google.cloud.discoveryengine_v1alpha.types.MediaInfo): + Media-specific info. + """ + + event_type: str = proto.Field( + proto.STRING, + number=1, + ) + user_pseudo_id: str = proto.Field( + proto.STRING, + number=2, + ) + event_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + user_info: common.UserInfo = proto.Field( + proto.MESSAGE, + number=4, + message=common.UserInfo, + ) + direct_user_request: bool = proto.Field( + proto.BOOL, + number=5, + ) + session_id: str = proto.Field( + proto.STRING, + number=6, + ) + page_info: 'PageInfo' = proto.Field( + proto.MESSAGE, + number=7, + message='PageInfo', + ) + attribution_token: str = proto.Field( + proto.STRING, + number=8, + ) + filter: str = proto.Field( + proto.STRING, + number=9, + ) + documents: MutableSequence['DocumentInfo'] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message='DocumentInfo', + ) + panel: 'PanelInfo' = proto.Field( + proto.MESSAGE, + number=11, + message='PanelInfo', + ) + search_info: 'SearchInfo' = proto.Field( + proto.MESSAGE, + number=12, + message='SearchInfo', + ) + completion_info: 'CompletionInfo' = proto.Field( + proto.MESSAGE, + number=13, + message='CompletionInfo', + ) + transaction_info: 'TransactionInfo' = proto.Field( + proto.MESSAGE, + number=14, + message='TransactionInfo', + ) + tag_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=15, + ) + promotion_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=16, + ) + attributes: MutableMapping[str, common.CustomAttribute] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=17, + message=common.CustomAttribute, + ) + media_info: 'MediaInfo' = proto.Field( + proto.MESSAGE, + number=18, + message='MediaInfo', + ) + + +class PageInfo(proto.Message): + r"""Detailed page information. + + Attributes: + pageview_id (str): + A unique ID of a web page view. + + This should be kept the same for all user events triggered + from the same pageview. For example, an item detail page + view could trigger multiple events as the user is browsing + the page. The ``pageview_id`` property should be kept the + same for all these events so that they can be grouped + together properly. + + When using the client side event reporting with JavaScript + pixel and Google Tag Manager, this value is filled in + automatically. + page_category (str): + The most specific category associated with a category page. + + To represent full path of category, use '>' sign to separate + different hierarchies. If '>' is part of the category name, + please replace it with other character(s). + + Category pages include special pages such as sales or + promotions. For instance, a special sale page may have the + category hierarchy: + ``"pageCategory" : "Sales > 2017 Black Friday Deals"``. + + Required for ``view-category-page`` events. Other event + types should not set this field. Otherwise, an + ``INVALID_ARGUMENT`` error is returned. + uri (str): + Complete URL (window.location.href) of the + user's current page. + When using the client side event reporting with + JavaScript pixel and Google Tag Manager, this + value is filled in automatically. Maximum length + 5,000 characters. + referrer_uri (str): + The referrer URL of the current page. + + When using the client side event reporting with + JavaScript pixel and Google Tag Manager, this + value is filled in automatically. However, some + browser privacy restrictions may cause this + field to be empty. + """ + + pageview_id: str = proto.Field( + proto.STRING, + number=1, + ) + page_category: str = proto.Field( + proto.STRING, + number=2, + ) + uri: str = proto.Field( + proto.STRING, + number=3, + ) + referrer_uri: str = proto.Field( + proto.STRING, + number=4, + ) + + +class SearchInfo(proto.Message): + r"""Detailed search information. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + search_query (str): + The user's search query. + + See + [SearchRequest.query][google.cloud.discoveryengine.v1alpha.SearchRequest.query] + for definition. + + The value must be a UTF-8 encoded string with a length limit + of 5,000 characters. Otherwise, an ``INVALID_ARGUMENT`` + error is returned. + + At least one of + [search_query][google.cloud.discoveryengine.v1alpha.SearchInfo.search_query] + or + [PageInfo.page_category][google.cloud.discoveryengine.v1alpha.PageInfo.page_category] + is required for ``search`` events. Other event types should + not set this field. Otherwise, an ``INVALID_ARGUMENT`` error + is returned. + order_by (str): + The order in which products are returned, if applicable. + + See + [SearchRequest.order_by][google.cloud.discoveryengine.v1alpha.SearchRequest.order_by] + for definition and syntax. + + The value must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an ``INVALID_ARGUMENT`` + error is returned. + + This can only be set for ``search`` events. Other event + types should not set this field. Otherwise, an + ``INVALID_ARGUMENT`` error is returned. + offset (int): + An integer that specifies the current offset for pagination + (the 0-indexed starting location, amongst the products + deemed by the API as relevant). + + See + [SearchRequest.offset][google.cloud.discoveryengine.v1alpha.SearchRequest.offset] + for definition. + + If this field is negative, an ``INVALID_ARGUMENT`` is + returned. + + This can only be set for ``search`` events. Other event + types should not set this field. Otherwise, an + ``INVALID_ARGUMENT`` error is returned. + + This field is a member of `oneof`_ ``_offset``. + """ + + search_query: str = proto.Field( + proto.STRING, + number=1, + ) + order_by: str = proto.Field( + proto.STRING, + number=2, + ) + offset: int = proto.Field( + proto.INT32, + number=3, + optional=True, + ) + + +class CompletionInfo(proto.Message): + r"""Detailed completion information including completion + attribution token and clicked completion info. + + Attributes: + selected_suggestion (str): + End user selected + [CompleteQueryResponse.QuerySuggestion.suggestion][google.cloud.discoveryengine.v1alpha.CompleteQueryResponse.QuerySuggestion.suggestion]. + selected_position (int): + End user selected + [CompleteQueryResponse.QuerySuggestion.suggestion][google.cloud.discoveryengine.v1alpha.CompleteQueryResponse.QuerySuggestion.suggestion] + position, starting from 0. + """ + + selected_suggestion: str = proto.Field( + proto.STRING, + number=1, + ) + selected_position: int = proto.Field( + proto.INT32, + number=2, + ) + + +class TransactionInfo(proto.Message): + r"""A transaction represents the entire purchase transaction. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + value (float): + Required. Total non-zero value associated + with the transaction. This value may include + shipping, tax, or other adjustments to the total + value that you want to include. + + This field is a member of `oneof`_ ``_value``. + currency (str): + Required. Currency code. Use three-character + ISO-4217 code. + transaction_id (str): + The transaction ID with a length limit of 128 + characters. + tax (float): + All the taxes associated with the + transaction. + + This field is a member of `oneof`_ ``_tax``. + cost (float): + All the costs associated with the products. These can be + manufacturing costs, shipping expenses not borne by the end + user, or any other costs, such that: + + - Profit = + [value][google.cloud.discoveryengine.v1alpha.TransactionInfo.value] + - + [tax][google.cloud.discoveryengine.v1alpha.TransactionInfo.tax] + - + [cost][google.cloud.discoveryengine.v1alpha.TransactionInfo.cost] + + This field is a member of `oneof`_ ``_cost``. + discount_value (float): + The total discount(s) value applied to this transaction. + This figure should be excluded from + [TransactionInfo.value][google.cloud.discoveryengine.v1alpha.TransactionInfo.value] + + For example, if a user paid + [TransactionInfo.value][google.cloud.discoveryengine.v1alpha.TransactionInfo.value] + amount, then nominal (pre-discount) value of the transaction + is the sum of + [TransactionInfo.value][google.cloud.discoveryengine.v1alpha.TransactionInfo.value] + and + [TransactionInfo.discount_value][google.cloud.discoveryengine.v1alpha.TransactionInfo.discount_value] + + This means that profit is calculated the same way, + regardless of the discount value, and that + [TransactionInfo.discount_value][google.cloud.discoveryengine.v1alpha.TransactionInfo.discount_value] + can be larger than + [TransactionInfo.value][google.cloud.discoveryengine.v1alpha.TransactionInfo.value]: + + - Profit = + [value][google.cloud.discoveryengine.v1alpha.TransactionInfo.value] + - + [tax][google.cloud.discoveryengine.v1alpha.TransactionInfo.tax] + - + [cost][google.cloud.discoveryengine.v1alpha.TransactionInfo.cost] + + This field is a member of `oneof`_ ``_discount_value``. + """ + + value: float = proto.Field( + proto.FLOAT, + number=1, + optional=True, + ) + currency: str = proto.Field( + proto.STRING, + number=2, + ) + transaction_id: str = proto.Field( + proto.STRING, + number=3, + ) + tax: float = proto.Field( + proto.FLOAT, + number=4, + optional=True, + ) + cost: float = proto.Field( + proto.FLOAT, + number=5, + optional=True, + ) + discount_value: float = proto.Field( + proto.FLOAT, + number=6, + optional=True, + ) + + +class DocumentInfo(proto.Message): + r"""Detailed document information associated with a user event. + + 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: + id (str): + The + [Document][google.cloud.discoveryengine.v1alpha.Document] + resource ID. + + This field is a member of `oneof`_ ``document_descriptor``. + name (str): + The + [Document][google.cloud.discoveryengine.v1alpha.Document] + resource full name, of the form: + ``projects/{project_id}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}/branches/{branch_id}/documents/{document_id}`` + + This field is a member of `oneof`_ ``document_descriptor``. + uri (str): + The + [Document][google.cloud.discoveryengine.v1alpha.Document] + URI - only allowed for website data stores. + + This field is a member of `oneof`_ ``document_descriptor``. + quantity (int): + Quantity of the Document associated with the user event. + Defaults to 1. + + For example, this field will be 2 if two quantities of the + same Document are involved in a ``add-to-cart`` event. + + Required for events of the following event types: + + - ``add-to-cart`` + - ``purchase`` + + This field is a member of `oneof`_ ``_quantity``. + promotion_ids (MutableSequence[str]): + The promotion IDs associated with this + Document. Currently, this field is restricted to + at most one ID. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + oneof='document_descriptor', + ) + name: str = proto.Field( + proto.STRING, + number=2, + oneof='document_descriptor', + ) + uri: str = proto.Field( + proto.STRING, + number=6, + oneof='document_descriptor', + ) + quantity: int = proto.Field( + proto.INT32, + number=3, + optional=True, + ) + promotion_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + + +class PanelInfo(proto.Message): + r"""Detailed panel information associated with a user event. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + panel_id (str): + Required. The panel ID. + display_name (str): + The display name of the panel. + panel_position (int): + The ordered position of the panel, if shown to the user with + other panels. If set, then + [total_panels][google.cloud.discoveryengine.v1alpha.PanelInfo.total_panels] + must also be set. + + This field is a member of `oneof`_ ``_panel_position``. + total_panels (int): + The total number of panels, including this one, shown to the + user. Must be set if + [panel_position][google.cloud.discoveryengine.v1alpha.PanelInfo.panel_position] + is set. + + This field is a member of `oneof`_ ``_total_panels``. + """ + + panel_id: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + panel_position: int = proto.Field( + proto.INT32, + number=4, + optional=True, + ) + total_panels: int = proto.Field( + proto.INT32, + number=5, + optional=True, + ) + + +class MediaInfo(proto.Message): + r"""Media-specific user event information. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + media_progress_duration (google.protobuf.duration_pb2.Duration): + The media progress time in seconds, if applicable. For + example, if the end user has finished 90 seconds of a + playback video, then + [MediaInfo.media_progress_duration.seconds][google.protobuf.Duration.seconds] + should be set to 90. + media_progress_percentage (float): + Media progress should be computed using only the + [media_progress_duration][google.cloud.discoveryengine.v1alpha.MediaInfo.media_progress_duration] + relative to the media total length. + + This value must be between ``[0, 1.0]`` inclusive. + + If this is not a playback or the progress cannot be computed + (e.g. ongoing livestream), this field should be unset. + + This field is a member of `oneof`_ ``_media_progress_percentage``. + """ + + media_progress_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + media_progress_percentage: float = proto.Field( + proto.FLOAT, + number=2, + optional=True, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/user_event_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/user_event_service.py new file mode 100644 index 000000000000..c5ec95071940 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/user_event_service.py @@ -0,0 +1,110 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.discoveryengine_v1alpha.types import user_event as gcd_user_event + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1alpha', + manifest={ + 'WriteUserEventRequest', + 'CollectUserEventRequest', + }, +) + + +class WriteUserEventRequest(proto.Message): + r"""Request message for WriteUserEvent method. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. The parent DataStore resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. + user_event (google.cloud.discoveryengine_v1alpha.types.UserEvent): + Required. User event to write. + + This field is a member of `oneof`_ ``_user_event``. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + user_event: gcd_user_event.UserEvent = proto.Field( + proto.MESSAGE, + number=2, + optional=True, + message=gcd_user_event.UserEvent, + ) + + +class CollectUserEventRequest(proto.Message): + r"""Request message for CollectUserEvent method. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. The parent DataStore resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. + user_event (str): + Required. URL encoded UserEvent proto with a + length limit of 2,000,000 characters. + uri (str): + The URL including cgi-parameters but + excluding the hash fragment with a length limit + of 5,000 characters. This is often more useful + than the referer URL, because many browsers only + send the domain for third-party requests. + + This field is a member of `oneof`_ ``_uri``. + ets (int): + The event timestamp in milliseconds. This + prevents browser caching of otherwise identical + get requests. The name is abbreviated to reduce + the payload bytes. + + This field is a member of `oneof`_ ``_ets``. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + user_event: str = proto.Field( + proto.STRING, + number=2, + ) + uri: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + ets: int = proto.Field( + proto.INT64, + number=4, + optional=True, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/mypy.ini b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/noxfile.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/noxfile.py new file mode 100644 index 000000000000..dfc37936ccfa --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/noxfile.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.11" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/discoveryengine_v1alpha/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + 'mypy', + 'types-requests', + 'types-protobuf' + ) + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==7.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_completion_service_complete_query_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_completion_service_complete_query_async.py new file mode 100644 index 000000000000..5c669849a195 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_completion_service_complete_query_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CompleteQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_CompletionService_CompleteQuery_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_complete_query(): + # Create a client + client = discoveryengine_v1alpha.CompletionServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.CompleteQueryRequest( + data_store="data_store_value", + query="query_value", + ) + + # Make the request + response = await client.complete_query(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_CompletionService_CompleteQuery_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_completion_service_complete_query_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_completion_service_complete_query_sync.py new file mode 100644 index 000000000000..6e01114696ff --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_completion_service_complete_query_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CompleteQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_CompletionService_CompleteQuery_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_complete_query(): + # Create a client + client = discoveryengine_v1alpha.CompletionServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.CompleteQueryRequest( + data_store="data_store_value", + query="query_value", + ) + + # Make the request + response = client.complete_query(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_CompletionService_CompleteQuery_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_converse_conversation_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_converse_conversation_async.py new file mode 100644 index 000000000000..b92f6208cb53 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_converse_conversation_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ConverseConversation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_ConversationalSearchService_ConverseConversation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_converse_conversation(): + # Create a client + client = discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ConverseConversationRequest( + name="name_value", + ) + + # Make the request + response = await client.converse_conversation(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_ConversationalSearchService_ConverseConversation_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_converse_conversation_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_converse_conversation_sync.py new file mode 100644 index 000000000000..c729b8e5128a --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_converse_conversation_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ConverseConversation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_ConversationalSearchService_ConverseConversation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_converse_conversation(): + # Create a client + client = discoveryengine_v1alpha.ConversationalSearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ConverseConversationRequest( + name="name_value", + ) + + # Make the request + response = client.converse_conversation(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_ConversationalSearchService_ConverseConversation_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_create_conversation_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_create_conversation_async.py new file mode 100644 index 000000000000..6b3581f3ec78 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_create_conversation_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateConversation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_ConversationalSearchService_CreateConversation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_create_conversation(): + # Create a client + client = discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.CreateConversationRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_conversation(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_ConversationalSearchService_CreateConversation_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_create_conversation_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_create_conversation_sync.py new file mode 100644 index 000000000000..083ae91a8a5a --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_create_conversation_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateConversation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_ConversationalSearchService_CreateConversation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_create_conversation(): + # Create a client + client = discoveryengine_v1alpha.ConversationalSearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.CreateConversationRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_conversation(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_ConversationalSearchService_CreateConversation_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_delete_conversation_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_delete_conversation_async.py new file mode 100644 index 000000000000..6be302999234 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_delete_conversation_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteConversation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_ConversationalSearchService_DeleteConversation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_delete_conversation(): + # Create a client + client = discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.DeleteConversationRequest( + name="name_value", + ) + + # Make the request + await client.delete_conversation(request=request) + + +# [END discoveryengine_v1alpha_generated_ConversationalSearchService_DeleteConversation_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_delete_conversation_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_delete_conversation_sync.py new file mode 100644 index 000000000000..ef3206f9d867 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_delete_conversation_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteConversation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_ConversationalSearchService_DeleteConversation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_delete_conversation(): + # Create a client + client = discoveryengine_v1alpha.ConversationalSearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.DeleteConversationRequest( + name="name_value", + ) + + # Make the request + client.delete_conversation(request=request) + + +# [END discoveryengine_v1alpha_generated_ConversationalSearchService_DeleteConversation_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_get_conversation_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_get_conversation_async.py new file mode 100644 index 000000000000..8f8a2ed38b12 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_get_conversation_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetConversation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_ConversationalSearchService_GetConversation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_get_conversation(): + # Create a client + client = discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.GetConversationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_conversation(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_ConversationalSearchService_GetConversation_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_get_conversation_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_get_conversation_sync.py new file mode 100644 index 000000000000..a890c360cac6 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_get_conversation_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetConversation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_ConversationalSearchService_GetConversation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_get_conversation(): + # Create a client + client = discoveryengine_v1alpha.ConversationalSearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.GetConversationRequest( + name="name_value", + ) + + # Make the request + response = client.get_conversation(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_ConversationalSearchService_GetConversation_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_list_conversations_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_list_conversations_async.py new file mode 100644 index 000000000000..43cd740fdb04 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_list_conversations_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListConversations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_ConversationalSearchService_ListConversations_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_list_conversations(): + # Create a client + client = discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ListConversationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_conversations(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END discoveryengine_v1alpha_generated_ConversationalSearchService_ListConversations_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_list_conversations_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_list_conversations_sync.py new file mode 100644 index 000000000000..4ea900cd1c37 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_list_conversations_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListConversations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_ConversationalSearchService_ListConversations_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_list_conversations(): + # Create a client + client = discoveryengine_v1alpha.ConversationalSearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ListConversationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_conversations(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END discoveryengine_v1alpha_generated_ConversationalSearchService_ListConversations_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_update_conversation_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_update_conversation_async.py new file mode 100644 index 000000000000..53d6e3b5f804 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_update_conversation_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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-discoveryengine + + +# [START discoveryengine_v1alpha_generated_ConversationalSearchService_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 discoveryengine_v1alpha + + +async def sample_update_conversation(): + # Create a client + client = discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.UpdateConversationRequest( + ) + + # Make the request + response = await client.update_conversation(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_ConversationalSearchService_UpdateConversation_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_update_conversation_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_update_conversation_sync.py new file mode 100644 index 000000000000..f1bc6a28a0ab --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_update_conversation_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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-discoveryengine + + +# [START discoveryengine_v1alpha_generated_ConversationalSearchService_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 discoveryengine_v1alpha + + +def sample_update_conversation(): + # Create a client + client = discoveryengine_v1alpha.ConversationalSearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.UpdateConversationRequest( + ) + + # Make the request + response = client.update_conversation(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_ConversationalSearchService_UpdateConversation_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_create_data_store_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_create_data_store_async.py new file mode 100644 index 000000000000..d4d79cbaea8e --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_create_data_store_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateDataStore +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_DataStoreService_CreateDataStore_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_create_data_store(): + # Create a client + client = discoveryengine_v1alpha.DataStoreServiceAsyncClient() + + # Initialize request argument(s) + data_store = discoveryengine_v1alpha.DataStore() + data_store.display_name = "display_name_value" + + request = discoveryengine_v1alpha.CreateDataStoreRequest( + parent="parent_value", + data_store=data_store, + data_store_id="data_store_id_value", + ) + + # Make the request + operation = client.create_data_store(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_DataStoreService_CreateDataStore_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_create_data_store_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_create_data_store_sync.py new file mode 100644 index 000000000000..e656f88635e0 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_create_data_store_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateDataStore +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_DataStoreService_CreateDataStore_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_create_data_store(): + # Create a client + client = discoveryengine_v1alpha.DataStoreServiceClient() + + # Initialize request argument(s) + data_store = discoveryengine_v1alpha.DataStore() + data_store.display_name = "display_name_value" + + request = discoveryengine_v1alpha.CreateDataStoreRequest( + parent="parent_value", + data_store=data_store, + data_store_id="data_store_id_value", + ) + + # Make the request + operation = client.create_data_store(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_DataStoreService_CreateDataStore_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_delete_data_store_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_delete_data_store_async.py new file mode 100644 index 000000000000..9abb86648235 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_delete_data_store_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteDataStore +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_DataStoreService_DeleteDataStore_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_delete_data_store(): + # Create a client + client = discoveryengine_v1alpha.DataStoreServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.DeleteDataStoreRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_data_store(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_DataStoreService_DeleteDataStore_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_delete_data_store_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_delete_data_store_sync.py new file mode 100644 index 000000000000..2166c5fc591e --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_delete_data_store_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteDataStore +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_DataStoreService_DeleteDataStore_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_delete_data_store(): + # Create a client + client = discoveryengine_v1alpha.DataStoreServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.DeleteDataStoreRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_data_store(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_DataStoreService_DeleteDataStore_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_get_data_store_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_get_data_store_async.py new file mode 100644 index 000000000000..8742ec68794a --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_get_data_store_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDataStore +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_DataStoreService_GetDataStore_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_get_data_store(): + # Create a client + client = discoveryengine_v1alpha.DataStoreServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.GetDataStoreRequest( + name="name_value", + ) + + # Make the request + response = await client.get_data_store(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_DataStoreService_GetDataStore_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_get_data_store_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_get_data_store_sync.py new file mode 100644 index 000000000000..0f49711f3a67 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_get_data_store_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDataStore +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_DataStoreService_GetDataStore_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_get_data_store(): + # Create a client + client = discoveryengine_v1alpha.DataStoreServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.GetDataStoreRequest( + name="name_value", + ) + + # Make the request + response = client.get_data_store(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_DataStoreService_GetDataStore_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_list_data_stores_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_list_data_stores_async.py new file mode 100644 index 000000000000..dbb947ef0502 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_list_data_stores_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDataStores +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_DataStoreService_ListDataStores_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_list_data_stores(): + # Create a client + client = discoveryengine_v1alpha.DataStoreServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ListDataStoresRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_data_stores(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END discoveryengine_v1alpha_generated_DataStoreService_ListDataStores_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_list_data_stores_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_list_data_stores_sync.py new file mode 100644 index 000000000000..4d4f02b54b40 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_list_data_stores_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDataStores +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_DataStoreService_ListDataStores_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_list_data_stores(): + # Create a client + client = discoveryengine_v1alpha.DataStoreServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ListDataStoresRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_data_stores(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END discoveryengine_v1alpha_generated_DataStoreService_ListDataStores_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_update_data_store_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_update_data_store_async.py new file mode 100644 index 000000000000..e47dd4e6f9d0 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_update_data_store_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateDataStore +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_DataStoreService_UpdateDataStore_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_update_data_store(): + # Create a client + client = discoveryengine_v1alpha.DataStoreServiceAsyncClient() + + # Initialize request argument(s) + data_store = discoveryengine_v1alpha.DataStore() + data_store.display_name = "display_name_value" + + request = discoveryengine_v1alpha.UpdateDataStoreRequest( + data_store=data_store, + ) + + # Make the request + response = await client.update_data_store(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_DataStoreService_UpdateDataStore_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_update_data_store_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_update_data_store_sync.py new file mode 100644 index 000000000000..a46c8483f3d6 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_update_data_store_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateDataStore +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_DataStoreService_UpdateDataStore_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_update_data_store(): + # Create a client + client = discoveryengine_v1alpha.DataStoreServiceClient() + + # Initialize request argument(s) + data_store = discoveryengine_v1alpha.DataStore() + data_store.display_name = "display_name_value" + + request = discoveryengine_v1alpha.UpdateDataStoreRequest( + data_store=data_store, + ) + + # Make the request + response = client.update_data_store(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_DataStoreService_UpdateDataStore_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_create_document_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_create_document_async.py new file mode 100644 index 000000000000..197fa2d86cb5 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_create_document_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateDocument +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_DocumentService_CreateDocument_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_create_document(): + # Create a client + client = discoveryengine_v1alpha.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.CreateDocumentRequest( + parent="parent_value", + document_id="document_id_value", + ) + + # Make the request + response = await client.create_document(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_DocumentService_CreateDocument_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_create_document_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_create_document_sync.py new file mode 100644 index 000000000000..9d2f43561e6d --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_create_document_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateDocument +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_DocumentService_CreateDocument_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_create_document(): + # Create a client + client = discoveryengine_v1alpha.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.CreateDocumentRequest( + parent="parent_value", + document_id="document_id_value", + ) + + # Make the request + response = client.create_document(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_DocumentService_CreateDocument_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_delete_document_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_delete_document_async.py new file mode 100644 index 000000000000..94222cb3fa7f --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_delete_document_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteDocument +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_DocumentService_DeleteDocument_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_delete_document(): + # Create a client + client = discoveryengine_v1alpha.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.DeleteDocumentRequest( + name="name_value", + ) + + # Make the request + await client.delete_document(request=request) + + +# [END discoveryengine_v1alpha_generated_DocumentService_DeleteDocument_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_delete_document_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_delete_document_sync.py new file mode 100644 index 000000000000..b7f221c3a7b3 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_delete_document_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteDocument +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_DocumentService_DeleteDocument_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_delete_document(): + # Create a client + client = discoveryengine_v1alpha.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.DeleteDocumentRequest( + name="name_value", + ) + + # Make the request + client.delete_document(request=request) + + +# [END discoveryengine_v1alpha_generated_DocumentService_DeleteDocument_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_get_document_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_get_document_async.py new file mode 100644 index 000000000000..0d4b0bf5e7ac --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_get_document_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDocument +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_DocumentService_GetDocument_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_get_document(): + # Create a client + client = discoveryengine_v1alpha.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.GetDocumentRequest( + name="name_value", + ) + + # Make the request + response = await client.get_document(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_DocumentService_GetDocument_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_get_document_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_get_document_sync.py new file mode 100644 index 000000000000..5f81c278063e --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_get_document_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDocument +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_DocumentService_GetDocument_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_get_document(): + # Create a client + client = discoveryengine_v1alpha.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.GetDocumentRequest( + name="name_value", + ) + + # Make the request + response = client.get_document(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_DocumentService_GetDocument_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_import_documents_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_import_documents_async.py new file mode 100644 index 000000000000..6c6300958c5e --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_import_documents_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportDocuments +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_DocumentService_ImportDocuments_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_import_documents(): + # Create a client + client = discoveryengine_v1alpha.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ImportDocumentsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.import_documents(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_DocumentService_ImportDocuments_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_import_documents_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_import_documents_sync.py new file mode 100644 index 000000000000..26dd44fd2e50 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_import_documents_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportDocuments +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_DocumentService_ImportDocuments_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_import_documents(): + # Create a client + client = discoveryengine_v1alpha.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ImportDocumentsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.import_documents(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_DocumentService_ImportDocuments_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_list_documents_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_list_documents_async.py new file mode 100644 index 000000000000..e3dbd6905564 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_list_documents_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDocuments +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_DocumentService_ListDocuments_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_list_documents(): + # Create a client + client = discoveryengine_v1alpha.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ListDocumentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_documents(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END discoveryengine_v1alpha_generated_DocumentService_ListDocuments_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_list_documents_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_list_documents_sync.py new file mode 100644 index 000000000000..7fa03e62969b --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_list_documents_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDocuments +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_DocumentService_ListDocuments_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_list_documents(): + # Create a client + client = discoveryengine_v1alpha.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ListDocumentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_documents(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END discoveryengine_v1alpha_generated_DocumentService_ListDocuments_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_purge_documents_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_purge_documents_async.py new file mode 100644 index 000000000000..45b09d4f452b --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_purge_documents_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PurgeDocuments +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_DocumentService_PurgeDocuments_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_purge_documents(): + # Create a client + client = discoveryengine_v1alpha.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.PurgeDocumentsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_documents(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_DocumentService_PurgeDocuments_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_purge_documents_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_purge_documents_sync.py new file mode 100644 index 000000000000..8fc675f1cda3 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_purge_documents_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PurgeDocuments +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_DocumentService_PurgeDocuments_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_purge_documents(): + # Create a client + client = discoveryengine_v1alpha.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.PurgeDocumentsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_documents(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_DocumentService_PurgeDocuments_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_update_document_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_update_document_async.py new file mode 100644 index 000000000000..73c47803842d --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_update_document_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateDocument +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_DocumentService_UpdateDocument_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_update_document(): + # Create a client + client = discoveryengine_v1alpha.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.UpdateDocumentRequest( + ) + + # Make the request + response = await client.update_document(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_DocumentService_UpdateDocument_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_update_document_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_update_document_sync.py new file mode 100644 index 000000000000..68d14fe02d15 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_update_document_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateDocument +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_DocumentService_UpdateDocument_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_update_document(): + # Create a client + client = discoveryengine_v1alpha.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.UpdateDocumentRequest( + ) + + # Make the request + response = client.update_document(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_DocumentService_UpdateDocument_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_create_engine_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_create_engine_async.py new file mode 100644 index 000000000000..e613162c6b03 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_create_engine_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateEngine +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_EngineService_CreateEngine_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_create_engine(): + # Create a client + client = discoveryengine_v1alpha.EngineServiceAsyncClient() + + # Initialize request argument(s) + engine = discoveryengine_v1alpha.Engine() + engine.display_name = "display_name_value" + engine.solution_type = "SOLUTION_TYPE_CHAT" + + request = discoveryengine_v1alpha.CreateEngineRequest( + parent="parent_value", + engine=engine, + engine_id="engine_id_value", + ) + + # Make the request + operation = client.create_engine(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_EngineService_CreateEngine_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_create_engine_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_create_engine_sync.py new file mode 100644 index 000000000000..06e91fade63c --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_create_engine_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateEngine +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_EngineService_CreateEngine_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_create_engine(): + # Create a client + client = discoveryengine_v1alpha.EngineServiceClient() + + # Initialize request argument(s) + engine = discoveryengine_v1alpha.Engine() + engine.display_name = "display_name_value" + engine.solution_type = "SOLUTION_TYPE_CHAT" + + request = discoveryengine_v1alpha.CreateEngineRequest( + parent="parent_value", + engine=engine, + engine_id="engine_id_value", + ) + + # Make the request + operation = client.create_engine(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_EngineService_CreateEngine_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_delete_engine_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_delete_engine_async.py new file mode 100644 index 000000000000..4c0f5b2056c3 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_delete_engine_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteEngine +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_EngineService_DeleteEngine_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_delete_engine(): + # Create a client + client = discoveryengine_v1alpha.EngineServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.DeleteEngineRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_engine(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_EngineService_DeleteEngine_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_delete_engine_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_delete_engine_sync.py new file mode 100644 index 000000000000..46e2a7eff1e0 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_delete_engine_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteEngine +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_EngineService_DeleteEngine_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_delete_engine(): + # Create a client + client = discoveryengine_v1alpha.EngineServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.DeleteEngineRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_engine(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_EngineService_DeleteEngine_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_get_engine_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_get_engine_async.py new file mode 100644 index 000000000000..c2a223dd97df --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_get_engine_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEngine +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_EngineService_GetEngine_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_get_engine(): + # Create a client + client = discoveryengine_v1alpha.EngineServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.GetEngineRequest( + name="name_value", + ) + + # Make the request + response = await client.get_engine(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_EngineService_GetEngine_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_get_engine_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_get_engine_sync.py new file mode 100644 index 000000000000..a04573bd5d85 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_get_engine_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEngine +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_EngineService_GetEngine_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_get_engine(): + # Create a client + client = discoveryengine_v1alpha.EngineServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.GetEngineRequest( + name="name_value", + ) + + # Make the request + response = client.get_engine(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_EngineService_GetEngine_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_list_engines_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_list_engines_async.py new file mode 100644 index 000000000000..c7f0d4599758 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_list_engines_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListEngines +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_EngineService_ListEngines_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_list_engines(): + # Create a client + client = discoveryengine_v1alpha.EngineServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ListEnginesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_engines(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END discoveryengine_v1alpha_generated_EngineService_ListEngines_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_list_engines_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_list_engines_sync.py new file mode 100644 index 000000000000..632b1da8f0b2 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_list_engines_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListEngines +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_EngineService_ListEngines_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_list_engines(): + # Create a client + client = discoveryengine_v1alpha.EngineServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ListEnginesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_engines(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END discoveryengine_v1alpha_generated_EngineService_ListEngines_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_pause_engine_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_pause_engine_async.py new file mode 100644 index 000000000000..637e58a2462e --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_pause_engine_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PauseEngine +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_EngineService_PauseEngine_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_pause_engine(): + # Create a client + client = discoveryengine_v1alpha.EngineServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.PauseEngineRequest( + name="name_value", + ) + + # Make the request + response = await client.pause_engine(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_EngineService_PauseEngine_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_pause_engine_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_pause_engine_sync.py new file mode 100644 index 000000000000..435b1b301973 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_pause_engine_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PauseEngine +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_EngineService_PauseEngine_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_pause_engine(): + # Create a client + client = discoveryengine_v1alpha.EngineServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.PauseEngineRequest( + name="name_value", + ) + + # Make the request + response = client.pause_engine(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_EngineService_PauseEngine_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_resume_engine_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_resume_engine_async.py new file mode 100644 index 000000000000..1c1aeef48b3a --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_resume_engine_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ResumeEngine +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_EngineService_ResumeEngine_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_resume_engine(): + # Create a client + client = discoveryengine_v1alpha.EngineServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ResumeEngineRequest( + name="name_value", + ) + + # Make the request + response = await client.resume_engine(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_EngineService_ResumeEngine_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_resume_engine_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_resume_engine_sync.py new file mode 100644 index 000000000000..604d0b157978 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_resume_engine_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ResumeEngine +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_EngineService_ResumeEngine_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_resume_engine(): + # Create a client + client = discoveryengine_v1alpha.EngineServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ResumeEngineRequest( + name="name_value", + ) + + # Make the request + response = client.resume_engine(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_EngineService_ResumeEngine_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_tune_engine_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_tune_engine_async.py new file mode 100644 index 000000000000..d47e4a345059 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_tune_engine_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for TuneEngine +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_EngineService_TuneEngine_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_tune_engine(): + # Create a client + client = discoveryengine_v1alpha.EngineServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.TuneEngineRequest( + name="name_value", + ) + + # Make the request + operation = client.tune_engine(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_EngineService_TuneEngine_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_tune_engine_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_tune_engine_sync.py new file mode 100644 index 000000000000..ccd188fef503 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_tune_engine_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for TuneEngine +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_EngineService_TuneEngine_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_tune_engine(): + # Create a client + client = discoveryengine_v1alpha.EngineServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.TuneEngineRequest( + name="name_value", + ) + + # Make the request + operation = client.tune_engine(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_EngineService_TuneEngine_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_update_engine_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_update_engine_async.py new file mode 100644 index 000000000000..e3539d0285f1 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_update_engine_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateEngine +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_EngineService_UpdateEngine_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_update_engine(): + # Create a client + client = discoveryengine_v1alpha.EngineServiceAsyncClient() + + # Initialize request argument(s) + engine = discoveryengine_v1alpha.Engine() + engine.display_name = "display_name_value" + engine.solution_type = "SOLUTION_TYPE_CHAT" + + request = discoveryengine_v1alpha.UpdateEngineRequest( + engine=engine, + ) + + # Make the request + response = await client.update_engine(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_EngineService_UpdateEngine_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_update_engine_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_update_engine_sync.py new file mode 100644 index 000000000000..e08b1f09fbb7 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_update_engine_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateEngine +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_EngineService_UpdateEngine_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_update_engine(): + # Create a client + client = discoveryengine_v1alpha.EngineServiceClient() + + # Initialize request argument(s) + engine = discoveryengine_v1alpha.Engine() + engine.display_name = "display_name_value" + engine.solution_type = "SOLUTION_TYPE_CHAT" + + request = discoveryengine_v1alpha.UpdateEngineRequest( + engine=engine, + ) + + # Make the request + response = client.update_engine(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_EngineService_UpdateEngine_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_recommendation_service_recommend_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_recommendation_service_recommend_async.py new file mode 100644 index 000000000000..25ad50f34a8c --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_recommendation_service_recommend_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Recommend +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_RecommendationService_Recommend_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_recommend(): + # Create a client + client = discoveryengine_v1alpha.RecommendationServiceAsyncClient() + + # Initialize request argument(s) + user_event = discoveryengine_v1alpha.UserEvent() + user_event.event_type = "event_type_value" + user_event.user_pseudo_id = "user_pseudo_id_value" + + request = discoveryengine_v1alpha.RecommendRequest( + serving_config="serving_config_value", + user_event=user_event, + ) + + # Make the request + response = await client.recommend(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_RecommendationService_Recommend_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_recommendation_service_recommend_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_recommendation_service_recommend_sync.py new file mode 100644 index 000000000000..7da58be33a1f --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_recommendation_service_recommend_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Recommend +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_RecommendationService_Recommend_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_recommend(): + # Create a client + client = discoveryengine_v1alpha.RecommendationServiceClient() + + # Initialize request argument(s) + user_event = discoveryengine_v1alpha.UserEvent() + user_event.event_type = "event_type_value" + user_event.user_pseudo_id = "user_pseudo_id_value" + + request = discoveryengine_v1alpha.RecommendRequest( + serving_config="serving_config_value", + user_event=user_event, + ) + + # Make the request + response = client.recommend(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_RecommendationService_Recommend_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_create_schema_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_create_schema_async.py new file mode 100644 index 000000000000..34f0bc7db5eb --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_create_schema_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_SchemaService_CreateSchema_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_create_schema(): + # Create a client + client = discoveryengine_v1alpha.SchemaServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.CreateSchemaRequest( + parent="parent_value", + schema_id="schema_id_value", + ) + + # Make the request + operation = client.create_schema(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_SchemaService_CreateSchema_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_create_schema_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_create_schema_sync.py new file mode 100644 index 000000000000..b0cd2f174166 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_create_schema_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_SchemaService_CreateSchema_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_create_schema(): + # Create a client + client = discoveryengine_v1alpha.SchemaServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.CreateSchemaRequest( + parent="parent_value", + schema_id="schema_id_value", + ) + + # Make the request + operation = client.create_schema(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_SchemaService_CreateSchema_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_delete_schema_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_delete_schema_async.py new file mode 100644 index 000000000000..7c195b6508c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_delete_schema_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_SchemaService_DeleteSchema_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_delete_schema(): + # Create a client + client = discoveryengine_v1alpha.SchemaServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.DeleteSchemaRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_schema(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_SchemaService_DeleteSchema_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_delete_schema_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_delete_schema_sync.py new file mode 100644 index 000000000000..dff9cfb661b1 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_delete_schema_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_SchemaService_DeleteSchema_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_delete_schema(): + # Create a client + client = discoveryengine_v1alpha.SchemaServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.DeleteSchemaRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_schema(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_SchemaService_DeleteSchema_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_get_schema_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_get_schema_async.py new file mode 100644 index 000000000000..c9da228ac811 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_get_schema_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_SchemaService_GetSchema_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_get_schema(): + # Create a client + client = discoveryengine_v1alpha.SchemaServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.GetSchemaRequest( + name="name_value", + ) + + # Make the request + response = await client.get_schema(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_SchemaService_GetSchema_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_get_schema_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_get_schema_sync.py new file mode 100644 index 000000000000..ea9e973843dd --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_get_schema_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_SchemaService_GetSchema_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_get_schema(): + # Create a client + client = discoveryengine_v1alpha.SchemaServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.GetSchemaRequest( + name="name_value", + ) + + # Make the request + response = client.get_schema(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_SchemaService_GetSchema_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_list_schemas_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_list_schemas_async.py new file mode 100644 index 000000000000..594f682f8dea --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_list_schemas_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSchemas +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_SchemaService_ListSchemas_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_list_schemas(): + # Create a client + client = discoveryengine_v1alpha.SchemaServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ListSchemasRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_schemas(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END discoveryengine_v1alpha_generated_SchemaService_ListSchemas_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_list_schemas_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_list_schemas_sync.py new file mode 100644 index 000000000000..476fe6943a0a --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_list_schemas_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSchemas +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_SchemaService_ListSchemas_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_list_schemas(): + # Create a client + client = discoveryengine_v1alpha.SchemaServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.ListSchemasRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_schemas(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END discoveryengine_v1alpha_generated_SchemaService_ListSchemas_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_update_schema_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_update_schema_async.py new file mode 100644 index 000000000000..15ecd5c92277 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_update_schema_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_SchemaService_UpdateSchema_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_update_schema(): + # Create a client + client = discoveryengine_v1alpha.SchemaServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.UpdateSchemaRequest( + ) + + # Make the request + operation = client.update_schema(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_SchemaService_UpdateSchema_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_update_schema_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_update_schema_sync.py new file mode 100644 index 000000000000..751bbefc31fb --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_update_schema_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_SchemaService_UpdateSchema_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_update_schema(): + # Create a client + client = discoveryengine_v1alpha.SchemaServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.UpdateSchemaRequest( + ) + + # Make the request + operation = client.update_schema(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_SchemaService_UpdateSchema_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_search_service_search_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_search_service_search_async.py new file mode 100644 index 000000000000..ed04cd567ada --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_search_service_search_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Search +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_SearchService_Search_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_search(): + # Create a client + client = discoveryengine_v1alpha.SearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.SearchRequest( + serving_config="serving_config_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END discoveryengine_v1alpha_generated_SearchService_Search_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_search_service_search_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_search_service_search_sync.py new file mode 100644 index 000000000000..ca39f556b3b2 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_search_service_search_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Search +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_SearchService_Search_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_search(): + # Create a client + client = discoveryengine_v1alpha.SearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.SearchRequest( + serving_config="serving_config_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END discoveryengine_v1alpha_generated_SearchService_Search_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_site_search_engine_service_recrawl_uris_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_site_search_engine_service_recrawl_uris_async.py new file mode 100644 index 000000000000..7a083fc2362b --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_site_search_engine_service_recrawl_uris_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RecrawlUris +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_SiteSearchEngineService_RecrawlUris_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_recrawl_uris(): + # Create a client + client = discoveryengine_v1alpha.SiteSearchEngineServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.RecrawlUrisRequest( + site_search_engine="site_search_engine_value", + uris=['uris_value1', 'uris_value2'], + ) + + # Make the request + operation = client.recrawl_uris(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_SiteSearchEngineService_RecrawlUris_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_site_search_engine_service_recrawl_uris_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_site_search_engine_service_recrawl_uris_sync.py new file mode 100644 index 000000000000..f0e38570263e --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_site_search_engine_service_recrawl_uris_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RecrawlUris +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_SiteSearchEngineService_RecrawlUris_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_recrawl_uris(): + # Create a client + client = discoveryengine_v1alpha.SiteSearchEngineServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.RecrawlUrisRequest( + site_search_engine="site_search_engine_value", + uris=['uris_value1', 'uris_value2'], + ) + + # Make the request + operation = client.recrawl_uris(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_SiteSearchEngineService_RecrawlUris_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_collect_user_event_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_collect_user_event_async.py new file mode 100644 index 000000000000..66c89511c060 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_collect_user_event_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CollectUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_UserEventService_CollectUserEvent_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_collect_user_event(): + # Create a client + client = discoveryengine_v1alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = await client.collect_user_event(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_UserEventService_CollectUserEvent_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_collect_user_event_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_collect_user_event_sync.py new file mode 100644 index 000000000000..bf5d7495686b --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_collect_user_event_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CollectUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_UserEventService_CollectUserEvent_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_collect_user_event(): + # Create a client + client = discoveryengine_v1alpha.UserEventServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = client.collect_user_event(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_UserEventService_CollectUserEvent_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_import_user_events_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_import_user_events_async.py new file mode 100644 index 000000000000..e94e32400499 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_import_user_events_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_UserEventService_ImportUserEvents_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_import_user_events(): + # Create a client + client = discoveryengine_v1alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + inline_source = discoveryengine_v1alpha.InlineSource() + inline_source.user_events.event_type = "event_type_value" + inline_source.user_events.user_pseudo_id = "user_pseudo_id_value" + + request = discoveryengine_v1alpha.ImportUserEventsRequest( + inline_source=inline_source, + parent="parent_value", + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_UserEventService_ImportUserEvents_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_import_user_events_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_import_user_events_sync.py new file mode 100644 index 000000000000..6fe5c9dfe3a0 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_import_user_events_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_UserEventService_ImportUserEvents_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_import_user_events(): + # Create a client + client = discoveryengine_v1alpha.UserEventServiceClient() + + # Initialize request argument(s) + inline_source = discoveryengine_v1alpha.InlineSource() + inline_source.user_events.event_type = "event_type_value" + inline_source.user_events.user_pseudo_id = "user_pseudo_id_value" + + request = discoveryengine_v1alpha.ImportUserEventsRequest( + inline_source=inline_source, + parent="parent_value", + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_UserEventService_ImportUserEvents_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_purge_user_events_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_purge_user_events_async.py new file mode 100644 index 000000000000..fe3f264a8936 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_purge_user_events_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PurgeUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_UserEventService_PurgeUserEvents_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_purge_user_events(): + # Create a client + client = discoveryengine_v1alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_UserEventService_PurgeUserEvents_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_purge_user_events_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_purge_user_events_sync.py new file mode 100644 index 000000000000..0801661354e9 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_purge_user_events_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PurgeUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_UserEventService_PurgeUserEvents_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_purge_user_events(): + # Create a client + client = discoveryengine_v1alpha.UserEventServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.PurgeUserEventsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_UserEventService_PurgeUserEvents_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_write_user_event_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_write_user_event_async.py new file mode 100644 index 000000000000..674fe125a506 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_write_user_event_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for WriteUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_UserEventService_WriteUserEvent_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +async def sample_write_user_event(): + # Create a client + client = discoveryengine_v1alpha.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.WriteUserEventRequest( + parent="parent_value", + ) + + # Make the request + response = await client.write_user_event(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_UserEventService_WriteUserEvent_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_write_user_event_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_write_user_event_sync.py new file mode 100644 index 000000000000..19d53382b452 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_write_user_event_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for WriteUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1alpha_generated_UserEventService_WriteUserEvent_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1alpha + + +def sample_write_user_event(): + # Create a client + client = discoveryengine_v1alpha.UserEventServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1alpha.WriteUserEventRequest( + parent="parent_value", + ) + + # Make the request + response = client.write_user_event(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1alpha_generated_UserEventService_WriteUserEvent_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1alpha.json b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1alpha.json new file mode 100644 index 000000000000..ce41071d0b4c --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1alpha.json @@ -0,0 +1,6290 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.discoveryengine.v1alpha", + "version": "v1alpha" + } + ], + "language": "PYTHON", + "name": "google-cloud-discoveryengine", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.CompletionServiceAsyncClient", + "shortName": "CompletionServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.CompletionServiceAsyncClient.complete_query", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.CompletionService.CompleteQuery", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "CompleteQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.CompleteQueryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.CompleteQueryResponse", + "shortName": "complete_query" + }, + "description": "Sample for CompleteQuery", + "file": "discoveryengine_v1alpha_generated_completion_service_complete_query_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_CompletionService_CompleteQuery_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": "discoveryengine_v1alpha_generated_completion_service_complete_query_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.CompletionServiceClient", + "shortName": "CompletionServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.CompletionServiceClient.complete_query", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.CompletionService.CompleteQuery", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "CompleteQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.CompleteQueryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.CompleteQueryResponse", + "shortName": "complete_query" + }, + "description": "Sample for CompleteQuery", + "file": "discoveryengine_v1alpha_generated_completion_service_complete_query_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_CompletionService_CompleteQuery_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": "discoveryengine_v1alpha_generated_completion_service_complete_query_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient", + "shortName": "ConversationalSearchServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient.converse_conversation", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService.ConverseConversation", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService", + "shortName": "ConversationalSearchService" + }, + "shortName": "ConverseConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.ConverseConversationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "query", + "type": "google.cloud.discoveryengine_v1alpha.types.TextInput" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.ConverseConversationResponse", + "shortName": "converse_conversation" + }, + "description": "Sample for ConverseConversation", + "file": "discoveryengine_v1alpha_generated_conversational_search_service_converse_conversation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_ConversationalSearchService_ConverseConversation_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": "discoveryengine_v1alpha_generated_conversational_search_service_converse_conversation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceClient", + "shortName": "ConversationalSearchServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceClient.converse_conversation", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService.ConverseConversation", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService", + "shortName": "ConversationalSearchService" + }, + "shortName": "ConverseConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.ConverseConversationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "query", + "type": "google.cloud.discoveryengine_v1alpha.types.TextInput" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.ConverseConversationResponse", + "shortName": "converse_conversation" + }, + "description": "Sample for ConverseConversation", + "file": "discoveryengine_v1alpha_generated_conversational_search_service_converse_conversation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_ConversationalSearchService_ConverseConversation_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": "discoveryengine_v1alpha_generated_conversational_search_service_converse_conversation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient", + "shortName": "ConversationalSearchServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient.create_conversation", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService.CreateConversation", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService", + "shortName": "ConversationalSearchService" + }, + "shortName": "CreateConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.CreateConversationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "conversation", + "type": "google.cloud.discoveryengine_v1alpha.types.Conversation" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.Conversation", + "shortName": "create_conversation" + }, + "description": "Sample for CreateConversation", + "file": "discoveryengine_v1alpha_generated_conversational_search_service_create_conversation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_ConversationalSearchService_CreateConversation_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": "discoveryengine_v1alpha_generated_conversational_search_service_create_conversation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceClient", + "shortName": "ConversationalSearchServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceClient.create_conversation", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService.CreateConversation", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService", + "shortName": "ConversationalSearchService" + }, + "shortName": "CreateConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.CreateConversationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "conversation", + "type": "google.cloud.discoveryengine_v1alpha.types.Conversation" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.Conversation", + "shortName": "create_conversation" + }, + "description": "Sample for CreateConversation", + "file": "discoveryengine_v1alpha_generated_conversational_search_service_create_conversation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_ConversationalSearchService_CreateConversation_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": "discoveryengine_v1alpha_generated_conversational_search_service_create_conversation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient", + "shortName": "ConversationalSearchServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient.delete_conversation", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService.DeleteConversation", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService", + "shortName": "ConversationalSearchService" + }, + "shortName": "DeleteConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.DeleteConversationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_conversation" + }, + "description": "Sample for DeleteConversation", + "file": "discoveryengine_v1alpha_generated_conversational_search_service_delete_conversation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_ConversationalSearchService_DeleteConversation_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": "discoveryengine_v1alpha_generated_conversational_search_service_delete_conversation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceClient", + "shortName": "ConversationalSearchServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceClient.delete_conversation", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService.DeleteConversation", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService", + "shortName": "ConversationalSearchService" + }, + "shortName": "DeleteConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.DeleteConversationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_conversation" + }, + "description": "Sample for DeleteConversation", + "file": "discoveryengine_v1alpha_generated_conversational_search_service_delete_conversation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_ConversationalSearchService_DeleteConversation_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": "discoveryengine_v1alpha_generated_conversational_search_service_delete_conversation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient", + "shortName": "ConversationalSearchServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient.get_conversation", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService.GetConversation", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService", + "shortName": "ConversationalSearchService" + }, + "shortName": "GetConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.GetConversationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.Conversation", + "shortName": "get_conversation" + }, + "description": "Sample for GetConversation", + "file": "discoveryengine_v1alpha_generated_conversational_search_service_get_conversation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_ConversationalSearchService_GetConversation_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": "discoveryengine_v1alpha_generated_conversational_search_service_get_conversation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceClient", + "shortName": "ConversationalSearchServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceClient.get_conversation", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService.GetConversation", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService", + "shortName": "ConversationalSearchService" + }, + "shortName": "GetConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.GetConversationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.Conversation", + "shortName": "get_conversation" + }, + "description": "Sample for GetConversation", + "file": "discoveryengine_v1alpha_generated_conversational_search_service_get_conversation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_ConversationalSearchService_GetConversation_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": "discoveryengine_v1alpha_generated_conversational_search_service_get_conversation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient", + "shortName": "ConversationalSearchServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient.list_conversations", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService.ListConversations", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService", + "shortName": "ConversationalSearchService" + }, + "shortName": "ListConversations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.ListConversationsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.services.conversational_search_service.pagers.ListConversationsAsyncPager", + "shortName": "list_conversations" + }, + "description": "Sample for ListConversations", + "file": "discoveryengine_v1alpha_generated_conversational_search_service_list_conversations_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_ConversationalSearchService_ListConversations_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": "discoveryengine_v1alpha_generated_conversational_search_service_list_conversations_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceClient", + "shortName": "ConversationalSearchServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceClient.list_conversations", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService.ListConversations", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService", + "shortName": "ConversationalSearchService" + }, + "shortName": "ListConversations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.ListConversationsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.services.conversational_search_service.pagers.ListConversationsPager", + "shortName": "list_conversations" + }, + "description": "Sample for ListConversations", + "file": "discoveryengine_v1alpha_generated_conversational_search_service_list_conversations_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_ConversationalSearchService_ListConversations_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": "discoveryengine_v1alpha_generated_conversational_search_service_list_conversations_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient", + "shortName": "ConversationalSearchServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient.update_conversation", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService.UpdateConversation", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService", + "shortName": "ConversationalSearchService" + }, + "shortName": "UpdateConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.UpdateConversationRequest" + }, + { + "name": "conversation", + "type": "google.cloud.discoveryengine_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, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.Conversation", + "shortName": "update_conversation" + }, + "description": "Sample for UpdateConversation", + "file": "discoveryengine_v1alpha_generated_conversational_search_service_update_conversation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_ConversationalSearchService_UpdateConversation_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": "discoveryengine_v1alpha_generated_conversational_search_service_update_conversation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceClient", + "shortName": "ConversationalSearchServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceClient.update_conversation", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService.UpdateConversation", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService", + "shortName": "ConversationalSearchService" + }, + "shortName": "UpdateConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.UpdateConversationRequest" + }, + { + "name": "conversation", + "type": "google.cloud.discoveryengine_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, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.Conversation", + "shortName": "update_conversation" + }, + "description": "Sample for UpdateConversation", + "file": "discoveryengine_v1alpha_generated_conversational_search_service_update_conversation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_ConversationalSearchService_UpdateConversation_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": "discoveryengine_v1alpha_generated_conversational_search_service_update_conversation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceAsyncClient", + "shortName": "DataStoreServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceAsyncClient.create_data_store", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService.CreateDataStore", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService", + "shortName": "DataStoreService" + }, + "shortName": "CreateDataStore" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.CreateDataStoreRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "data_store", + "type": "google.cloud.discoveryengine_v1alpha.types.DataStore" + }, + { + "name": "data_store_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_data_store" + }, + "description": "Sample for CreateDataStore", + "file": "discoveryengine_v1alpha_generated_data_store_service_create_data_store_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_DataStoreService_CreateDataStore_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": "discoveryengine_v1alpha_generated_data_store_service_create_data_store_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceClient", + "shortName": "DataStoreServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceClient.create_data_store", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService.CreateDataStore", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService", + "shortName": "DataStoreService" + }, + "shortName": "CreateDataStore" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.CreateDataStoreRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "data_store", + "type": "google.cloud.discoveryengine_v1alpha.types.DataStore" + }, + { + "name": "data_store_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_data_store" + }, + "description": "Sample for CreateDataStore", + "file": "discoveryengine_v1alpha_generated_data_store_service_create_data_store_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_DataStoreService_CreateDataStore_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": "discoveryengine_v1alpha_generated_data_store_service_create_data_store_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceAsyncClient", + "shortName": "DataStoreServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceAsyncClient.delete_data_store", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService.DeleteDataStore", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService", + "shortName": "DataStoreService" + }, + "shortName": "DeleteDataStore" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.DeleteDataStoreRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_data_store" + }, + "description": "Sample for DeleteDataStore", + "file": "discoveryengine_v1alpha_generated_data_store_service_delete_data_store_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_DataStoreService_DeleteDataStore_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": "discoveryengine_v1alpha_generated_data_store_service_delete_data_store_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceClient", + "shortName": "DataStoreServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceClient.delete_data_store", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService.DeleteDataStore", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService", + "shortName": "DataStoreService" + }, + "shortName": "DeleteDataStore" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.DeleteDataStoreRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_data_store" + }, + "description": "Sample for DeleteDataStore", + "file": "discoveryengine_v1alpha_generated_data_store_service_delete_data_store_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_DataStoreService_DeleteDataStore_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": "discoveryengine_v1alpha_generated_data_store_service_delete_data_store_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceAsyncClient", + "shortName": "DataStoreServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceAsyncClient.get_data_store", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService.GetDataStore", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService", + "shortName": "DataStoreService" + }, + "shortName": "GetDataStore" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.GetDataStoreRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.DataStore", + "shortName": "get_data_store" + }, + "description": "Sample for GetDataStore", + "file": "discoveryengine_v1alpha_generated_data_store_service_get_data_store_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_DataStoreService_GetDataStore_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": "discoveryengine_v1alpha_generated_data_store_service_get_data_store_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceClient", + "shortName": "DataStoreServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceClient.get_data_store", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService.GetDataStore", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService", + "shortName": "DataStoreService" + }, + "shortName": "GetDataStore" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.GetDataStoreRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.DataStore", + "shortName": "get_data_store" + }, + "description": "Sample for GetDataStore", + "file": "discoveryengine_v1alpha_generated_data_store_service_get_data_store_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_DataStoreService_GetDataStore_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": "discoveryengine_v1alpha_generated_data_store_service_get_data_store_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceAsyncClient", + "shortName": "DataStoreServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceAsyncClient.list_data_stores", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService.ListDataStores", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService", + "shortName": "DataStoreService" + }, + "shortName": "ListDataStores" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.ListDataStoresRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.services.data_store_service.pagers.ListDataStoresAsyncPager", + "shortName": "list_data_stores" + }, + "description": "Sample for ListDataStores", + "file": "discoveryengine_v1alpha_generated_data_store_service_list_data_stores_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_DataStoreService_ListDataStores_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": "discoveryengine_v1alpha_generated_data_store_service_list_data_stores_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceClient", + "shortName": "DataStoreServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceClient.list_data_stores", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService.ListDataStores", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService", + "shortName": "DataStoreService" + }, + "shortName": "ListDataStores" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.ListDataStoresRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.services.data_store_service.pagers.ListDataStoresPager", + "shortName": "list_data_stores" + }, + "description": "Sample for ListDataStores", + "file": "discoveryengine_v1alpha_generated_data_store_service_list_data_stores_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_DataStoreService_ListDataStores_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": "discoveryengine_v1alpha_generated_data_store_service_list_data_stores_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceAsyncClient", + "shortName": "DataStoreServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceAsyncClient.update_data_store", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService.UpdateDataStore", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService", + "shortName": "DataStoreService" + }, + "shortName": "UpdateDataStore" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.UpdateDataStoreRequest" + }, + { + "name": "data_store", + "type": "google.cloud.discoveryengine_v1alpha.types.DataStore" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.DataStore", + "shortName": "update_data_store" + }, + "description": "Sample for UpdateDataStore", + "file": "discoveryengine_v1alpha_generated_data_store_service_update_data_store_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_DataStoreService_UpdateDataStore_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": "discoveryengine_v1alpha_generated_data_store_service_update_data_store_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceClient", + "shortName": "DataStoreServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceClient.update_data_store", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService.UpdateDataStore", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService", + "shortName": "DataStoreService" + }, + "shortName": "UpdateDataStore" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.UpdateDataStoreRequest" + }, + { + "name": "data_store", + "type": "google.cloud.discoveryengine_v1alpha.types.DataStore" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.DataStore", + "shortName": "update_data_store" + }, + "description": "Sample for UpdateDataStore", + "file": "discoveryengine_v1alpha_generated_data_store_service_update_data_store_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_DataStoreService_UpdateDataStore_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": "discoveryengine_v1alpha_generated_data_store_service_update_data_store_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient", + "shortName": "DocumentServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient.create_document", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.CreateDocument", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "CreateDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.CreateDocumentRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "document", + "type": "google.cloud.discoveryengine_v1alpha.types.Document" + }, + { + "name": "document_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.Document", + "shortName": "create_document" + }, + "description": "Sample for CreateDocument", + "file": "discoveryengine_v1alpha_generated_document_service_create_document_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_DocumentService_CreateDocument_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": "discoveryengine_v1alpha_generated_document_service_create_document_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient", + "shortName": "DocumentServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient.create_document", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.CreateDocument", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "CreateDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.CreateDocumentRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "document", + "type": "google.cloud.discoveryengine_v1alpha.types.Document" + }, + { + "name": "document_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.Document", + "shortName": "create_document" + }, + "description": "Sample for CreateDocument", + "file": "discoveryengine_v1alpha_generated_document_service_create_document_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_DocumentService_CreateDocument_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": "discoveryengine_v1alpha_generated_document_service_create_document_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient", + "shortName": "DocumentServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient.delete_document", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.DeleteDocument", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "DeleteDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.DeleteDocumentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_document" + }, + "description": "Sample for DeleteDocument", + "file": "discoveryengine_v1alpha_generated_document_service_delete_document_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_DocumentService_DeleteDocument_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": "discoveryengine_v1alpha_generated_document_service_delete_document_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient", + "shortName": "DocumentServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient.delete_document", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.DeleteDocument", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "DeleteDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.DeleteDocumentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_document" + }, + "description": "Sample for DeleteDocument", + "file": "discoveryengine_v1alpha_generated_document_service_delete_document_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_DocumentService_DeleteDocument_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": "discoveryengine_v1alpha_generated_document_service_delete_document_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient", + "shortName": "DocumentServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient.get_document", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.GetDocument", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "GetDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.GetDocumentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.Document", + "shortName": "get_document" + }, + "description": "Sample for GetDocument", + "file": "discoveryengine_v1alpha_generated_document_service_get_document_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_DocumentService_GetDocument_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": "discoveryengine_v1alpha_generated_document_service_get_document_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient", + "shortName": "DocumentServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient.get_document", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.GetDocument", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "GetDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.GetDocumentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.Document", + "shortName": "get_document" + }, + "description": "Sample for GetDocument", + "file": "discoveryengine_v1alpha_generated_document_service_get_document_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_DocumentService_GetDocument_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": "discoveryengine_v1alpha_generated_document_service_get_document_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient", + "shortName": "DocumentServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient.import_documents", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.ImportDocuments", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "ImportDocuments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.ImportDocumentsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "import_documents" + }, + "description": "Sample for ImportDocuments", + "file": "discoveryengine_v1alpha_generated_document_service_import_documents_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_DocumentService_ImportDocuments_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": "discoveryengine_v1alpha_generated_document_service_import_documents_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient", + "shortName": "DocumentServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient.import_documents", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.ImportDocuments", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "ImportDocuments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.ImportDocumentsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "import_documents" + }, + "description": "Sample for ImportDocuments", + "file": "discoveryengine_v1alpha_generated_document_service_import_documents_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_DocumentService_ImportDocuments_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": "discoveryengine_v1alpha_generated_document_service_import_documents_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient", + "shortName": "DocumentServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient.list_documents", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.ListDocuments", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "ListDocuments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.ListDocumentsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.services.document_service.pagers.ListDocumentsAsyncPager", + "shortName": "list_documents" + }, + "description": "Sample for ListDocuments", + "file": "discoveryengine_v1alpha_generated_document_service_list_documents_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_DocumentService_ListDocuments_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": "discoveryengine_v1alpha_generated_document_service_list_documents_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient", + "shortName": "DocumentServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient.list_documents", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.ListDocuments", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "ListDocuments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.ListDocumentsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.services.document_service.pagers.ListDocumentsPager", + "shortName": "list_documents" + }, + "description": "Sample for ListDocuments", + "file": "discoveryengine_v1alpha_generated_document_service_list_documents_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_DocumentService_ListDocuments_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": "discoveryengine_v1alpha_generated_document_service_list_documents_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient", + "shortName": "DocumentServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient.purge_documents", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.PurgeDocuments", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "PurgeDocuments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.PurgeDocumentsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "purge_documents" + }, + "description": "Sample for PurgeDocuments", + "file": "discoveryengine_v1alpha_generated_document_service_purge_documents_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_DocumentService_PurgeDocuments_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": "discoveryengine_v1alpha_generated_document_service_purge_documents_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient", + "shortName": "DocumentServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient.purge_documents", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.PurgeDocuments", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "PurgeDocuments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.PurgeDocumentsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "purge_documents" + }, + "description": "Sample for PurgeDocuments", + "file": "discoveryengine_v1alpha_generated_document_service_purge_documents_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_DocumentService_PurgeDocuments_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": "discoveryengine_v1alpha_generated_document_service_purge_documents_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient", + "shortName": "DocumentServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient.update_document", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.UpdateDocument", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "UpdateDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.UpdateDocumentRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.Document", + "shortName": "update_document" + }, + "description": "Sample for UpdateDocument", + "file": "discoveryengine_v1alpha_generated_document_service_update_document_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_DocumentService_UpdateDocument_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": "discoveryengine_v1alpha_generated_document_service_update_document_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient", + "shortName": "DocumentServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient.update_document", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.UpdateDocument", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "UpdateDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.UpdateDocumentRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.Document", + "shortName": "update_document" + }, + "description": "Sample for UpdateDocument", + "file": "discoveryengine_v1alpha_generated_document_service_update_document_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_DocumentService_UpdateDocument_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": "discoveryengine_v1alpha_generated_document_service_update_document_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient", + "shortName": "EngineServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient.create_engine", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.CreateEngine", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", + "shortName": "EngineService" + }, + "shortName": "CreateEngine" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.CreateEngineRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "engine", + "type": "google.cloud.discoveryengine_v1alpha.types.Engine" + }, + { + "name": "engine_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_engine" + }, + "description": "Sample for CreateEngine", + "file": "discoveryengine_v1alpha_generated_engine_service_create_engine_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_EngineService_CreateEngine_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1alpha_generated_engine_service_create_engine_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient", + "shortName": "EngineServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient.create_engine", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.CreateEngine", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", + "shortName": "EngineService" + }, + "shortName": "CreateEngine" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.CreateEngineRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "engine", + "type": "google.cloud.discoveryengine_v1alpha.types.Engine" + }, + { + "name": "engine_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_engine" + }, + "description": "Sample for CreateEngine", + "file": "discoveryengine_v1alpha_generated_engine_service_create_engine_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_EngineService_CreateEngine_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1alpha_generated_engine_service_create_engine_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient", + "shortName": "EngineServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient.delete_engine", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.DeleteEngine", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", + "shortName": "EngineService" + }, + "shortName": "DeleteEngine" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.DeleteEngineRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_engine" + }, + "description": "Sample for DeleteEngine", + "file": "discoveryengine_v1alpha_generated_engine_service_delete_engine_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_EngineService_DeleteEngine_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": "discoveryengine_v1alpha_generated_engine_service_delete_engine_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient", + "shortName": "EngineServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient.delete_engine", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.DeleteEngine", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", + "shortName": "EngineService" + }, + "shortName": "DeleteEngine" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.DeleteEngineRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_engine" + }, + "description": "Sample for DeleteEngine", + "file": "discoveryengine_v1alpha_generated_engine_service_delete_engine_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_EngineService_DeleteEngine_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": "discoveryengine_v1alpha_generated_engine_service_delete_engine_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient", + "shortName": "EngineServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient.get_engine", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.GetEngine", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", + "shortName": "EngineService" + }, + "shortName": "GetEngine" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.GetEngineRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.Engine", + "shortName": "get_engine" + }, + "description": "Sample for GetEngine", + "file": "discoveryengine_v1alpha_generated_engine_service_get_engine_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_EngineService_GetEngine_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": "discoveryengine_v1alpha_generated_engine_service_get_engine_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient", + "shortName": "EngineServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient.get_engine", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.GetEngine", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", + "shortName": "EngineService" + }, + "shortName": "GetEngine" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.GetEngineRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.Engine", + "shortName": "get_engine" + }, + "description": "Sample for GetEngine", + "file": "discoveryengine_v1alpha_generated_engine_service_get_engine_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_EngineService_GetEngine_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": "discoveryengine_v1alpha_generated_engine_service_get_engine_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient", + "shortName": "EngineServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient.list_engines", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.ListEngines", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", + "shortName": "EngineService" + }, + "shortName": "ListEngines" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.ListEnginesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.services.engine_service.pagers.ListEnginesAsyncPager", + "shortName": "list_engines" + }, + "description": "Sample for ListEngines", + "file": "discoveryengine_v1alpha_generated_engine_service_list_engines_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_EngineService_ListEngines_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": "discoveryengine_v1alpha_generated_engine_service_list_engines_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient", + "shortName": "EngineServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient.list_engines", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.ListEngines", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", + "shortName": "EngineService" + }, + "shortName": "ListEngines" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.ListEnginesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.services.engine_service.pagers.ListEnginesPager", + "shortName": "list_engines" + }, + "description": "Sample for ListEngines", + "file": "discoveryengine_v1alpha_generated_engine_service_list_engines_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_EngineService_ListEngines_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": "discoveryengine_v1alpha_generated_engine_service_list_engines_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient", + "shortName": "EngineServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient.pause_engine", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.PauseEngine", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", + "shortName": "EngineService" + }, + "shortName": "PauseEngine" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.PauseEngineRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.Engine", + "shortName": "pause_engine" + }, + "description": "Sample for PauseEngine", + "file": "discoveryengine_v1alpha_generated_engine_service_pause_engine_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_EngineService_PauseEngine_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": "discoveryengine_v1alpha_generated_engine_service_pause_engine_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient", + "shortName": "EngineServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient.pause_engine", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.PauseEngine", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", + "shortName": "EngineService" + }, + "shortName": "PauseEngine" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.PauseEngineRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.Engine", + "shortName": "pause_engine" + }, + "description": "Sample for PauseEngine", + "file": "discoveryengine_v1alpha_generated_engine_service_pause_engine_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_EngineService_PauseEngine_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": "discoveryengine_v1alpha_generated_engine_service_pause_engine_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient", + "shortName": "EngineServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient.resume_engine", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.ResumeEngine", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", + "shortName": "EngineService" + }, + "shortName": "ResumeEngine" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.ResumeEngineRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.Engine", + "shortName": "resume_engine" + }, + "description": "Sample for ResumeEngine", + "file": "discoveryengine_v1alpha_generated_engine_service_resume_engine_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_EngineService_ResumeEngine_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": "discoveryengine_v1alpha_generated_engine_service_resume_engine_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient", + "shortName": "EngineServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient.resume_engine", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.ResumeEngine", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", + "shortName": "EngineService" + }, + "shortName": "ResumeEngine" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.ResumeEngineRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.Engine", + "shortName": "resume_engine" + }, + "description": "Sample for ResumeEngine", + "file": "discoveryengine_v1alpha_generated_engine_service_resume_engine_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_EngineService_ResumeEngine_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": "discoveryengine_v1alpha_generated_engine_service_resume_engine_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient", + "shortName": "EngineServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient.tune_engine", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.TuneEngine", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", + "shortName": "EngineService" + }, + "shortName": "TuneEngine" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.TuneEngineRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "tune_engine" + }, + "description": "Sample for TuneEngine", + "file": "discoveryengine_v1alpha_generated_engine_service_tune_engine_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_EngineService_TuneEngine_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": "discoveryengine_v1alpha_generated_engine_service_tune_engine_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient", + "shortName": "EngineServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient.tune_engine", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.TuneEngine", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", + "shortName": "EngineService" + }, + "shortName": "TuneEngine" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.TuneEngineRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "tune_engine" + }, + "description": "Sample for TuneEngine", + "file": "discoveryengine_v1alpha_generated_engine_service_tune_engine_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_EngineService_TuneEngine_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": "discoveryengine_v1alpha_generated_engine_service_tune_engine_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient", + "shortName": "EngineServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient.update_engine", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.UpdateEngine", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", + "shortName": "EngineService" + }, + "shortName": "UpdateEngine" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.UpdateEngineRequest" + }, + { + "name": "engine", + "type": "google.cloud.discoveryengine_v1alpha.types.Engine" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.Engine", + "shortName": "update_engine" + }, + "description": "Sample for UpdateEngine", + "file": "discoveryengine_v1alpha_generated_engine_service_update_engine_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_EngineService_UpdateEngine_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": "discoveryengine_v1alpha_generated_engine_service_update_engine_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient", + "shortName": "EngineServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient.update_engine", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.UpdateEngine", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", + "shortName": "EngineService" + }, + "shortName": "UpdateEngine" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.UpdateEngineRequest" + }, + { + "name": "engine", + "type": "google.cloud.discoveryengine_v1alpha.types.Engine" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.Engine", + "shortName": "update_engine" + }, + "description": "Sample for UpdateEngine", + "file": "discoveryengine_v1alpha_generated_engine_service_update_engine_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_EngineService_UpdateEngine_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": "discoveryengine_v1alpha_generated_engine_service_update_engine_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.RecommendationServiceAsyncClient", + "shortName": "RecommendationServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.RecommendationServiceAsyncClient.recommend", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.RecommendationService.Recommend", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.RecommendationService", + "shortName": "RecommendationService" + }, + "shortName": "Recommend" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.RecommendRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.RecommendResponse", + "shortName": "recommend" + }, + "description": "Sample for Recommend", + "file": "discoveryengine_v1alpha_generated_recommendation_service_recommend_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_RecommendationService_Recommend_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1alpha_generated_recommendation_service_recommend_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.RecommendationServiceClient", + "shortName": "RecommendationServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.RecommendationServiceClient.recommend", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.RecommendationService.Recommend", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.RecommendationService", + "shortName": "RecommendationService" + }, + "shortName": "Recommend" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.RecommendRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.RecommendResponse", + "shortName": "recommend" + }, + "description": "Sample for Recommend", + "file": "discoveryengine_v1alpha_generated_recommendation_service_recommend_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_RecommendationService_Recommend_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1alpha_generated_recommendation_service_recommend_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceAsyncClient", + "shortName": "SchemaServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceAsyncClient.create_schema", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService.CreateSchema", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService", + "shortName": "SchemaService" + }, + "shortName": "CreateSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.CreateSchemaRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "schema", + "type": "google.cloud.discoveryengine_v1alpha.types.Schema" + }, + { + "name": "schema_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_schema" + }, + "description": "Sample for CreateSchema", + "file": "discoveryengine_v1alpha_generated_schema_service_create_schema_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_SchemaService_CreateSchema_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": "discoveryengine_v1alpha_generated_schema_service_create_schema_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceClient", + "shortName": "SchemaServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceClient.create_schema", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService.CreateSchema", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService", + "shortName": "SchemaService" + }, + "shortName": "CreateSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.CreateSchemaRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "schema", + "type": "google.cloud.discoveryengine_v1alpha.types.Schema" + }, + { + "name": "schema_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_schema" + }, + "description": "Sample for CreateSchema", + "file": "discoveryengine_v1alpha_generated_schema_service_create_schema_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_SchemaService_CreateSchema_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": "discoveryengine_v1alpha_generated_schema_service_create_schema_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceAsyncClient", + "shortName": "SchemaServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceAsyncClient.delete_schema", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService.DeleteSchema", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService", + "shortName": "SchemaService" + }, + "shortName": "DeleteSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.DeleteSchemaRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_schema" + }, + "description": "Sample for DeleteSchema", + "file": "discoveryengine_v1alpha_generated_schema_service_delete_schema_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_SchemaService_DeleteSchema_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": "discoveryengine_v1alpha_generated_schema_service_delete_schema_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceClient", + "shortName": "SchemaServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceClient.delete_schema", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService.DeleteSchema", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService", + "shortName": "SchemaService" + }, + "shortName": "DeleteSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.DeleteSchemaRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_schema" + }, + "description": "Sample for DeleteSchema", + "file": "discoveryengine_v1alpha_generated_schema_service_delete_schema_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_SchemaService_DeleteSchema_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": "discoveryengine_v1alpha_generated_schema_service_delete_schema_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceAsyncClient", + "shortName": "SchemaServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceAsyncClient.get_schema", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService.GetSchema", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService", + "shortName": "SchemaService" + }, + "shortName": "GetSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.GetSchemaRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.Schema", + "shortName": "get_schema" + }, + "description": "Sample for GetSchema", + "file": "discoveryengine_v1alpha_generated_schema_service_get_schema_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_SchemaService_GetSchema_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": "discoveryengine_v1alpha_generated_schema_service_get_schema_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceClient", + "shortName": "SchemaServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceClient.get_schema", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService.GetSchema", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService", + "shortName": "SchemaService" + }, + "shortName": "GetSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.GetSchemaRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.Schema", + "shortName": "get_schema" + }, + "description": "Sample for GetSchema", + "file": "discoveryengine_v1alpha_generated_schema_service_get_schema_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_SchemaService_GetSchema_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": "discoveryengine_v1alpha_generated_schema_service_get_schema_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceAsyncClient", + "shortName": "SchemaServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceAsyncClient.list_schemas", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService.ListSchemas", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService", + "shortName": "SchemaService" + }, + "shortName": "ListSchemas" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.ListSchemasRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.services.schema_service.pagers.ListSchemasAsyncPager", + "shortName": "list_schemas" + }, + "description": "Sample for ListSchemas", + "file": "discoveryengine_v1alpha_generated_schema_service_list_schemas_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_SchemaService_ListSchemas_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": "discoveryengine_v1alpha_generated_schema_service_list_schemas_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceClient", + "shortName": "SchemaServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceClient.list_schemas", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService.ListSchemas", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService", + "shortName": "SchemaService" + }, + "shortName": "ListSchemas" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.ListSchemasRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.services.schema_service.pagers.ListSchemasPager", + "shortName": "list_schemas" + }, + "description": "Sample for ListSchemas", + "file": "discoveryengine_v1alpha_generated_schema_service_list_schemas_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_SchemaService_ListSchemas_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": "discoveryengine_v1alpha_generated_schema_service_list_schemas_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceAsyncClient", + "shortName": "SchemaServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceAsyncClient.update_schema", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService.UpdateSchema", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService", + "shortName": "SchemaService" + }, + "shortName": "UpdateSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.UpdateSchemaRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_schema" + }, + "description": "Sample for UpdateSchema", + "file": "discoveryengine_v1alpha_generated_schema_service_update_schema_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_SchemaService_UpdateSchema_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1alpha_generated_schema_service_update_schema_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceClient", + "shortName": "SchemaServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceClient.update_schema", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService.UpdateSchema", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService", + "shortName": "SchemaService" + }, + "shortName": "UpdateSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.UpdateSchemaRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_schema" + }, + "description": "Sample for UpdateSchema", + "file": "discoveryengine_v1alpha_generated_schema_service_update_schema_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_SchemaService_UpdateSchema_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1alpha_generated_schema_service_update_schema_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.SearchServiceAsyncClient", + "shortName": "SearchServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.SearchServiceAsyncClient.search", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.SearchService.Search", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.SearchService", + "shortName": "SearchService" + }, + "shortName": "Search" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.SearchRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.services.search_service.pagers.SearchAsyncPager", + "shortName": "search" + }, + "description": "Sample for Search", + "file": "discoveryengine_v1alpha_generated_search_service_search_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_SearchService_Search_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": "discoveryengine_v1alpha_generated_search_service_search_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.SearchServiceClient", + "shortName": "SearchServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.SearchServiceClient.search", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.SearchService.Search", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.SearchService", + "shortName": "SearchService" + }, + "shortName": "Search" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.SearchRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.services.search_service.pagers.SearchPager", + "shortName": "search" + }, + "description": "Sample for Search", + "file": "discoveryengine_v1alpha_generated_search_service_search_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_SearchService_Search_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": "discoveryengine_v1alpha_generated_search_service_search_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.SiteSearchEngineServiceAsyncClient", + "shortName": "SiteSearchEngineServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.SiteSearchEngineServiceAsyncClient.recrawl_uris", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.RecrawlUris", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.SiteSearchEngineService", + "shortName": "SiteSearchEngineService" + }, + "shortName": "RecrawlUris" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.RecrawlUrisRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "recrawl_uris" + }, + "description": "Sample for RecrawlUris", + "file": "discoveryengine_v1alpha_generated_site_search_engine_service_recrawl_uris_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_SiteSearchEngineService_RecrawlUris_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": "discoveryengine_v1alpha_generated_site_search_engine_service_recrawl_uris_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.SiteSearchEngineServiceClient", + "shortName": "SiteSearchEngineServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.SiteSearchEngineServiceClient.recrawl_uris", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.RecrawlUris", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.SiteSearchEngineService", + "shortName": "SiteSearchEngineService" + }, + "shortName": "RecrawlUris" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.RecrawlUrisRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "recrawl_uris" + }, + "description": "Sample for RecrawlUris", + "file": "discoveryengine_v1alpha_generated_site_search_engine_service_recrawl_uris_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_SiteSearchEngineService_RecrawlUris_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": "discoveryengine_v1alpha_generated_site_search_engine_service_recrawl_uris_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.UserEventServiceAsyncClient.collect_user_event", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.UserEventService.CollectUserEvent", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "CollectUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.CollectUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api.httpbody_pb2.HttpBody", + "shortName": "collect_user_event" + }, + "description": "Sample for CollectUserEvent", + "file": "discoveryengine_v1alpha_generated_user_event_service_collect_user_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_UserEventService_CollectUserEvent_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": "discoveryengine_v1alpha_generated_user_event_service_collect_user_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.UserEventServiceClient.collect_user_event", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.UserEventService.CollectUserEvent", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "CollectUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.CollectUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api.httpbody_pb2.HttpBody", + "shortName": "collect_user_event" + }, + "description": "Sample for CollectUserEvent", + "file": "discoveryengine_v1alpha_generated_user_event_service_collect_user_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_UserEventService_CollectUserEvent_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": "discoveryengine_v1alpha_generated_user_event_service_collect_user_event_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.UserEventServiceAsyncClient.import_user_events", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.UserEventService.ImportUserEvents", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "ImportUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.ImportUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "import_user_events" + }, + "description": "Sample for ImportUserEvents", + "file": "discoveryengine_v1alpha_generated_user_event_service_import_user_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_UserEventService_ImportUserEvents_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": "discoveryengine_v1alpha_generated_user_event_service_import_user_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.UserEventServiceClient.import_user_events", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.UserEventService.ImportUserEvents", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "ImportUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.ImportUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "import_user_events" + }, + "description": "Sample for ImportUserEvents", + "file": "discoveryengine_v1alpha_generated_user_event_service_import_user_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_UserEventService_ImportUserEvents_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": "discoveryengine_v1alpha_generated_user_event_service_import_user_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.UserEventServiceAsyncClient.purge_user_events", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.UserEventService.PurgeUserEvents", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "PurgeUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.PurgeUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "purge_user_events" + }, + "description": "Sample for PurgeUserEvents", + "file": "discoveryengine_v1alpha_generated_user_event_service_purge_user_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_UserEventService_PurgeUserEvents_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": "discoveryengine_v1alpha_generated_user_event_service_purge_user_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.UserEventServiceClient.purge_user_events", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.UserEventService.PurgeUserEvents", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "PurgeUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.PurgeUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "purge_user_events" + }, + "description": "Sample for PurgeUserEvents", + "file": "discoveryengine_v1alpha_generated_user_event_service_purge_user_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_UserEventService_PurgeUserEvents_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": "discoveryengine_v1alpha_generated_user_event_service_purge_user_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.UserEventServiceAsyncClient.write_user_event", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.UserEventService.WriteUserEvent", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "WriteUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.WriteUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.UserEvent", + "shortName": "write_user_event" + }, + "description": "Sample for WriteUserEvent", + "file": "discoveryengine_v1alpha_generated_user_event_service_write_user_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_UserEventService_WriteUserEvent_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": "discoveryengine_v1alpha_generated_user_event_service_write_user_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.UserEventServiceClient.write_user_event", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.UserEventService.WriteUserEvent", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "WriteUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.WriteUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.UserEvent", + "shortName": "write_user_event" + }, + "description": "Sample for WriteUserEvent", + "file": "discoveryengine_v1alpha_generated_user_event_service_write_user_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_UserEventService_WriteUserEvent_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": "discoveryengine_v1alpha_generated_user_event_service_write_user_event_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/scripts/fixup_discoveryengine_v1alpha_keywords.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/scripts/fixup_discoveryengine_v1alpha_keywords.py new file mode 100644 index 000000000000..36332ca4a1e0 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/scripts/fixup_discoveryengine_v1alpha_keywords.py @@ -0,0 +1,214 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class discoveryengineCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'collect_user_event': ('parent', 'user_event', 'uri', 'ets', ), + 'complete_query': ('data_store', 'query', 'query_model', 'user_pseudo_id', 'include_tail_suggestions', ), + 'converse_conversation': ('name', 'query', 'serving_config', 'conversation', 'safe_search', 'user_labels', 'summary_spec', ), + 'create_conversation': ('parent', 'conversation', ), + 'create_data_store': ('parent', 'data_store', 'data_store_id', 'create_advanced_site_search', ), + 'create_document': ('parent', 'document', 'document_id', ), + 'create_engine': ('parent', 'engine', 'engine_id', ), + 'create_schema': ('parent', 'schema', 'schema_id', ), + 'delete_conversation': ('name', ), + 'delete_data_store': ('name', ), + 'delete_document': ('name', ), + 'delete_engine': ('name', ), + 'delete_schema': ('name', ), + 'get_conversation': ('name', ), + 'get_data_store': ('name', ), + 'get_document': ('name', ), + 'get_engine': ('name', ), + 'get_schema': ('name', ), + 'import_documents': ('parent', 'inline_source', 'gcs_source', 'bigquery_source', 'error_config', 'reconciliation_mode', 'auto_generate_ids', 'id_field', ), + 'import_user_events': ('parent', 'inline_source', 'gcs_source', 'bigquery_source', 'error_config', ), + 'list_conversations': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_data_stores': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_documents': ('parent', 'page_size', 'page_token', ), + 'list_engines': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_schemas': ('parent', 'page_size', 'page_token', ), + 'pause_engine': ('name', ), + 'purge_documents': ('parent', 'filter', 'force', ), + 'purge_user_events': ('parent', 'filter', 'force', ), + 'recommend': ('serving_config', 'user_event', 'page_size', 'filter', 'validate_only', 'params', 'user_labels', ), + 'recrawl_uris': ('site_search_engine', 'uris', ), + 'resume_engine': ('name', ), + 'search': ('serving_config', 'branch', 'query', 'image_query', 'page_size', 'page_token', 'offset', 'filter', 'order_by', 'user_info', 'facet_specs', 'boost_spec', 'params', 'query_expansion_spec', 'spell_correction_spec', 'user_pseudo_id', 'content_search_spec', 'embedding_spec', 'ranking_expression', 'safe_search', 'user_labels', ), + 'tune_engine': ('name', ), + 'update_conversation': ('conversation', 'update_mask', ), + 'update_data_store': ('data_store', 'update_mask', ), + 'update_document': ('document', 'allow_missing', ), + 'update_engine': ('engine', 'update_mask', ), + 'update_schema': ('schema', 'allow_missing', ), + 'write_user_event': ('parent', 'user_event', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=discoveryengineCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the discoveryengine client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/setup.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/setup.py new file mode 100644 index 000000000000..513896d68575 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/setup.py @@ -0,0 +1,90 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-discoveryengine' + + +description = "Google Cloud Discoveryengine API client library" + +version = {} +with open(os.path.join(package_root, 'google/cloud/discoveryengine/gapic_version.py')) as fp: + exec(fp.read(), version) +version = version["__version__"] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + "proto-plus >= 1.22.0, <2.0.0dev", + "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", + "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +url = "https://github.com/googleapis/python-discoveryengine" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.PEP420PackageFinder.find() + if package.startswith("google") +] + +namespaces = ["google", "google.cloud"] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + namespace_packages=namespaces, + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.10.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.11.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.12.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.7.txt new file mode 100644 index 000000000000..6c44adfea7ee --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.7.txt @@ -0,0 +1,9 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.0 +proto-plus==1.22.0 +protobuf==3.19.5 diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.8.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.9.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/__init__.py new file mode 100644 index 000000000000..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/__init__.py new file mode 100644 index 000000000000..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/__init__.py new file mode 100644 index 000000000000..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_completion_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_completion_service.py new file mode 100644 index 000000000000..1db2af92f704 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_completion_service.py @@ -0,0 +1,1920 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.discoveryengine_v1alpha.services.completion_service import CompletionServiceAsyncClient +from google.cloud.discoveryengine_v1alpha.services.completion_service import CompletionServiceClient +from google.cloud.discoveryengine_v1alpha.services.completion_service import transports +from google.cloud.discoveryengine_v1alpha.types import completion_service +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert CompletionServiceClient._get_default_mtls_endpoint(None) is None + assert CompletionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (CompletionServiceClient, "grpc"), + (CompletionServiceAsyncClient, "grpc_asyncio"), + (CompletionServiceClient, "rest"), +]) +def test_completion_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.CompletionServiceGrpcTransport, "grpc"), + (transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.CompletionServiceRestTransport, "rest"), +]) +def test_completion_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", [ + (CompletionServiceClient, "grpc"), + (CompletionServiceAsyncClient, "grpc_asyncio"), + (CompletionServiceClient, "rest"), +]) +def test_completion_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +def test_completion_service_client_get_transport_class(): + transport = CompletionServiceClient.get_transport_class() + available_transports = [ + transports.CompletionServiceGrpcTransport, + transports.CompletionServiceRestTransport, + ] + assert transport in available_transports + + transport = CompletionServiceClient.get_transport_class("grpc") + assert transport == transports.CompletionServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (CompletionServiceClient, transports.CompletionServiceRestTransport, "rest"), +]) +@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) +@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) +def test_completion_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(CompletionServiceClient, '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(CompletionServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "true"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "false"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (CompletionServiceClient, transports.CompletionServiceRestTransport, "rest", "true"), + (CompletionServiceClient, transports.CompletionServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) +@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_completion_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 + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + CompletionServiceClient, CompletionServiceAsyncClient +]) +@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) +@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) +def test_completion_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (CompletionServiceClient, transports.CompletionServiceRestTransport, "rest"), +]) +def test_completion_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, + 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", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (CompletionServiceClient, transports.CompletionServiceRestTransport, "rest", None), +]) +def test_completion_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, + scopes=None, + client_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_completion_service_client_client_options_from_dict(): + with mock.patch('google.cloud.discoveryengine_v1alpha.services.completion_service.transports.CompletionServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = CompletionServiceClient( + 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", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_completion_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, + scopes=None, + client_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + completion_service.CompleteQueryRequest, + dict, +]) +def test_complete_query(request_type, transport: str = 'grpc'): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = completion_service.CompleteQueryResponse( + tail_match_triggered=True, + ) + response = client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == completion_service.CompleteQueryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, completion_service.CompleteQueryResponse) + assert response.tail_match_triggered is True + + +def test_complete_query_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + client.complete_query() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == completion_service.CompleteQueryRequest() + +@pytest.mark.asyncio +async def test_complete_query_async(transport: str = 'grpc_asyncio', request_type=completion_service.CompleteQueryRequest): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse( + tail_match_triggered=True, + )) + response = await client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == completion_service.CompleteQueryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, completion_service.CompleteQueryResponse) + assert response.tail_match_triggered is True + + +@pytest.mark.asyncio +async def test_complete_query_async_from_dict(): + await test_complete_query_async(request_type=dict) + + +def test_complete_query_field_headers(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = completion_service.CompleteQueryRequest() + + request.data_store = 'data_store_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + call.return_value = completion_service.CompleteQueryResponse() + client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'data_store=data_store_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_complete_query_field_headers_async(): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = completion_service.CompleteQueryRequest() + + request.data_store = 'data_store_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse()) + await client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'data_store=data_store_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + completion_service.CompleteQueryRequest, + dict, +]) +def test_complete_query_rest(request_type): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'data_store': 'projects/sample1/locations/sample2/dataStores/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 = completion_service.CompleteQueryResponse( + tail_match_triggered=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = completion_service.CompleteQueryResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.complete_query(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, completion_service.CompleteQueryResponse) + assert response.tail_match_triggered is True + + +def test_complete_query_rest_required_fields(request_type=completion_service.CompleteQueryRequest): + transport_class = transports.CompletionServiceRestTransport + + request_init = {} + request_init["data_store"] = "" + request_init["query"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "query" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).complete_query._get_unset_required_fields(jsonified_request) + 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["dataStore"] = 'data_store_value' + jsonified_request["query"] = 'query_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).complete_query._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("include_tail_suggestions", "query", "query_model", "user_pseudo_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "dataStore" in jsonified_request + assert jsonified_request["dataStore"] == 'data_store_value' + assert "query" in jsonified_request + assert jsonified_request["query"] == 'query_value' + + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = completion_service.CompleteQueryResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = completion_service.CompleteQueryResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.complete_query(request) + + expected_params = [ + ( + "query", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_complete_query_rest_unset_required_fields(): + transport = transports.CompletionServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.complete_query._get_unset_required_fields({}) + assert set(unset_fields) == (set(("includeTailSuggestions", "query", "queryModel", "userPseudoId", )) & set(("dataStore", "query", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_complete_query_rest_interceptors(null_interceptor): + transport = transports.CompletionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.CompletionServiceRestInterceptor(), + ) + client = CompletionServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.CompletionServiceRestInterceptor, "post_complete_query") as post, \ + mock.patch.object(transports.CompletionServiceRestInterceptor, "pre_complete_query") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = completion_service.CompleteQueryRequest.pb(completion_service.CompleteQueryRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = completion_service.CompleteQueryResponse.to_json(completion_service.CompleteQueryResponse()) + + request = completion_service.CompleteQueryRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = completion_service.CompleteQueryResponse() + + client.complete_query(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_complete_query_rest_bad_request(transport: str = 'rest', request_type=completion_service.CompleteQueryRequest): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'data_store': 'projects/sample1/locations/sample2/dataStores/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.complete_query(request) + + +def test_complete_query_rest_error(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CompletionServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CompletionServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, + transports.CompletionServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = CompletionServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CompletionServiceGrpcTransport, + ) + +def test_completion_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CompletionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_completion_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.discoveryengine_v1alpha.services.completion_service.transports.CompletionServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.CompletionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'complete_query', + 'get_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_completion_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.discoveryengine_v1alpha.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CompletionServiceTransport( + 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_completion_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.discoveryengine_v1alpha.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CompletionServiceTransport() + adc.assert_called_once() + + +def test_completion_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) + CompletionServiceClient() + 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.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, + ], +) +def test_completion_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.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, + transports.CompletionServiceRestTransport, + ], +) +def test_completion_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.CompletionServiceGrpcTransport, grpc_helpers), + (transports.CompletionServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_completion_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) +def test_completion_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_completion_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.CompletionServiceRestTransport ( + 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_completion_service_host_no_port(transport_name): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_completion_service_host_with_port(transport_name): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_completion_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = CompletionServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = CompletionServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.complete_query._session + session2 = client2.transport.complete_query._session + assert session1 != session2 +def test_completion_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CompletionServiceGrpcTransport( + 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_completion_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CompletionServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) +def test_completion_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.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) +def test_completion_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_data_store_path(): + project = "squid" + location = "clam" + data_store = "whelk" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) + actual = CompletionServiceClient.data_store_path(project, location, data_store) + assert expected == actual + + +def test_parse_data_store_path(): + expected = { + "project": "octopus", + "location": "oyster", + "data_store": "nudibranch", + } + path = CompletionServiceClient.data_store_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_data_store_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = CompletionServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = CompletionServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = CompletionServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = CompletionServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = CompletionServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = CompletionServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = CompletionServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = CompletionServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = CompletionServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = CompletionServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.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.CompletionServiceTransport, '_prep_wrapped_messages') as prep: + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = CompletionServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_get_operation(transport: str = "grpc"): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc"): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = CompletionServiceClient( + 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 = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc"): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = CompletionServiceClient( + 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 = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = CompletionServiceClient( + 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", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_conversational_search_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_conversational_search_service.py new file mode 100644 index 000000000000..40e254d2a90f --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_conversational_search_service.py @@ -0,0 +1,4908 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.discoveryengine_v1alpha.services.conversational_search_service import ConversationalSearchServiceAsyncClient +from google.cloud.discoveryengine_v1alpha.services.conversational_search_service import ConversationalSearchServiceClient +from google.cloud.discoveryengine_v1alpha.services.conversational_search_service import pagers +from google.cloud.discoveryengine_v1alpha.services.conversational_search_service import transports +from google.cloud.discoveryengine_v1alpha.types import conversation +from google.cloud.discoveryengine_v1alpha.types import conversation as gcd_conversation +from google.cloud.discoveryengine_v1alpha.types import conversational_search_service +from google.cloud.discoveryengine_v1alpha.types import search_service +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ConversationalSearchServiceClient._get_default_mtls_endpoint(None) is None + assert ConversationalSearchServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ConversationalSearchServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ConversationalSearchServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ConversationalSearchServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ConversationalSearchServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ConversationalSearchServiceClient, "grpc"), + (ConversationalSearchServiceAsyncClient, "grpc_asyncio"), + (ConversationalSearchServiceClient, "rest"), +]) +def test_conversational_search_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ConversationalSearchServiceGrpcTransport, "grpc"), + (transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ConversationalSearchServiceRestTransport, "rest"), +]) +def test_conversational_search_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", [ + (ConversationalSearchServiceClient, "grpc"), + (ConversationalSearchServiceAsyncClient, "grpc_asyncio"), + (ConversationalSearchServiceClient, "rest"), +]) +def test_conversational_search_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +def test_conversational_search_service_client_get_transport_class(): + transport = ConversationalSearchServiceClient.get_transport_class() + available_transports = [ + transports.ConversationalSearchServiceGrpcTransport, + transports.ConversationalSearchServiceRestTransport, + ] + assert transport in available_transports + + transport = ConversationalSearchServiceClient.get_transport_class("grpc") + assert transport == transports.ConversationalSearchServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport, "grpc"), + (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (ConversationalSearchServiceClient, transports.ConversationalSearchServiceRestTransport, "rest"), +]) +@mock.patch.object(ConversationalSearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationalSearchServiceClient)) +@mock.patch.object(ConversationalSearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationalSearchServiceAsyncClient)) +def test_conversational_search_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(ConversationalSearchServiceClient, '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(ConversationalSearchServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport, "grpc", "true"), + (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport, "grpc", "false"), + (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (ConversationalSearchServiceClient, transports.ConversationalSearchServiceRestTransport, "rest", "true"), + (ConversationalSearchServiceClient, transports.ConversationalSearchServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(ConversationalSearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationalSearchServiceClient)) +@mock.patch.object(ConversationalSearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationalSearchServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_conversational_search_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 + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + ConversationalSearchServiceClient, ConversationalSearchServiceAsyncClient +]) +@mock.patch.object(ConversationalSearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationalSearchServiceClient)) +@mock.patch.object(ConversationalSearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationalSearchServiceAsyncClient)) +def test_conversational_search_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport, "grpc"), + (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (ConversationalSearchServiceClient, transports.ConversationalSearchServiceRestTransport, "rest"), +]) +def test_conversational_search_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, + 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", [ + (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport, "grpc", grpc_helpers), + (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (ConversationalSearchServiceClient, transports.ConversationalSearchServiceRestTransport, "rest", None), +]) +def test_conversational_search_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, + scopes=None, + client_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_conversational_search_service_client_client_options_from_dict(): + with mock.patch('google.cloud.discoveryengine_v1alpha.services.conversational_search_service.transports.ConversationalSearchServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ConversationalSearchServiceClient( + 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", [ + (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport, "grpc", grpc_helpers), + (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_conversational_search_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, + scopes=None, + client_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + conversational_search_service.ConverseConversationRequest, + dict, +]) +def test_converse_conversation(request_type, transport: str = 'grpc'): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.converse_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversational_search_service.ConverseConversationResponse( + related_questions=['related_questions_value'], + ) + response = client.converse_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] == conversational_search_service.ConverseConversationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, conversational_search_service.ConverseConversationResponse) + assert response.related_questions == ['related_questions_value'] + + +def test_converse_conversation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.converse_conversation), + '__call__') as call: + client.converse_conversation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversational_search_service.ConverseConversationRequest() + +@pytest.mark.asyncio +async def test_converse_conversation_async(transport: str = 'grpc_asyncio', request_type=conversational_search_service.ConverseConversationRequest): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.converse_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversational_search_service.ConverseConversationResponse( + related_questions=['related_questions_value'], + )) + response = await client.converse_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == conversational_search_service.ConverseConversationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, conversational_search_service.ConverseConversationResponse) + assert response.related_questions == ['related_questions_value'] + + +@pytest.mark.asyncio +async def test_converse_conversation_async_from_dict(): + await test_converse_conversation_async(request_type=dict) + + +def test_converse_conversation_field_headers(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversational_search_service.ConverseConversationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.converse_conversation), + '__call__') as call: + call.return_value = conversational_search_service.ConverseConversationResponse() + client.converse_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', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_converse_conversation_field_headers_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversational_search_service.ConverseConversationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.converse_conversation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversational_search_service.ConverseConversationResponse()) + await client.converse_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', + 'name=name_value', + ) in kw['metadata'] + + +def test_converse_conversation_flattened(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.converse_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversational_search_service.ConverseConversationResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.converse_conversation( + name='name_value', + query=conversation.TextInput(input='input_value'), + ) + + # Establish that the 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].query + mock_val = conversation.TextInput(input='input_value') + assert arg == mock_val + + +def test_converse_conversation_flattened_error(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.converse_conversation( + conversational_search_service.ConverseConversationRequest(), + name='name_value', + query=conversation.TextInput(input='input_value'), + ) + +@pytest.mark.asyncio +async def test_converse_conversation_flattened_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.converse_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversational_search_service.ConverseConversationResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversational_search_service.ConverseConversationResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.converse_conversation( + name='name_value', + query=conversation.TextInput(input='input_value'), + ) + + # Establish that 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].query + mock_val = conversation.TextInput(input='input_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_converse_conversation_flattened_error_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.converse_conversation( + conversational_search_service.ConverseConversationRequest(), + name='name_value', + query=conversation.TextInput(input='input_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + conversational_search_service.CreateConversationRequest, + dict, +]) +def test_create_conversation(request_type, transport: str = 'grpc'): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_conversation.Conversation( + name='name_value', + state=gcd_conversation.Conversation.State.IN_PROGRESS, + user_pseudo_id='user_pseudo_id_value', + ) + response = client.create_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] == conversational_search_service.CreateConversationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_conversation.Conversation) + assert response.name == 'name_value' + assert response.state == gcd_conversation.Conversation.State.IN_PROGRESS + assert response.user_pseudo_id == 'user_pseudo_id_value' + + +def test_create_conversation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversation), + '__call__') as call: + client.create_conversation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversational_search_service.CreateConversationRequest() + +@pytest.mark.asyncio +async def test_create_conversation_async(transport: str = 'grpc_asyncio', request_type=conversational_search_service.CreateConversationRequest): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation.Conversation( + name='name_value', + state=gcd_conversation.Conversation.State.IN_PROGRESS, + user_pseudo_id='user_pseudo_id_value', + )) + response = await client.create_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == conversational_search_service.CreateConversationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_conversation.Conversation) + assert response.name == 'name_value' + assert response.state == gcd_conversation.Conversation.State.IN_PROGRESS + assert response.user_pseudo_id == 'user_pseudo_id_value' + + +@pytest.mark.asyncio +async def test_create_conversation_async_from_dict(): + await test_create_conversation_async(request_type=dict) + + +def test_create_conversation_field_headers(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversational_search_service.CreateConversationRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversation), + '__call__') as call: + call.return_value = gcd_conversation.Conversation() + client.create_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', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_conversation_field_headers_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversational_search_service.CreateConversationRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation.Conversation()) + await client.create_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', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_conversation_flattened(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_conversation.Conversation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_conversation( + parent='parent_value', + conversation=gcd_conversation.Conversation(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].conversation + mock_val = gcd_conversation.Conversation(name='name_value') + assert arg == mock_val + + +def test_create_conversation_flattened_error(): + client = ConversationalSearchServiceClient( + credentials=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_conversation( + conversational_search_service.CreateConversationRequest(), + parent='parent_value', + conversation=gcd_conversation.Conversation(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_conversation_flattened_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_conversation.Conversation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation.Conversation()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_conversation( + parent='parent_value', + conversation=gcd_conversation.Conversation(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].conversation + mock_val = gcd_conversation.Conversation(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_conversation_flattened_error_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_conversation( + conversational_search_service.CreateConversationRequest(), + parent='parent_value', + conversation=gcd_conversation.Conversation(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + conversational_search_service.DeleteConversationRequest, + dict, +]) +def test_delete_conversation(request_type, transport: str = 'grpc'): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_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] == conversational_search_service.DeleteConversationRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_conversation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversation), + '__call__') as call: + client.delete_conversation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversational_search_service.DeleteConversationRequest() + +@pytest.mark.asyncio +async def test_delete_conversation_async(transport: str = 'grpc_asyncio', request_type=conversational_search_service.DeleteConversationRequest): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == conversational_search_service.DeleteConversationRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_conversation_async_from_dict(): + await test_delete_conversation_async(request_type=dict) + + +def test_delete_conversation_field_headers(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversational_search_service.DeleteConversationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversation), + '__call__') as call: + call.return_value = None + client.delete_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', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_conversation_field_headers_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversational_search_service.DeleteConversationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_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', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_conversation_flattened(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, 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 = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_conversation( + 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_conversation_flattened_error(): + client = ConversationalSearchServiceClient( + credentials=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_conversation( + conversational_search_service.DeleteConversationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_conversation_flattened_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, 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 = 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_conversation( + 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_conversation_flattened_error_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_conversation( + conversational_search_service.DeleteConversationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + conversational_search_service.UpdateConversationRequest, + dict, +]) +def test_update_conversation(request_type, transport: str = 'grpc'): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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 = gcd_conversation.Conversation( + name='name_value', + state=gcd_conversation.Conversation.State.IN_PROGRESS, + user_pseudo_id='user_pseudo_id_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] + assert args[0] == conversational_search_service.UpdateConversationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_conversation.Conversation) + assert response.name == 'name_value' + assert response.state == gcd_conversation.Conversation.State.IN_PROGRESS + assert response.user_pseudo_id == 'user_pseudo_id_value' + + +def test_update_conversation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversation), + '__call__') as call: + client.update_conversation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversational_search_service.UpdateConversationRequest() + +@pytest.mark.asyncio +async def test_update_conversation_async(transport: str = 'grpc_asyncio', request_type=conversational_search_service.UpdateConversationRequest): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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(gcd_conversation.Conversation( + name='name_value', + state=gcd_conversation.Conversation.State.IN_PROGRESS, + user_pseudo_id='user_pseudo_id_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] + assert args[0] == conversational_search_service.UpdateConversationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_conversation.Conversation) + assert response.name == 'name_value' + assert response.state == gcd_conversation.Conversation.State.IN_PROGRESS + assert response.user_pseudo_id == 'user_pseudo_id_value' + + +@pytest.mark.asyncio +async def test_update_conversation_async_from_dict(): + await test_update_conversation_async(request_type=dict) + + +def test_update_conversation_field_headers(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversational_search_service.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 = gcd_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 = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversational_search_service.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(gcd_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 = ConversationalSearchServiceClient( + 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 = gcd_conversation.Conversation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_conversation( + conversation=gcd_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 = gcd_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 = ConversationalSearchServiceClient( + credentials=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( + conversational_search_service.UpdateConversationRequest(), + conversation=gcd_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 = ConversationalSearchServiceAsyncClient( + 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 = gcd_conversation.Conversation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_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=gcd_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 = gcd_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 = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_conversation( + conversational_search_service.UpdateConversationRequest(), + conversation=gcd_conversation.Conversation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + conversational_search_service.GetConversationRequest, + dict, +]) +def test_get_conversation(request_type, transport: str = 'grpc'): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.Conversation( + name='name_value', + state=conversation.Conversation.State.IN_PROGRESS, + user_pseudo_id='user_pseudo_id_value', + ) + response = client.get_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] == conversational_search_service.GetConversationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, conversation.Conversation) + assert response.name == 'name_value' + assert response.state == conversation.Conversation.State.IN_PROGRESS + assert response.user_pseudo_id == 'user_pseudo_id_value' + + +def test_get_conversation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversation), + '__call__') as call: + client.get_conversation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversational_search_service.GetConversationRequest() + +@pytest.mark.asyncio +async def test_get_conversation_async(transport: str = 'grpc_asyncio', request_type=conversational_search_service.GetConversationRequest): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation( + name='name_value', + state=conversation.Conversation.State.IN_PROGRESS, + user_pseudo_id='user_pseudo_id_value', + )) + response = await client.get_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == conversational_search_service.GetConversationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, conversation.Conversation) + assert response.name == 'name_value' + assert response.state == conversation.Conversation.State.IN_PROGRESS + assert response.user_pseudo_id == 'user_pseudo_id_value' + + +@pytest.mark.asyncio +async def test_get_conversation_async_from_dict(): + await test_get_conversation_async(request_type=dict) + + +def test_get_conversation_field_headers(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversational_search_service.GetConversationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversation), + '__call__') as call: + call.return_value = conversation.Conversation() + client.get_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', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_conversation_field_headers_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversational_search_service.GetConversationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation()) + await client.get_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', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_conversation_flattened(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.Conversation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_conversation( + 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_conversation_flattened_error(): + client = ConversationalSearchServiceClient( + credentials=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_conversation( + conversational_search_service.GetConversationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_conversation_flattened_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.Conversation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_conversation( + 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_conversation_flattened_error_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_conversation( + conversational_search_service.GetConversationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + conversational_search_service.ListConversationsRequest, + dict, +]) +def test_list_conversations(request_type, transport: str = 'grpc'): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversational_search_service.ListConversationsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_conversations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == conversational_search_service.ListConversationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConversationsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_conversations_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + '__call__') as call: + client.list_conversations() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversational_search_service.ListConversationsRequest() + +@pytest.mark.asyncio +async def test_list_conversations_async(transport: str = 'grpc_asyncio', request_type=conversational_search_service.ListConversationsRequest): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversational_search_service.ListConversationsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_conversations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == conversational_search_service.ListConversationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConversationsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_conversations_async_from_dict(): + await test_list_conversations_async(request_type=dict) + + +def test_list_conversations_field_headers(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversational_search_service.ListConversationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + '__call__') as call: + call.return_value = conversational_search_service.ListConversationsResponse() + client.list_conversations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_conversations_field_headers_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversational_search_service.ListConversationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversational_search_service.ListConversationsResponse()) + await client.list_conversations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_conversations_flattened(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversational_search_service.ListConversationsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_conversations( + 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_conversations_flattened_error(): + client = ConversationalSearchServiceClient( + credentials=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_conversations( + conversational_search_service.ListConversationsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_conversations_flattened_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversational_search_service.ListConversationsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversational_search_service.ListConversationsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_conversations( + 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_conversations_flattened_error_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_conversations( + conversational_search_service.ListConversationsRequest(), + parent='parent_value', + ) + + +def test_list_conversations_pager(transport_name: str = "grpc"): + client = ConversationalSearchServiceClient( + 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_conversations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + conversation.Conversation(), + ], + next_page_token='abc', + ), + conversational_search_service.ListConversationsResponse( + conversations=[], + next_page_token='def', + ), + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + ], + next_page_token='ghi', + ), + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_conversations(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, conversation.Conversation) + for i in results) +def test_list_conversations_pages(transport_name: str = "grpc"): + client = ConversationalSearchServiceClient( + 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_conversations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + conversation.Conversation(), + ], + next_page_token='abc', + ), + conversational_search_service.ListConversationsResponse( + conversations=[], + next_page_token='def', + ), + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + ], + next_page_token='ghi', + ), + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + ], + ), + RuntimeError, + ) + pages = list(client.list_conversations(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_conversations_async_pager(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + conversation.Conversation(), + ], + next_page_token='abc', + ), + conversational_search_service.ListConversationsResponse( + conversations=[], + next_page_token='def', + ), + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + ], + next_page_token='ghi', + ), + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_conversations(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, conversation.Conversation) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_conversations_async_pages(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + conversation.Conversation(), + ], + next_page_token='abc', + ), + conversational_search_service.ListConversationsResponse( + conversations=[], + next_page_token='def', + ), + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + ], + next_page_token='ghi', + ), + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_conversations(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", [ + conversational_search_service.ConverseConversationRequest, + dict, +]) +def test_converse_conversation_rest(request_type): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/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 = conversational_search_service.ConverseConversationResponse( + related_questions=['related_questions_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 = conversational_search_service.ConverseConversationResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.converse_conversation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, conversational_search_service.ConverseConversationResponse) + assert response.related_questions == ['related_questions_value'] + + +def test_converse_conversation_rest_required_fields(request_type=conversational_search_service.ConverseConversationRequest): + transport_class = transports.ConversationalSearchServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).converse_conversation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).converse_conversation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = conversational_search_service.ConverseConversationResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = conversational_search_service.ConverseConversationResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.converse_conversation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_converse_conversation_rest_unset_required_fields(): + transport = transports.ConversationalSearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.converse_conversation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "query", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_converse_conversation_rest_interceptors(null_interceptor): + transport = transports.ConversationalSearchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConversationalSearchServiceRestInterceptor(), + ) + client = ConversationalSearchServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "post_converse_conversation") as post, \ + mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "pre_converse_conversation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = conversational_search_service.ConverseConversationRequest.pb(conversational_search_service.ConverseConversationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = conversational_search_service.ConverseConversationResponse.to_json(conversational_search_service.ConverseConversationResponse()) + + request = conversational_search_service.ConverseConversationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = conversational_search_service.ConverseConversationResponse() + + client.converse_conversation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_converse_conversation_rest_bad_request(transport: str = 'rest', request_type=conversational_search_service.ConverseConversationRequest): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.converse_conversation(request) + + +def test_converse_conversation_rest_flattened(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = conversational_search_service.ConverseConversationResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + query=conversation.TextInput(input='input_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 = conversational_search_service.ConverseConversationResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.converse_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/{name=projects/*/locations/*/dataStores/*/conversations/*}:converse" % client.transport._host, args[1]) + + +def test_converse_conversation_rest_flattened_error(transport: str = 'rest'): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.converse_conversation( + conversational_search_service.ConverseConversationRequest(), + name='name_value', + query=conversation.TextInput(input='input_value'), + ) + + +def test_converse_conversation_rest_error(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + conversational_search_service.CreateConversationRequest, + dict, +]) +def test_create_conversation_rest(request_type): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + request_init["conversation"] = {'name': 'name_value', 'state': 1, 'user_pseudo_id': 'user_pseudo_id_value', 'messages': [{'user_input': {'input': 'input_value', 'context': {'context_documents': ['context_documents_value1', 'context_documents_value2'], 'active_document': 'active_document_value'}}, 'reply': {'reply': 'reply_value', 'references': [{'uri': 'uri_value', 'anchor_text': 'anchor_text_value', 'start': 558, 'end': 311}], 'summary': {'summary_text': 'summary_text_value', 'summary_skipped_reasons': [1], 'safety_attributes': {'categories': ['categories_value1', 'categories_value2'], 'scores': [0.656, 0.657]}}}, 'create_time': {'seconds': 751, 'nanos': 543}}], 'start_time': {}, 'end_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 = conversational_search_service.CreateConversationRequest.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 = gcd_conversation.Conversation( + name='name_value', + state=gcd_conversation.Conversation.State.IN_PROGRESS, + user_pseudo_id='user_pseudo_id_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 = gcd_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 + response = client.create_conversation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_conversation.Conversation) + assert response.name == 'name_value' + assert response.state == gcd_conversation.Conversation.State.IN_PROGRESS + assert response.user_pseudo_id == 'user_pseudo_id_value' + + +def test_create_conversation_rest_required_fields(request_type=conversational_search_service.CreateConversationRequest): + transport_class = transports.ConversationalSearchServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_conversation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_conversation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcd_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': "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 = gcd_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 + + response = client.create_conversation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_conversation_rest_unset_required_fields(): + transport = transports.ConversationalSearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_conversation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "conversation", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_conversation_rest_interceptors(null_interceptor): + transport = transports.ConversationalSearchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConversationalSearchServiceRestInterceptor(), + ) + client = ConversationalSearchServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "post_create_conversation") as post, \ + mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "pre_create_conversation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = conversational_search_service.CreateConversationRequest.pb(conversational_search_service.CreateConversationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcd_conversation.Conversation.to_json(gcd_conversation.Conversation()) + + request = conversational_search_service.CreateConversationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcd_conversation.Conversation() + + client.create_conversation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_conversation_rest_bad_request(transport: str = 'rest', request_type=conversational_search_service.CreateConversationRequest): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_conversation(request) + + +def test_create_conversation_rest_flattened(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcd_conversation.Conversation() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + conversation=gcd_conversation.Conversation(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 = gcd_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 + + client.create_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/{parent=projects/*/locations/*/dataStores/*}/conversations" % client.transport._host, args[1]) + + +def test_create_conversation_rest_flattened_error(transport: str = 'rest'): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.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_conversation( + conversational_search_service.CreateConversationRequest(), + parent='parent_value', + conversation=gcd_conversation.Conversation(name='name_value'), + ) + + +def test_create_conversation_rest_error(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + conversational_search_service.DeleteConversationRequest, + dict, +]) +def test_delete_conversation_rest(request_type): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_conversation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_conversation_rest_required_fields(request_type=conversational_search_service.DeleteConversationRequest): + transport_class = transports.ConversationalSearchServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_conversation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_conversation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = ConversationalSearchServiceClient( + 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 + + response = client.delete_conversation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_conversation_rest_unset_required_fields(): + transport = transports.ConversationalSearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_conversation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_conversation_rest_interceptors(null_interceptor): + transport = transports.ConversationalSearchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConversationalSearchServiceRestInterceptor(), + ) + client = ConversationalSearchServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "pre_delete_conversation") as pre: + pre.assert_not_called() + pb_message = conversational_search_service.DeleteConversationRequest.pb(conversational_search_service.DeleteConversationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = conversational_search_service.DeleteConversationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_conversation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_conversation_rest_bad_request(transport: str = 'rest', request_type=conversational_search_service.DeleteConversationRequest): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_conversation(request) + + +def test_delete_conversation_rest_flattened(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/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 = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_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/{name=projects/*/locations/*/dataStores/*/conversations/*}" % client.transport._host, args[1]) + + +def test_delete_conversation_rest_flattened_error(transport: str = 'rest'): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.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_conversation( + conversational_search_service.DeleteConversationRequest(), + name='name_value', + ) + + +def test_delete_conversation_rest_error(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + conversational_search_service.UpdateConversationRequest, + dict, +]) +def test_update_conversation_rest(request_type): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'conversation': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'}} + request_init["conversation"] = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4', 'state': 1, 'user_pseudo_id': 'user_pseudo_id_value', 'messages': [{'user_input': {'input': 'input_value', 'context': {'context_documents': ['context_documents_value1', 'context_documents_value2'], 'active_document': 'active_document_value'}}, 'reply': {'reply': 'reply_value', 'references': [{'uri': 'uri_value', 'anchor_text': 'anchor_text_value', 'start': 558, 'end': 311}], 'summary': {'summary_text': 'summary_text_value', 'summary_skipped_reasons': [1], 'safety_attributes': {'categories': ['categories_value1', 'categories_value2'], 'scores': [0.656, 0.657]}}}, 'create_time': {'seconds': 751, 'nanos': 543}}], 'start_time': {}, 'end_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 = conversational_search_service.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 = gcd_conversation.Conversation( + name='name_value', + state=gcd_conversation.Conversation.State.IN_PROGRESS, + user_pseudo_id='user_pseudo_id_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 = gcd_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 + response = client.update_conversation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_conversation.Conversation) + assert response.name == 'name_value' + assert response.state == gcd_conversation.Conversation.State.IN_PROGRESS + assert response.user_pseudo_id == 'user_pseudo_id_value' + + +def test_update_conversation_rest_required_fields(request_type=conversational_search_service.UpdateConversationRequest): + transport_class = transports.ConversationalSearchServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_conversation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_conversation._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcd_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 = gcd_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 + + response = client.update_conversation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_conversation_rest_unset_required_fields(): + transport = transports.ConversationalSearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_conversation._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("conversation", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_conversation_rest_interceptors(null_interceptor): + transport = transports.ConversationalSearchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConversationalSearchServiceRestInterceptor(), + ) + client = ConversationalSearchServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "post_update_conversation") as post, \ + mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "pre_update_conversation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = conversational_search_service.UpdateConversationRequest.pb(conversational_search_service.UpdateConversationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcd_conversation.Conversation.to_json(gcd_conversation.Conversation()) + + request = conversational_search_service.UpdateConversationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcd_conversation.Conversation() + + client.update_conversation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_conversation_rest_bad_request(transport: str = 'rest', request_type=conversational_search_service.UpdateConversationRequest): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'conversation': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_conversation(request) + + +def test_update_conversation_rest_flattened(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcd_conversation.Conversation() + + # get arguments that satisfy an http rule for this method + sample_request = {'conversation': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + conversation=gcd_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 = gcd_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 + + 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/*/dataStores/*/conversations/*}" % client.transport._host, args[1]) + + +def test_update_conversation_rest_flattened_error(transport: str = 'rest'): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.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( + conversational_search_service.UpdateConversationRequest(), + conversation=gcd_conversation.Conversation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_conversation_rest_error(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + conversational_search_service.GetConversationRequest, + dict, +]) +def test_get_conversation_rest(request_type): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/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 = conversation.Conversation( + name='name_value', + state=conversation.Conversation.State.IN_PROGRESS, + user_pseudo_id='user_pseudo_id_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 = 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 + response = client.get_conversation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, conversation.Conversation) + assert response.name == 'name_value' + assert response.state == conversation.Conversation.State.IN_PROGRESS + assert response.user_pseudo_id == 'user_pseudo_id_value' + + +def test_get_conversation_rest_required_fields(request_type=conversational_search_service.GetConversationRequest): + transport_class = transports.ConversationalSearchServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_conversation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_conversation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = 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': "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 = 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 + + response = client.get_conversation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_conversation_rest_unset_required_fields(): + transport = transports.ConversationalSearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_conversation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_conversation_rest_interceptors(null_interceptor): + transport = transports.ConversationalSearchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConversationalSearchServiceRestInterceptor(), + ) + client = ConversationalSearchServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "post_get_conversation") as post, \ + mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "pre_get_conversation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = conversational_search_service.GetConversationRequest.pb(conversational_search_service.GetConversationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = conversation.Conversation.to_json(conversation.Conversation()) + + request = conversational_search_service.GetConversationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = conversation.Conversation() + + client.get_conversation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_conversation_rest_bad_request(transport: str = 'rest', request_type=conversational_search_service.GetConversationRequest): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_conversation(request) + + +def test_get_conversation_rest_flattened(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = conversation.Conversation() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/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 = 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 + + client.get_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/{name=projects/*/locations/*/dataStores/*/conversations/*}" % client.transport._host, args[1]) + + +def test_get_conversation_rest_flattened_error(transport: str = 'rest'): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.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_conversation( + conversational_search_service.GetConversationRequest(), + name='name_value', + ) + + +def test_get_conversation_rest_error(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + conversational_search_service.ListConversationsRequest, + dict, +]) +def test_list_conversations_rest(request_type): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/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 = conversational_search_service.ListConversationsResponse( + next_page_token='next_page_token_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 = conversational_search_service.ListConversationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_conversations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConversationsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_conversations_rest_required_fields(request_type=conversational_search_service.ListConversationsRequest): + transport_class = transports.ConversationalSearchServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_conversations._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_conversations._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = conversational_search_service.ListConversationsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = conversational_search_service.ListConversationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_conversations(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_conversations_rest_unset_required_fields(): + transport = transports.ConversationalSearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_conversations._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_conversations_rest_interceptors(null_interceptor): + transport = transports.ConversationalSearchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConversationalSearchServiceRestInterceptor(), + ) + client = ConversationalSearchServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "post_list_conversations") as post, \ + mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "pre_list_conversations") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = conversational_search_service.ListConversationsRequest.pb(conversational_search_service.ListConversationsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = conversational_search_service.ListConversationsResponse.to_json(conversational_search_service.ListConversationsResponse()) + + request = conversational_search_service.ListConversationsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = conversational_search_service.ListConversationsResponse() + + client.list_conversations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_conversations_rest_bad_request(transport: str = 'rest', request_type=conversational_search_service.ListConversationsRequest): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_conversations(request) + + +def test_list_conversations_rest_flattened(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = conversational_search_service.ListConversationsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/dataStores/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 = conversational_search_service.ListConversationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_conversations(**mock_args) + + # Establish that the underlying call 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/*/dataStores/*}/conversations" % client.transport._host, args[1]) + + +def test_list_conversations_rest_flattened_error(transport: str = 'rest'): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.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_conversations( + conversational_search_service.ListConversationsRequest(), + parent='parent_value', + ) + + +def test_list_conversations_rest_pager(transport: str = 'rest'): + client = ConversationalSearchServiceClient( + 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 = ( + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + conversation.Conversation(), + ], + next_page_token='abc', + ), + conversational_search_service.ListConversationsResponse( + conversations=[], + next_page_token='def', + ), + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + ], + next_page_token='ghi', + ), + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(conversational_search_service.ListConversationsResponse.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/dataStores/sample3'} + + pager = client.list_conversations(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, conversation.Conversation) + for i in results) + + pages = list(client.list_conversations(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.ConversationalSearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ConversationalSearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ConversationalSearchServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ConversationalSearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ConversationalSearchServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ConversationalSearchServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ConversationalSearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ConversationalSearchServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ConversationalSearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ConversationalSearchServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ConversationalSearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ConversationalSearchServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ConversationalSearchServiceGrpcTransport, + transports.ConversationalSearchServiceGrpcAsyncIOTransport, + transports.ConversationalSearchServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = ConversationalSearchServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ConversationalSearchServiceGrpcTransport, + ) + +def test_conversational_search_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ConversationalSearchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_conversational_search_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.discoveryengine_v1alpha.services.conversational_search_service.transports.ConversationalSearchServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ConversationalSearchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'converse_conversation', + 'create_conversation', + 'delete_conversation', + 'update_conversation', + 'get_conversation', + 'list_conversations', + 'get_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_conversational_search_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.discoveryengine_v1alpha.services.conversational_search_service.transports.ConversationalSearchServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ConversationalSearchServiceTransport( + 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_conversational_search_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.discoveryengine_v1alpha.services.conversational_search_service.transports.ConversationalSearchServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ConversationalSearchServiceTransport() + adc.assert_called_once() + + +def test_conversational_search_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) + ConversationalSearchServiceClient() + 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.ConversationalSearchServiceGrpcTransport, + transports.ConversationalSearchServiceGrpcAsyncIOTransport, + ], +) +def test_conversational_search_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.ConversationalSearchServiceGrpcTransport, + transports.ConversationalSearchServiceGrpcAsyncIOTransport, + transports.ConversationalSearchServiceRestTransport, + ], +) +def test_conversational_search_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.ConversationalSearchServiceGrpcTransport, grpc_helpers), + (transports.ConversationalSearchServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_conversational_search_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ConversationalSearchServiceGrpcTransport, transports.ConversationalSearchServiceGrpcAsyncIOTransport]) +def test_conversational_search_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_conversational_search_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.ConversationalSearchServiceRestTransport ( + 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_conversational_search_service_host_no_port(transport_name): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_conversational_search_service_host_with_port(transport_name): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_conversational_search_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ConversationalSearchServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ConversationalSearchServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.converse_conversation._session + session2 = client2.transport.converse_conversation._session + assert session1 != session2 + session1 = client1.transport.create_conversation._session + session2 = client2.transport.create_conversation._session + assert session1 != session2 + 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 + session1 = client1.transport.list_conversations._session + session2 = client2.transport.list_conversations._session + assert session1 != session2 +def test_conversational_search_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ConversationalSearchServiceGrpcTransport( + 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_conversational_search_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ConversationalSearchServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.ConversationalSearchServiceGrpcTransport, transports.ConversationalSearchServiceGrpcAsyncIOTransport]) +def test_conversational_search_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.ConversationalSearchServiceGrpcTransport, transports.ConversationalSearchServiceGrpcAsyncIOTransport]) +def test_conversational_search_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_conversation_path(): + project = "squid" + location = "clam" + data_store = "whelk" + conversation = "octopus" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/conversations/{conversation}".format(project=project, location=location, data_store=data_store, conversation=conversation, ) + actual = ConversationalSearchServiceClient.conversation_path(project, location, data_store, conversation) + assert expected == actual + + +def test_parse_conversation_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "data_store": "cuttlefish", + "conversation": "mussel", + } + path = ConversationalSearchServiceClient.conversation_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationalSearchServiceClient.parse_conversation_path(path) + assert expected == actual + +def test_data_store_path(): + project = "winkle" + location = "nautilus" + data_store = "scallop" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) + actual = ConversationalSearchServiceClient.data_store_path(project, location, data_store) + assert expected == actual + + +def test_parse_data_store_path(): + expected = { + "project": "abalone", + "location": "squid", + "data_store": "clam", + } + path = ConversationalSearchServiceClient.data_store_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationalSearchServiceClient.parse_data_store_path(path) + assert expected == actual + +def test_document_path(): + project = "whelk" + location = "octopus" + data_store = "oyster" + branch = "nudibranch" + document = "cuttlefish" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) + actual = ConversationalSearchServiceClient.document_path(project, location, data_store, branch, document) + assert expected == actual + + +def test_parse_document_path(): + expected = { + "project": "mussel", + "location": "winkle", + "data_store": "nautilus", + "branch": "scallop", + "document": "abalone", + } + path = ConversationalSearchServiceClient.document_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationalSearchServiceClient.parse_document_path(path) + assert expected == actual + +def test_serving_config_path(): + project = "squid" + location = "clam" + data_store = "whelk" + serving_config = "octopus" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/servingConfigs/{serving_config}".format(project=project, location=location, data_store=data_store, serving_config=serving_config, ) + actual = ConversationalSearchServiceClient.serving_config_path(project, location, data_store, serving_config) + assert expected == actual + + +def test_parse_serving_config_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "data_store": "cuttlefish", + "serving_config": "mussel", + } + path = ConversationalSearchServiceClient.serving_config_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationalSearchServiceClient.parse_serving_config_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ConversationalSearchServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = ConversationalSearchServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationalSearchServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format(folder=folder, ) + actual = ConversationalSearchServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = ConversationalSearchServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationalSearchServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ConversationalSearchServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = ConversationalSearchServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationalSearchServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format(project=project, ) + actual = ConversationalSearchServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = ConversationalSearchServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationalSearchServiceClient.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 = ConversationalSearchServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = ConversationalSearchServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationalSearchServiceClient.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.ConversationalSearchServiceTransport, '_prep_wrapped_messages') as prep: + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ConversationalSearchServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = ConversationalSearchServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_get_operation(transport: str = "grpc"): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc"): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = ConversationalSearchServiceClient( + 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 = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc"): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = ConversationalSearchServiceClient( + 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 = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = ConversationalSearchServiceClient( + 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", [ + (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport), + (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_data_store_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_data_store_service.py new file mode 100644 index 000000000000..6db7ece05a16 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_data_store_service.py @@ -0,0 +1,4481 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.discoveryengine_v1alpha.services.data_store_service import DataStoreServiceAsyncClient +from google.cloud.discoveryengine_v1alpha.services.data_store_service import DataStoreServiceClient +from google.cloud.discoveryengine_v1alpha.services.data_store_service import pagers +from google.cloud.discoveryengine_v1alpha.services.data_store_service import transports +from google.cloud.discoveryengine_v1alpha.types import common +from google.cloud.discoveryengine_v1alpha.types import data_store +from google.cloud.discoveryengine_v1alpha.types import data_store as gcd_data_store +from google.cloud.discoveryengine_v1alpha.types import data_store_service +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert DataStoreServiceClient._get_default_mtls_endpoint(None) is None + assert DataStoreServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert DataStoreServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert DataStoreServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert DataStoreServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert DataStoreServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (DataStoreServiceClient, "grpc"), + (DataStoreServiceAsyncClient, "grpc_asyncio"), + (DataStoreServiceClient, "rest"), +]) +def test_data_store_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.DataStoreServiceGrpcTransport, "grpc"), + (transports.DataStoreServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.DataStoreServiceRestTransport, "rest"), +]) +def test_data_store_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", [ + (DataStoreServiceClient, "grpc"), + (DataStoreServiceAsyncClient, "grpc_asyncio"), + (DataStoreServiceClient, "rest"), +]) +def test_data_store_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +def test_data_store_service_client_get_transport_class(): + transport = DataStoreServiceClient.get_transport_class() + available_transports = [ + transports.DataStoreServiceGrpcTransport, + transports.DataStoreServiceRestTransport, + ] + assert transport in available_transports + + transport = DataStoreServiceClient.get_transport_class("grpc") + assert transport == transports.DataStoreServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DataStoreServiceClient, transports.DataStoreServiceGrpcTransport, "grpc"), + (DataStoreServiceAsyncClient, transports.DataStoreServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (DataStoreServiceClient, transports.DataStoreServiceRestTransport, "rest"), +]) +@mock.patch.object(DataStoreServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataStoreServiceClient)) +@mock.patch.object(DataStoreServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataStoreServiceAsyncClient)) +def test_data_store_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(DataStoreServiceClient, '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(DataStoreServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (DataStoreServiceClient, transports.DataStoreServiceGrpcTransport, "grpc", "true"), + (DataStoreServiceAsyncClient, transports.DataStoreServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (DataStoreServiceClient, transports.DataStoreServiceGrpcTransport, "grpc", "false"), + (DataStoreServiceAsyncClient, transports.DataStoreServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (DataStoreServiceClient, transports.DataStoreServiceRestTransport, "rest", "true"), + (DataStoreServiceClient, transports.DataStoreServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(DataStoreServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataStoreServiceClient)) +@mock.patch.object(DataStoreServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataStoreServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_data_store_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 + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + DataStoreServiceClient, DataStoreServiceAsyncClient +]) +@mock.patch.object(DataStoreServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataStoreServiceClient)) +@mock.patch.object(DataStoreServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataStoreServiceAsyncClient)) +def test_data_store_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DataStoreServiceClient, transports.DataStoreServiceGrpcTransport, "grpc"), + (DataStoreServiceAsyncClient, transports.DataStoreServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (DataStoreServiceClient, transports.DataStoreServiceRestTransport, "rest"), +]) +def test_data_store_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, + 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", [ + (DataStoreServiceClient, transports.DataStoreServiceGrpcTransport, "grpc", grpc_helpers), + (DataStoreServiceAsyncClient, transports.DataStoreServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (DataStoreServiceClient, transports.DataStoreServiceRestTransport, "rest", None), +]) +def test_data_store_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, + scopes=None, + client_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_store_service_client_client_options_from_dict(): + with mock.patch('google.cloud.discoveryengine_v1alpha.services.data_store_service.transports.DataStoreServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = DataStoreServiceClient( + 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", [ + (DataStoreServiceClient, transports.DataStoreServiceGrpcTransport, "grpc", grpc_helpers), + (DataStoreServiceAsyncClient, transports.DataStoreServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_data_store_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, + scopes=None, + client_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + data_store_service.CreateDataStoreRequest, + dict, +]) +def test_create_data_store(request_type, transport: str = 'grpc'): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_store), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_data_store(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == data_store_service.CreateDataStoreRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_data_store_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_store), + '__call__') as call: + client.create_data_store() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_store_service.CreateDataStoreRequest() + +@pytest.mark.asyncio +async def test_create_data_store_async(transport: str = 'grpc_asyncio', request_type=data_store_service.CreateDataStoreRequest): + client = DataStoreServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_store), + '__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_data_store(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_store_service.CreateDataStoreRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_data_store_async_from_dict(): + await test_create_data_store_async(request_type=dict) + + +def test_create_data_store_field_headers(): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_store_service.CreateDataStoreRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_store), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_data_store(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_data_store_field_headers_async(): + client = DataStoreServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_store_service.CreateDataStoreRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_store), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_data_store(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_data_store_flattened(): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_store), + '__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_data_store( + parent='parent_value', + data_store=gcd_data_store.DataStore(name='name_value'), + data_store_id='data_store_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].data_store + mock_val = gcd_data_store.DataStore(name='name_value') + assert arg == mock_val + arg = args[0].data_store_id + mock_val = 'data_store_id_value' + assert arg == mock_val + + +def test_create_data_store_flattened_error(): + client = DataStoreServiceClient( + credentials=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_data_store( + data_store_service.CreateDataStoreRequest(), + parent='parent_value', + data_store=gcd_data_store.DataStore(name='name_value'), + data_store_id='data_store_id_value', + ) + +@pytest.mark.asyncio +async def test_create_data_store_flattened_async(): + client = DataStoreServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_store), + '__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_data_store( + parent='parent_value', + data_store=gcd_data_store.DataStore(name='name_value'), + data_store_id='data_store_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].data_store + mock_val = gcd_data_store.DataStore(name='name_value') + assert arg == mock_val + arg = args[0].data_store_id + mock_val = 'data_store_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_data_store_flattened_error_async(): + client = DataStoreServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_data_store( + data_store_service.CreateDataStoreRequest(), + parent='parent_value', + data_store=gcd_data_store.DataStore(name='name_value'), + data_store_id='data_store_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + data_store_service.GetDataStoreRequest, + dict, +]) +def test_get_data_store(request_type, transport: str = 'grpc'): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_store), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = data_store.DataStore( + name='name_value', + display_name='display_name_value', + industry_vertical=common.IndustryVertical.GENERIC, + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + default_schema_id='default_schema_id_value', + content_config=data_store.DataStore.ContentConfig.NO_CONTENT, + ) + response = client.get_data_store(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == data_store_service.GetDataStoreRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, data_store.DataStore) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.industry_vertical == common.IndustryVertical.GENERIC + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + assert response.default_schema_id == 'default_schema_id_value' + assert response.content_config == data_store.DataStore.ContentConfig.NO_CONTENT + + +def test_get_data_store_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_store), + '__call__') as call: + client.get_data_store() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_store_service.GetDataStoreRequest() + +@pytest.mark.asyncio +async def test_get_data_store_async(transport: str = 'grpc_asyncio', request_type=data_store_service.GetDataStoreRequest): + client = DataStoreServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_store), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(data_store.DataStore( + name='name_value', + display_name='display_name_value', + industry_vertical=common.IndustryVertical.GENERIC, + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + default_schema_id='default_schema_id_value', + content_config=data_store.DataStore.ContentConfig.NO_CONTENT, + )) + response = await client.get_data_store(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_store_service.GetDataStoreRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, data_store.DataStore) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.industry_vertical == common.IndustryVertical.GENERIC + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + assert response.default_schema_id == 'default_schema_id_value' + assert response.content_config == data_store.DataStore.ContentConfig.NO_CONTENT + + +@pytest.mark.asyncio +async def test_get_data_store_async_from_dict(): + await test_get_data_store_async(request_type=dict) + + +def test_get_data_store_field_headers(): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_store_service.GetDataStoreRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_store), + '__call__') as call: + call.return_value = data_store.DataStore() + client.get_data_store(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_data_store_field_headers_async(): + client = DataStoreServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_store_service.GetDataStoreRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_store), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_store.DataStore()) + await client.get_data_store(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_data_store_flattened(): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_store), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = data_store.DataStore() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_data_store( + 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_data_store_flattened_error(): + client = DataStoreServiceClient( + credentials=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_data_store( + data_store_service.GetDataStoreRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_data_store_flattened_async(): + client = DataStoreServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_store), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = data_store.DataStore() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_store.DataStore()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_data_store( + 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_data_store_flattened_error_async(): + client = DataStoreServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_data_store( + data_store_service.GetDataStoreRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + data_store_service.ListDataStoresRequest, + dict, +]) +def test_list_data_stores(request_type, transport: str = 'grpc'): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_stores), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = data_store_service.ListDataStoresResponse( + next_page_token='next_page_token_value', + ) + response = client.list_data_stores(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == data_store_service.ListDataStoresRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDataStoresPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_data_stores_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_stores), + '__call__') as call: + client.list_data_stores() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_store_service.ListDataStoresRequest() + +@pytest.mark.asyncio +async def test_list_data_stores_async(transport: str = 'grpc_asyncio', request_type=data_store_service.ListDataStoresRequest): + client = DataStoreServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_stores), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(data_store_service.ListDataStoresResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_data_stores(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_store_service.ListDataStoresRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDataStoresAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_data_stores_async_from_dict(): + await test_list_data_stores_async(request_type=dict) + + +def test_list_data_stores_field_headers(): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_store_service.ListDataStoresRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_stores), + '__call__') as call: + call.return_value = data_store_service.ListDataStoresResponse() + client.list_data_stores(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_data_stores_field_headers_async(): + client = DataStoreServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_store_service.ListDataStoresRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_stores), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_store_service.ListDataStoresResponse()) + await client.list_data_stores(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_data_stores_flattened(): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_stores), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = data_store_service.ListDataStoresResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_data_stores( + 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_data_stores_flattened_error(): + client = DataStoreServiceClient( + credentials=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_data_stores( + data_store_service.ListDataStoresRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_data_stores_flattened_async(): + client = DataStoreServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_stores), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = data_store_service.ListDataStoresResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_store_service.ListDataStoresResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_data_stores( + 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_data_stores_flattened_error_async(): + client = DataStoreServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_data_stores( + data_store_service.ListDataStoresRequest(), + parent='parent_value', + ) + + +def test_list_data_stores_pager(transport_name: str = "grpc"): + client = DataStoreServiceClient( + 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_data_stores), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + data_store_service.ListDataStoresResponse( + data_stores=[ + data_store.DataStore(), + data_store.DataStore(), + data_store.DataStore(), + ], + next_page_token='abc', + ), + data_store_service.ListDataStoresResponse( + data_stores=[], + next_page_token='def', + ), + data_store_service.ListDataStoresResponse( + data_stores=[ + data_store.DataStore(), + ], + next_page_token='ghi', + ), + data_store_service.ListDataStoresResponse( + data_stores=[ + data_store.DataStore(), + data_store.DataStore(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_data_stores(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, data_store.DataStore) + for i in results) +def test_list_data_stores_pages(transport_name: str = "grpc"): + client = DataStoreServiceClient( + 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_data_stores), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + data_store_service.ListDataStoresResponse( + data_stores=[ + data_store.DataStore(), + data_store.DataStore(), + data_store.DataStore(), + ], + next_page_token='abc', + ), + data_store_service.ListDataStoresResponse( + data_stores=[], + next_page_token='def', + ), + data_store_service.ListDataStoresResponse( + data_stores=[ + data_store.DataStore(), + ], + next_page_token='ghi', + ), + data_store_service.ListDataStoresResponse( + data_stores=[ + data_store.DataStore(), + data_store.DataStore(), + ], + ), + RuntimeError, + ) + pages = list(client.list_data_stores(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_data_stores_async_pager(): + client = DataStoreServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_stores), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + data_store_service.ListDataStoresResponse( + data_stores=[ + data_store.DataStore(), + data_store.DataStore(), + data_store.DataStore(), + ], + next_page_token='abc', + ), + data_store_service.ListDataStoresResponse( + data_stores=[], + next_page_token='def', + ), + data_store_service.ListDataStoresResponse( + data_stores=[ + data_store.DataStore(), + ], + next_page_token='ghi', + ), + data_store_service.ListDataStoresResponse( + data_stores=[ + data_store.DataStore(), + data_store.DataStore(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_data_stores(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, data_store.DataStore) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_data_stores_async_pages(): + client = DataStoreServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_stores), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + data_store_service.ListDataStoresResponse( + data_stores=[ + data_store.DataStore(), + data_store.DataStore(), + data_store.DataStore(), + ], + next_page_token='abc', + ), + data_store_service.ListDataStoresResponse( + data_stores=[], + next_page_token='def', + ), + data_store_service.ListDataStoresResponse( + data_stores=[ + data_store.DataStore(), + ], + next_page_token='ghi', + ), + data_store_service.ListDataStoresResponse( + data_stores=[ + data_store.DataStore(), + data_store.DataStore(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_data_stores(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", [ + data_store_service.DeleteDataStoreRequest, + dict, +]) +def test_delete_data_store(request_type, transport: str = 'grpc'): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_store), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_data_store(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == data_store_service.DeleteDataStoreRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_data_store_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_store), + '__call__') as call: + client.delete_data_store() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_store_service.DeleteDataStoreRequest() + +@pytest.mark.asyncio +async def test_delete_data_store_async(transport: str = 'grpc_asyncio', request_type=data_store_service.DeleteDataStoreRequest): + client = DataStoreServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_store), + '__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_data_store(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_store_service.DeleteDataStoreRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_data_store_async_from_dict(): + await test_delete_data_store_async(request_type=dict) + + +def test_delete_data_store_field_headers(): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_store_service.DeleteDataStoreRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_store), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_data_store(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_data_store_field_headers_async(): + client = DataStoreServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_store_service.DeleteDataStoreRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_store), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_data_store(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_data_store_flattened(): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_store), + '__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_data_store( + 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_data_store_flattened_error(): + client = DataStoreServiceClient( + credentials=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_data_store( + data_store_service.DeleteDataStoreRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_data_store_flattened_async(): + client = DataStoreServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_store), + '__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_data_store( + 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_data_store_flattened_error_async(): + client = DataStoreServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_data_store( + data_store_service.DeleteDataStoreRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + data_store_service.UpdateDataStoreRequest, + dict, +]) +def test_update_data_store(request_type, transport: str = 'grpc'): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_store), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_data_store.DataStore( + name='name_value', + display_name='display_name_value', + industry_vertical=common.IndustryVertical.GENERIC, + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + default_schema_id='default_schema_id_value', + content_config=gcd_data_store.DataStore.ContentConfig.NO_CONTENT, + ) + response = client.update_data_store(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == data_store_service.UpdateDataStoreRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_data_store.DataStore) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.industry_vertical == common.IndustryVertical.GENERIC + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + assert response.default_schema_id == 'default_schema_id_value' + assert response.content_config == gcd_data_store.DataStore.ContentConfig.NO_CONTENT + + +def test_update_data_store_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_store), + '__call__') as call: + client.update_data_store() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_store_service.UpdateDataStoreRequest() + +@pytest.mark.asyncio +async def test_update_data_store_async(transport: str = 'grpc_asyncio', request_type=data_store_service.UpdateDataStoreRequest): + client = DataStoreServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_data_store), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_data_store.DataStore( + name='name_value', + display_name='display_name_value', + industry_vertical=common.IndustryVertical.GENERIC, + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + default_schema_id='default_schema_id_value', + content_config=gcd_data_store.DataStore.ContentConfig.NO_CONTENT, + )) + response = await client.update_data_store(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == data_store_service.UpdateDataStoreRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_data_store.DataStore) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.industry_vertical == common.IndustryVertical.GENERIC + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + assert response.default_schema_id == 'default_schema_id_value' + assert response.content_config == gcd_data_store.DataStore.ContentConfig.NO_CONTENT + + +@pytest.mark.asyncio +async def test_update_data_store_async_from_dict(): + await test_update_data_store_async(request_type=dict) + + +def test_update_data_store_field_headers(): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_store_service.UpdateDataStoreRequest() + + request.data_store.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_store), + '__call__') as call: + call.return_value = gcd_data_store.DataStore() + client.update_data_store(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'data_store.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_data_store_field_headers_async(): + client = DataStoreServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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_store_service.UpdateDataStoreRequest() + + request.data_store.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_store), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_data_store.DataStore()) + await client.update_data_store(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'data_store.name=name_value', + ) in kw['metadata'] + + +def test_update_data_store_flattened(): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_store), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_data_store.DataStore() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_data_store( + data_store=gcd_data_store.DataStore(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].data_store + mock_val = gcd_data_store.DataStore(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_data_store_flattened_error(): + client = DataStoreServiceClient( + credentials=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_data_store( + data_store_service.UpdateDataStoreRequest(), + data_store=gcd_data_store.DataStore(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_data_store_flattened_async(): + client = DataStoreServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_store), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_data_store.DataStore() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_data_store.DataStore()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_data_store( + data_store=gcd_data_store.DataStore(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].data_store + mock_val = gcd_data_store.DataStore(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_data_store_flattened_error_async(): + client = DataStoreServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_data_store( + data_store_service.UpdateDataStoreRequest(), + data_store=gcd_data_store.DataStore(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + data_store_service.CreateDataStoreRequest, + dict, +]) +def test_create_data_store_rest(request_type): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["data_store"] = {'name': 'name_value', 'display_name': 'display_name_value', 'industry_vertical': 1, 'solution_types': [1], 'default_schema_id': 'default_schema_id_value', 'content_config': 1, 'create_time': {'seconds': 751, 'nanos': 543}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = data_store_service.CreateDataStoreRequest.meta.fields["data_store"] + + 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["data_store"].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["data_store"][field])): + del request_init["data_store"][field][i][subfield] + else: + del request_init["data_store"][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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_data_store(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_data_store_rest_required_fields(request_type=data_store_service.CreateDataStoreRequest): + transport_class = transports.DataStoreServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["data_store_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "dataStoreId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_data_store._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "dataStoreId" in jsonified_request + assert jsonified_request["dataStoreId"] == request_init["data_store_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["dataStoreId"] = 'data_store_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_data_store._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("create_advanced_site_search", "data_store_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "dataStoreId" in jsonified_request + assert jsonified_request["dataStoreId"] == 'data_store_id_value' + + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_data_store(request) + + expected_params = [ + ( + "dataStoreId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_data_store_rest_unset_required_fields(): + transport = transports.DataStoreServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_data_store._get_unset_required_fields({}) + assert set(unset_fields) == (set(("createAdvancedSiteSearch", "dataStoreId", )) & set(("parent", "dataStore", "dataStoreId", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_data_store_rest_interceptors(null_interceptor): + transport = transports.DataStoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataStoreServiceRestInterceptor(), + ) + client = DataStoreServiceClient(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.DataStoreServiceRestInterceptor, "post_create_data_store") as post, \ + mock.patch.object(transports.DataStoreServiceRestInterceptor, "pre_create_data_store") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = data_store_service.CreateDataStoreRequest.pb(data_store_service.CreateDataStoreRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = data_store_service.CreateDataStoreRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_data_store(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_data_store_rest_bad_request(transport: str = 'rest', request_type=data_store_service.CreateDataStoreRequest): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_data_store(request) + + +def test_create_data_store_rest_flattened(): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.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', + data_store=gcd_data_store.DataStore(name='name_value'), + data_store_id='data_store_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_data_store(**mock_args) + + # Establish that the underlying call 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/*}/dataStores" % client.transport._host, args[1]) + + +def test_create_data_store_rest_flattened_error(transport: str = 'rest'): + client = DataStoreServiceClient( + credentials=ga_credentials.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_store( + data_store_service.CreateDataStoreRequest(), + parent='parent_value', + data_store=gcd_data_store.DataStore(name='name_value'), + data_store_id='data_store_id_value', + ) + + +def test_create_data_store_rest_error(): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + data_store_service.GetDataStoreRequest, + dict, +]) +def test_get_data_store_rest(request_type): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/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_store.DataStore( + name='name_value', + display_name='display_name_value', + industry_vertical=common.IndustryVertical.GENERIC, + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + default_schema_id='default_schema_id_value', + content_config=data_store.DataStore.ContentConfig.NO_CONTENT, + ) + + # 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_store.DataStore.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_data_store(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, data_store.DataStore) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.industry_vertical == common.IndustryVertical.GENERIC + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + assert response.default_schema_id == 'default_schema_id_value' + assert response.content_config == data_store.DataStore.ContentConfig.NO_CONTENT + + +def test_get_data_store_rest_required_fields(request_type=data_store_service.GetDataStoreRequest): + transport_class = transports.DataStoreServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_data_store._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_data_store._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = data_store.DataStore() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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_store.DataStore.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_data_store(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_data_store_rest_unset_required_fields(): + transport = transports.DataStoreServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_data_store._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_data_store_rest_interceptors(null_interceptor): + transport = transports.DataStoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataStoreServiceRestInterceptor(), + ) + client = DataStoreServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DataStoreServiceRestInterceptor, "post_get_data_store") as post, \ + mock.patch.object(transports.DataStoreServiceRestInterceptor, "pre_get_data_store") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = data_store_service.GetDataStoreRequest.pb(data_store_service.GetDataStoreRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = data_store.DataStore.to_json(data_store.DataStore()) + + request = data_store_service.GetDataStoreRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = data_store.DataStore() + + client.get_data_store(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_data_store_rest_bad_request(transport: str = 'rest', request_type=data_store_service.GetDataStoreRequest): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_data_store(request) + + +def test_get_data_store_rest_flattened(): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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_store.DataStore() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/dataStores/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 = data_store.DataStore.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_data_store(**mock_args) + + # Establish that the underlying call 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/*/dataStores/*}" % client.transport._host, args[1]) + + +def test_get_data_store_rest_flattened_error(transport: str = 'rest'): + client = DataStoreServiceClient( + credentials=ga_credentials.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_data_store( + data_store_service.GetDataStoreRequest(), + name='name_value', + ) + + +def test_get_data_store_rest_error(): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + data_store_service.ListDataStoresRequest, + dict, +]) +def test_list_data_stores_rest(request_type): + client = DataStoreServiceClient( + 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 = data_store_service.ListDataStoresResponse( + next_page_token='next_page_token_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 = data_store_service.ListDataStoresResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_data_stores(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDataStoresPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_data_stores_rest_required_fields(request_type=data_store_service.ListDataStoresRequest): + transport_class = transports.DataStoreServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_data_stores._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_data_stores._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = data_store_service.ListDataStoresResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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_store_service.ListDataStoresResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_data_stores(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_data_stores_rest_unset_required_fields(): + transport = transports.DataStoreServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_data_stores._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_data_stores_rest_interceptors(null_interceptor): + transport = transports.DataStoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataStoreServiceRestInterceptor(), + ) + client = DataStoreServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DataStoreServiceRestInterceptor, "post_list_data_stores") as post, \ + mock.patch.object(transports.DataStoreServiceRestInterceptor, "pre_list_data_stores") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = data_store_service.ListDataStoresRequest.pb(data_store_service.ListDataStoresRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = data_store_service.ListDataStoresResponse.to_json(data_store_service.ListDataStoresResponse()) + + request = data_store_service.ListDataStoresRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = data_store_service.ListDataStoresResponse() + + client.list_data_stores(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_data_stores_rest_bad_request(transport: str = 'rest', request_type=data_store_service.ListDataStoresRequest): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_data_stores(request) + + +def test_list_data_stores_rest_flattened(): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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_store_service.ListDataStoresResponse() + + # 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_store_service.ListDataStoresResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_data_stores(**mock_args) + + # Establish that the underlying call 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/*}/dataStores" % client.transport._host, args[1]) + + +def test_list_data_stores_rest_flattened_error(transport: str = 'rest'): + client = DataStoreServiceClient( + credentials=ga_credentials.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_stores( + data_store_service.ListDataStoresRequest(), + parent='parent_value', + ) + + +def test_list_data_stores_rest_pager(transport: str = 'rest'): + client = DataStoreServiceClient( + 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_store_service.ListDataStoresResponse( + data_stores=[ + data_store.DataStore(), + data_store.DataStore(), + data_store.DataStore(), + ], + next_page_token='abc', + ), + data_store_service.ListDataStoresResponse( + data_stores=[], + next_page_token='def', + ), + data_store_service.ListDataStoresResponse( + data_stores=[ + data_store.DataStore(), + ], + next_page_token='ghi', + ), + data_store_service.ListDataStoresResponse( + data_stores=[ + data_store.DataStore(), + data_store.DataStore(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(data_store_service.ListDataStoresResponse.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_stores(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, data_store.DataStore) + for i in results) + + pages = list(client.list_data_stores(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + data_store_service.DeleteDataStoreRequest, + dict, +]) +def test_delete_data_store_rest(request_type): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_data_store(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_data_store_rest_required_fields(request_type=data_store_service.DeleteDataStoreRequest): + transport_class = transports.DataStoreServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_data_store._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_data_store._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_data_store(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_data_store_rest_unset_required_fields(): + transport = transports.DataStoreServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_data_store._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_data_store_rest_interceptors(null_interceptor): + transport = transports.DataStoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataStoreServiceRestInterceptor(), + ) + client = DataStoreServiceClient(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.DataStoreServiceRestInterceptor, "post_delete_data_store") as post, \ + mock.patch.object(transports.DataStoreServiceRestInterceptor, "pre_delete_data_store") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = data_store_service.DeleteDataStoreRequest.pb(data_store_service.DeleteDataStoreRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = data_store_service.DeleteDataStoreRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_data_store(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_data_store_rest_bad_request(transport: str = 'rest', request_type=data_store_service.DeleteDataStoreRequest): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_data_store(request) + + +def test_delete_data_store_rest_flattened(): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.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/dataStores/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_data_store(**mock_args) + + # Establish that the underlying call 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/*/dataStores/*}" % client.transport._host, args[1]) + + +def test_delete_data_store_rest_flattened_error(transport: str = 'rest'): + client = DataStoreServiceClient( + credentials=ga_credentials.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_data_store( + data_store_service.DeleteDataStoreRequest(), + name='name_value', + ) + + +def test_delete_data_store_rest_error(): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + data_store_service.UpdateDataStoreRequest, + dict, +]) +def test_update_data_store_rest(request_type): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'data_store': {'name': 'projects/sample1/locations/sample2/dataStores/sample3'}} + request_init["data_store"] = {'name': 'projects/sample1/locations/sample2/dataStores/sample3', 'display_name': 'display_name_value', 'industry_vertical': 1, 'solution_types': [1], 'default_schema_id': 'default_schema_id_value', 'content_config': 1, 'create_time': {'seconds': 751, 'nanos': 543}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = data_store_service.UpdateDataStoreRequest.meta.fields["data_store"] + + 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["data_store"].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["data_store"][field])): + del request_init["data_store"][field][i][subfield] + else: + del request_init["data_store"][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 = gcd_data_store.DataStore( + name='name_value', + display_name='display_name_value', + industry_vertical=common.IndustryVertical.GENERIC, + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + default_schema_id='default_schema_id_value', + content_config=gcd_data_store.DataStore.ContentConfig.NO_CONTENT, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcd_data_store.DataStore.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_data_store(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_data_store.DataStore) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.industry_vertical == common.IndustryVertical.GENERIC + assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] + assert response.default_schema_id == 'default_schema_id_value' + assert response.content_config == gcd_data_store.DataStore.ContentConfig.NO_CONTENT + + +def test_update_data_store_rest_required_fields(request_type=data_store_service.UpdateDataStoreRequest): + transport_class = transports.DataStoreServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_data_store._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_data_store._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcd_data_store.DataStore() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcd_data_store.DataStore.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_data_store(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_data_store_rest_unset_required_fields(): + transport = transports.DataStoreServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_data_store._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("dataStore", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_data_store_rest_interceptors(null_interceptor): + transport = transports.DataStoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataStoreServiceRestInterceptor(), + ) + client = DataStoreServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DataStoreServiceRestInterceptor, "post_update_data_store") as post, \ + mock.patch.object(transports.DataStoreServiceRestInterceptor, "pre_update_data_store") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = data_store_service.UpdateDataStoreRequest.pb(data_store_service.UpdateDataStoreRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcd_data_store.DataStore.to_json(gcd_data_store.DataStore()) + + request = data_store_service.UpdateDataStoreRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcd_data_store.DataStore() + + client.update_data_store(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_data_store_rest_bad_request(transport: str = 'rest', request_type=data_store_service.UpdateDataStoreRequest): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'data_store': {'name': 'projects/sample1/locations/sample2/dataStores/sample3'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_data_store(request) + + +def test_update_data_store_rest_flattened(): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcd_data_store.DataStore() + + # get arguments that satisfy an http rule for this method + sample_request = {'data_store': {'name': 'projects/sample1/locations/sample2/dataStores/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + data_store=gcd_data_store.DataStore(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 = gcd_data_store.DataStore.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_data_store(**mock_args) + + # Establish that the underlying call 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_store.name=projects/*/locations/*/dataStores/*}" % client.transport._host, args[1]) + + +def test_update_data_store_rest_flattened_error(transport: str = 'rest'): + client = DataStoreServiceClient( + credentials=ga_credentials.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_data_store( + data_store_service.UpdateDataStoreRequest(), + data_store=gcd_data_store.DataStore(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_data_store_rest_error(): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.DataStoreServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.DataStoreServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataStoreServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.DataStoreServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DataStoreServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DataStoreServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.DataStoreServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DataStoreServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.DataStoreServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = DataStoreServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.DataStoreServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.DataStoreServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.DataStoreServiceGrpcTransport, + transports.DataStoreServiceGrpcAsyncIOTransport, + transports.DataStoreServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = DataStoreServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.DataStoreServiceGrpcTransport, + ) + +def test_data_store_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.DataStoreServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_data_store_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.discoveryengine_v1alpha.services.data_store_service.transports.DataStoreServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.DataStoreServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_data_store', + 'get_data_store', + 'list_data_stores', + 'delete_data_store', + 'update_data_store', + 'get_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_data_store_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.discoveryengine_v1alpha.services.data_store_service.transports.DataStoreServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DataStoreServiceTransport( + 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_store_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.discoveryengine_v1alpha.services.data_store_service.transports.DataStoreServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DataStoreServiceTransport() + adc.assert_called_once() + + +def test_data_store_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) + DataStoreServiceClient() + 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.DataStoreServiceGrpcTransport, + transports.DataStoreServiceGrpcAsyncIOTransport, + ], +) +def test_data_store_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.DataStoreServiceGrpcTransport, + transports.DataStoreServiceGrpcAsyncIOTransport, + transports.DataStoreServiceRestTransport, + ], +) +def test_data_store_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.DataStoreServiceGrpcTransport, grpc_helpers), + (transports.DataStoreServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_data_store_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.DataStoreServiceGrpcTransport, transports.DataStoreServiceGrpcAsyncIOTransport]) +def test_data_store_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_store_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.DataStoreServiceRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_data_store_service_rest_lro_client(): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_data_store_service_host_no_port(transport_name): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_data_store_service_host_with_port(transport_name): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_data_store_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = DataStoreServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = DataStoreServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_data_store._session + session2 = client2.transport.create_data_store._session + assert session1 != session2 + session1 = client1.transport.get_data_store._session + session2 = client2.transport.get_data_store._session + assert session1 != session2 + session1 = client1.transport.list_data_stores._session + session2 = client2.transport.list_data_stores._session + assert session1 != session2 + session1 = client1.transport.delete_data_store._session + session2 = client2.transport.delete_data_store._session + assert session1 != session2 + session1 = client1.transport.update_data_store._session + session2 = client2.transport.update_data_store._session + assert session1 != session2 +def test_data_store_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DataStoreServiceGrpcTransport( + 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_store_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DataStoreServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.DataStoreServiceGrpcTransport, transports.DataStoreServiceGrpcAsyncIOTransport]) +def test_data_store_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.DataStoreServiceGrpcTransport, transports.DataStoreServiceGrpcAsyncIOTransport]) +def test_data_store_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_data_store_service_grpc_lro_client(): + client = DataStoreServiceClient( + 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_data_store_service_grpc_lro_async_client(): + client = DataStoreServiceAsyncClient( + 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_collection_path(): + project = "squid" + location = "clam" + collection = "whelk" + expected = "projects/{project}/locations/{location}/collections/{collection}".format(project=project, location=location, collection=collection, ) + actual = DataStoreServiceClient.collection_path(project, location, collection) + assert expected == actual + + +def test_parse_collection_path(): + expected = { + "project": "octopus", + "location": "oyster", + "collection": "nudibranch", + } + path = DataStoreServiceClient.collection_path(**expected) + + # Check that the path construction is reversible. + actual = DataStoreServiceClient.parse_collection_path(path) + assert expected == actual + +def test_data_store_path(): + project = "cuttlefish" + location = "mussel" + data_store = "winkle" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) + actual = DataStoreServiceClient.data_store_path(project, location, data_store) + assert expected == actual + + +def test_parse_data_store_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "data_store": "abalone", + } + path = DataStoreServiceClient.data_store_path(**expected) + + # Check that the path construction is reversible. + actual = DataStoreServiceClient.parse_data_store_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = DataStoreServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = DataStoreServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = DataStoreServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = DataStoreServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = DataStoreServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = DataStoreServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = DataStoreServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = DataStoreServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = DataStoreServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = DataStoreServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = DataStoreServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = DataStoreServiceClient.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 = DataStoreServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = DataStoreServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = DataStoreServiceClient.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.DataStoreServiceTransport, '_prep_wrapped_messages') as prep: + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.DataStoreServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = DataStoreServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = DataStoreServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_get_operation(transport: str = "grpc"): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc"): + client = DataStoreServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataStoreServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataStoreServiceClient( + 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 = DataStoreServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc"): + client = DataStoreServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataStoreServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DataStoreServiceClient( + 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 = DataStoreServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = DataStoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = DataStoreServiceClient( + 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", [ + (DataStoreServiceClient, transports.DataStoreServiceGrpcTransport), + (DataStoreServiceAsyncClient, transports.DataStoreServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_document_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_document_service.py new file mode 100644 index 000000000000..a06548425c15 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_document_service.py @@ -0,0 +1,4999 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.discoveryengine_v1alpha.services.document_service import DocumentServiceAsyncClient +from google.cloud.discoveryengine_v1alpha.services.document_service import DocumentServiceClient +from google.cloud.discoveryengine_v1alpha.services.document_service import pagers +from google.cloud.discoveryengine_v1alpha.services.document_service import transports +from google.cloud.discoveryengine_v1alpha.types import document +from google.cloud.discoveryengine_v1alpha.types import document as gcd_document +from google.cloud.discoveryengine_v1alpha.types import document_service +from google.cloud.discoveryengine_v1alpha.types import import_config +from google.cloud.discoveryengine_v1alpha.types import purge_config +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import struct_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert DocumentServiceClient._get_default_mtls_endpoint(None) is None + assert DocumentServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert DocumentServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert DocumentServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert DocumentServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert DocumentServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (DocumentServiceClient, "grpc"), + (DocumentServiceAsyncClient, "grpc_asyncio"), + (DocumentServiceClient, "rest"), +]) +def test_document_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.DocumentServiceGrpcTransport, "grpc"), + (transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.DocumentServiceRestTransport, "rest"), +]) +def test_document_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", [ + (DocumentServiceClient, "grpc"), + (DocumentServiceAsyncClient, "grpc_asyncio"), + (DocumentServiceClient, "rest"), +]) +def test_document_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +def test_document_service_client_get_transport_class(): + transport = DocumentServiceClient.get_transport_class() + available_transports = [ + transports.DocumentServiceGrpcTransport, + transports.DocumentServiceRestTransport, + ] + assert transport in available_transports + + transport = DocumentServiceClient.get_transport_class("grpc") + assert transport == transports.DocumentServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc"), + (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (DocumentServiceClient, transports.DocumentServiceRestTransport, "rest"), +]) +@mock.patch.object(DocumentServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceClient)) +@mock.patch.object(DocumentServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceAsyncClient)) +def test_document_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(DocumentServiceClient, '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(DocumentServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc", "true"), + (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc", "false"), + (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (DocumentServiceClient, transports.DocumentServiceRestTransport, "rest", "true"), + (DocumentServiceClient, transports.DocumentServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(DocumentServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceClient)) +@mock.patch.object(DocumentServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_document_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 + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + DocumentServiceClient, DocumentServiceAsyncClient +]) +@mock.patch.object(DocumentServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceClient)) +@mock.patch.object(DocumentServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceAsyncClient)) +def test_document_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc"), + (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (DocumentServiceClient, transports.DocumentServiceRestTransport, "rest"), +]) +def test_document_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, + 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", [ + (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc", grpc_helpers), + (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (DocumentServiceClient, transports.DocumentServiceRestTransport, "rest", None), +]) +def test_document_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, + scopes=None, + client_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_document_service_client_client_options_from_dict(): + with mock.patch('google.cloud.discoveryengine_v1alpha.services.document_service.transports.DocumentServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = DocumentServiceClient( + 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", [ + (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc", grpc_helpers), + (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_document_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, + scopes=None, + client_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + document_service.GetDocumentRequest, + dict, +]) +def test_get_document(request_type, transport: str = 'grpc'): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document.Document( + name='name_value', + id='id_value', + schema_id='schema_id_value', + parent_document_id='parent_document_id_value', + json_data='json_data_value', + ) + response = client.get_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.GetDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, document.Document) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.schema_id == 'schema_id_value' + assert response.parent_document_id == 'parent_document_id_value' + + +def test_get_document_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_document), + '__call__') as call: + client.get_document() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.GetDocumentRequest() + +@pytest.mark.asyncio +async def test_get_document_async(transport: str = 'grpc_asyncio', request_type=document_service.GetDocumentRequest): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document.Document( + name='name_value', + id='id_value', + schema_id='schema_id_value', + parent_document_id='parent_document_id_value', + )) + response = await client.get_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.GetDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, document.Document) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.schema_id == 'schema_id_value' + assert response.parent_document_id == 'parent_document_id_value' + + +@pytest.mark.asyncio +async def test_get_document_async_from_dict(): + await test_get_document_async(request_type=dict) + + +def test_get_document_field_headers(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_service.GetDocumentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_document), + '__call__') as call: + call.return_value = document.Document() + client.get_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_document_field_headers_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_service.GetDocumentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_document), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.Document()) + await client.get_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_document_flattened(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document.Document() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_document( + 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_document_flattened_error(): + client = DocumentServiceClient( + credentials=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_document( + document_service.GetDocumentRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_document_flattened_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document.Document() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.Document()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_document( + 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_document_flattened_error_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_document( + document_service.GetDocumentRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + document_service.ListDocumentsRequest, + dict, +]) +def test_list_documents(request_type, transport: str = 'grpc'): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_documents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_service.ListDocumentsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.ListDocumentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDocumentsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_documents_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_documents), + '__call__') as call: + client.list_documents() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.ListDocumentsRequest() + +@pytest.mark.asyncio +async def test_list_documents_async(transport: str = 'grpc_asyncio', request_type=document_service.ListDocumentsRequest): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_documents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document_service.ListDocumentsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.ListDocumentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDocumentsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_documents_async_from_dict(): + await test_list_documents_async(request_type=dict) + + +def test_list_documents_field_headers(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_service.ListDocumentsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_documents), + '__call__') as call: + call.return_value = document_service.ListDocumentsResponse() + client.list_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_documents_field_headers_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_service.ListDocumentsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_documents), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_service.ListDocumentsResponse()) + await client.list_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_documents_flattened(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_documents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_service.ListDocumentsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_documents( + 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_documents_flattened_error(): + client = DocumentServiceClient( + credentials=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_documents( + document_service.ListDocumentsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_documents_flattened_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_documents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_service.ListDocumentsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_service.ListDocumentsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_documents( + 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_documents_flattened_error_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_documents( + document_service.ListDocumentsRequest(), + parent='parent_value', + ) + + +def test_list_documents_pager(transport_name: str = "grpc"): + client = DocumentServiceClient( + 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_documents), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + document.Document(), + ], + next_page_token='abc', + ), + document_service.ListDocumentsResponse( + documents=[], + next_page_token='def', + ), + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + ], + next_page_token='ghi', + ), + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_documents(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, document.Document) + for i in results) +def test_list_documents_pages(transport_name: str = "grpc"): + client = DocumentServiceClient( + 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_documents), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + document.Document(), + ], + next_page_token='abc', + ), + document_service.ListDocumentsResponse( + documents=[], + next_page_token='def', + ), + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + ], + next_page_token='ghi', + ), + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + ], + ), + RuntimeError, + ) + pages = list(client.list_documents(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_documents_async_pager(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_documents), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + document.Document(), + ], + next_page_token='abc', + ), + document_service.ListDocumentsResponse( + documents=[], + next_page_token='def', + ), + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + ], + next_page_token='ghi', + ), + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_documents(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, document.Document) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_documents_async_pages(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_documents), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + document.Document(), + ], + next_page_token='abc', + ), + document_service.ListDocumentsResponse( + documents=[], + next_page_token='def', + ), + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + ], + next_page_token='ghi', + ), + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_documents(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", [ + document_service.CreateDocumentRequest, + dict, +]) +def test_create_document(request_type, transport: str = 'grpc'): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_document.Document( + name='name_value', + id='id_value', + schema_id='schema_id_value', + parent_document_id='parent_document_id_value', + json_data='json_data_value', + ) + response = client.create_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.CreateDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_document.Document) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.schema_id == 'schema_id_value' + assert response.parent_document_id == 'parent_document_id_value' + + +def test_create_document_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_document), + '__call__') as call: + client.create_document() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.CreateDocumentRequest() + +@pytest.mark.asyncio +async def test_create_document_async(transport: str = 'grpc_asyncio', request_type=document_service.CreateDocumentRequest): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_document.Document( + name='name_value', + id='id_value', + schema_id='schema_id_value', + parent_document_id='parent_document_id_value', + )) + response = await client.create_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.CreateDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_document.Document) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.schema_id == 'schema_id_value' + assert response.parent_document_id == 'parent_document_id_value' + + +@pytest.mark.asyncio +async def test_create_document_async_from_dict(): + await test_create_document_async(request_type=dict) + + +def test_create_document_field_headers(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_service.CreateDocumentRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_document), + '__call__') as call: + call.return_value = gcd_document.Document() + client.create_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_document_field_headers_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_service.CreateDocumentRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_document), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_document.Document()) + await client.create_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_document_flattened(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_document.Document() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_document( + parent='parent_value', + document=gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), + document_id='document_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].document + mock_val = gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})) + assert arg == mock_val + arg = args[0].document_id + mock_val = 'document_id_value' + assert arg == mock_val + + +def test_create_document_flattened_error(): + client = DocumentServiceClient( + credentials=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_document( + document_service.CreateDocumentRequest(), + parent='parent_value', + document=gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), + document_id='document_id_value', + ) + +@pytest.mark.asyncio +async def test_create_document_flattened_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_document.Document() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_document.Document()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_document( + parent='parent_value', + document=gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), + document_id='document_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].document + mock_val = gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})) + assert arg == mock_val + arg = args[0].document_id + mock_val = 'document_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_document_flattened_error_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_document( + document_service.CreateDocumentRequest(), + parent='parent_value', + document=gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), + document_id='document_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + document_service.UpdateDocumentRequest, + dict, +]) +def test_update_document(request_type, transport: str = 'grpc'): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document.Document( + name='name_value', + id='id_value', + schema_id='schema_id_value', + parent_document_id='parent_document_id_value', + json_data='json_data_value', + ) + response = client.update_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.UpdateDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, document.Document) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.schema_id == 'schema_id_value' + assert response.parent_document_id == 'parent_document_id_value' + + +def test_update_document_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_document), + '__call__') as call: + client.update_document() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.UpdateDocumentRequest() + +@pytest.mark.asyncio +async def test_update_document_async(transport: str = 'grpc_asyncio', request_type=document_service.UpdateDocumentRequest): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document.Document( + name='name_value', + id='id_value', + schema_id='schema_id_value', + parent_document_id='parent_document_id_value', + )) + response = await client.update_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.UpdateDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, document.Document) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.schema_id == 'schema_id_value' + assert response.parent_document_id == 'parent_document_id_value' + + +@pytest.mark.asyncio +async def test_update_document_async_from_dict(): + await test_update_document_async(request_type=dict) + + +def test_update_document_field_headers(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_service.UpdateDocumentRequest() + + request.document.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_document), + '__call__') as call: + call.return_value = document.Document() + client.update_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'document.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_document_field_headers_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_service.UpdateDocumentRequest() + + request.document.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_document), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.Document()) + await client.update_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'document.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + document_service.DeleteDocumentRequest, + dict, +]) +def test_delete_document(request_type, transport: str = 'grpc'): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.DeleteDocumentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_document_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_document), + '__call__') as call: + client.delete_document() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.DeleteDocumentRequest() + +@pytest.mark.asyncio +async def test_delete_document_async(transport: str = 'grpc_asyncio', request_type=document_service.DeleteDocumentRequest): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.DeleteDocumentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_document_async_from_dict(): + await test_delete_document_async(request_type=dict) + + +def test_delete_document_field_headers(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_service.DeleteDocumentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_document), + '__call__') as call: + call.return_value = None + client.delete_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_document_field_headers_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_service.DeleteDocumentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_document), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_document_flattened(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_document), + '__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_document( + 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_document_flattened_error(): + client = DocumentServiceClient( + credentials=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_document( + document_service.DeleteDocumentRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_document_flattened_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_document), + '__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_document( + 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_document_flattened_error_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_document( + document_service.DeleteDocumentRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportDocumentsRequest, + dict, +]) +def test_import_documents(request_type, transport: str = 'grpc'): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_documents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportDocumentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_documents_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_documents), + '__call__') as call: + client.import_documents() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportDocumentsRequest() + +@pytest.mark.asyncio +async def test_import_documents_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportDocumentsRequest): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_documents), + '__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_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportDocumentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_documents_async_from_dict(): + await test_import_documents_async(request_type=dict) + + +def test_import_documents_field_headers(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportDocumentsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_documents), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_import_documents_field_headers_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportDocumentsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_documents), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + purge_config.PurgeDocumentsRequest, + dict, +]) +def test_purge_documents(request_type, transport: str = 'grpc'): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_documents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.purge_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeDocumentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_purge_documents_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_documents), + '__call__') as call: + client.purge_documents() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeDocumentsRequest() + +@pytest.mark.asyncio +async def test_purge_documents_async(transport: str = 'grpc_asyncio', request_type=purge_config.PurgeDocumentsRequest): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_documents), + '__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.purge_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeDocumentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_purge_documents_async_from_dict(): + await test_purge_documents_async(request_type=dict) + + +def test_purge_documents_field_headers(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = purge_config.PurgeDocumentsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_documents), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.purge_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_purge_documents_field_headers_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = purge_config.PurgeDocumentsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_documents), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.purge_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + document_service.GetDocumentRequest, + dict, +]) +def test_get_document_rest(request_type): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = document.Document( + name='name_value', + id='id_value', + schema_id='schema_id_value', + parent_document_id='parent_document_id_value', + json_data='json_data_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 = document.Document.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_document(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, document.Document) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.schema_id == 'schema_id_value' + assert response.parent_document_id == 'parent_document_id_value' + + +def test_get_document_rest_required_fields(request_type=document_service.GetDocumentRequest): + transport_class = transports.DocumentServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_document._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_document._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = document.Document() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = document.Document.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_document(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_document_rest_unset_required_fields(): + transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_document._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_document_rest_interceptors(null_interceptor): + transport = transports.DocumentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), + ) + client = DocumentServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DocumentServiceRestInterceptor, "post_get_document") as post, \ + mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_get_document") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_service.GetDocumentRequest.pb(document_service.GetDocumentRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = document.Document.to_json(document.Document()) + + request = document_service.GetDocumentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = document.Document() + + client.get_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_document_rest_bad_request(transport: str = 'rest', request_type=document_service.GetDocumentRequest): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_document(request) + + +def test_get_document_rest_flattened(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = document.Document() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = document.Document.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_document(**mock_args) + + # Establish that the underlying call 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/*/dataStores/*/branches/*/documents/*}" % client.transport._host, args[1]) + + +def test_get_document_rest_flattened_error(transport: str = 'rest'): + client = DocumentServiceClient( + credentials=ga_credentials.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_document( + document_service.GetDocumentRequest(), + name='name_value', + ) + + +def test_get_document_rest_error(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_service.ListDocumentsRequest, + dict, +]) +def test_list_documents_rest(request_type): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/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 = document_service.ListDocumentsResponse( + next_page_token='next_page_token_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 = document_service.ListDocumentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_documents(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDocumentsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_documents_rest_required_fields(request_type=document_service.ListDocumentsRequest): + transport_class = transports.DocumentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_documents._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_documents._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = document_service.ListDocumentsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = document_service.ListDocumentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_documents(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_documents_rest_unset_required_fields(): + transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_documents._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_documents_rest_interceptors(null_interceptor): + transport = transports.DocumentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), + ) + client = DocumentServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DocumentServiceRestInterceptor, "post_list_documents") as post, \ + mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_list_documents") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_service.ListDocumentsRequest.pb(document_service.ListDocumentsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = document_service.ListDocumentsResponse.to_json(document_service.ListDocumentsResponse()) + + request = document_service.ListDocumentsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = document_service.ListDocumentsResponse() + + client.list_documents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_documents_rest_bad_request(transport: str = 'rest', request_type=document_service.ListDocumentsRequest): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_documents(request) + + +def test_list_documents_rest_flattened(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = document_service.ListDocumentsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = document_service.ListDocumentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_documents(**mock_args) + + # Establish that the underlying call 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/*/dataStores/*/branches/*}/documents" % client.transport._host, args[1]) + + +def test_list_documents_rest_flattened_error(transport: str = 'rest'): + client = DocumentServiceClient( + credentials=ga_credentials.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_documents( + document_service.ListDocumentsRequest(), + parent='parent_value', + ) + + +def test_list_documents_rest_pager(transport: str = 'rest'): + client = DocumentServiceClient( + 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 = ( + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + document.Document(), + ], + next_page_token='abc', + ), + document_service.ListDocumentsResponse( + documents=[], + next_page_token='def', + ), + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + ], + next_page_token='ghi', + ), + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(document_service.ListDocumentsResponse.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/dataStores/sample3/branches/sample4'} + + pager = client.list_documents(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, document.Document) + for i in results) + + pages = list(client.list_documents(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + document_service.CreateDocumentRequest, + dict, +]) +def test_create_document_rest(request_type): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} + request_init["document"] = {'struct_data': {'fields': {}}, 'json_data': 'json_data_value', 'name': 'name_value', 'id': 'id_value', 'schema_id': 'schema_id_value', 'content': {'raw_bytes': b'raw_bytes_blob', 'uri': 'uri_value', 'mime_type': 'mime_type_value'}, 'parent_document_id': 'parent_document_id_value', 'derived_struct_data': {}} + # 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 = document_service.CreateDocumentRequest.meta.fields["document"] + + 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["document"].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["document"][field])): + del request_init["document"][field][i][subfield] + else: + del request_init["document"][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 = gcd_document.Document( + name='name_value', + id='id_value', + schema_id='schema_id_value', + parent_document_id='parent_document_id_value', + json_data='json_data_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 = gcd_document.Document.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_document(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_document.Document) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.schema_id == 'schema_id_value' + assert response.parent_document_id == 'parent_document_id_value' + + +def test_create_document_rest_required_fields(request_type=document_service.CreateDocumentRequest): + transport_class = transports.DocumentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["document_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "documentId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_document._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "documentId" in jsonified_request + assert jsonified_request["documentId"] == request_init["document_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["documentId"] = 'document_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_document._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("document_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "documentId" in jsonified_request + assert jsonified_request["documentId"] == 'document_id_value' + + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcd_document.Document() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcd_document.Document.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_document(request) + + expected_params = [ + ( + "documentId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_document_rest_unset_required_fields(): + transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_document._get_unset_required_fields({}) + assert set(unset_fields) == (set(("documentId", )) & set(("parent", "document", "documentId", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_document_rest_interceptors(null_interceptor): + transport = transports.DocumentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), + ) + client = DocumentServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DocumentServiceRestInterceptor, "post_create_document") as post, \ + mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_create_document") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_service.CreateDocumentRequest.pb(document_service.CreateDocumentRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcd_document.Document.to_json(gcd_document.Document()) + + request = document_service.CreateDocumentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcd_document.Document() + + client.create_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_document_rest_bad_request(transport: str = 'rest', request_type=document_service.CreateDocumentRequest): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_document(request) + + +def test_create_document_rest_flattened(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcd_document.Document() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + document=gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), + document_id='document_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 = gcd_document.Document.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_document(**mock_args) + + # Establish that the underlying call 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/*/dataStores/*/branches/*}/documents" % client.transport._host, args[1]) + + +def test_create_document_rest_flattened_error(transport: str = 'rest'): + client = DocumentServiceClient( + credentials=ga_credentials.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_document( + document_service.CreateDocumentRequest(), + parent='parent_value', + document=gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), + document_id='document_id_value', + ) + + +def test_create_document_rest_error(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_service.UpdateDocumentRequest, + dict, +]) +def test_update_document_rest(request_type): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'document': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'}} + request_init["document"] = {'struct_data': {'fields': {}}, 'json_data': 'json_data_value', 'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5', 'id': 'id_value', 'schema_id': 'schema_id_value', 'content': {'raw_bytes': b'raw_bytes_blob', 'uri': 'uri_value', 'mime_type': 'mime_type_value'}, 'parent_document_id': 'parent_document_id_value', 'derived_struct_data': {}} + # 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 = document_service.UpdateDocumentRequest.meta.fields["document"] + + 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["document"].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["document"][field])): + del request_init["document"][field][i][subfield] + else: + del request_init["document"][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 = document.Document( + name='name_value', + id='id_value', + schema_id='schema_id_value', + parent_document_id='parent_document_id_value', + json_data='json_data_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 = document.Document.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_document(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, document.Document) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.schema_id == 'schema_id_value' + assert response.parent_document_id == 'parent_document_id_value' + + +def test_update_document_rest_required_fields(request_type=document_service.UpdateDocumentRequest): + transport_class = transports.DocumentServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_document._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_document._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = document.Document() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = document.Document.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_document(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_document_rest_unset_required_fields(): + transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_document._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", )) & set(("document", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_document_rest_interceptors(null_interceptor): + transport = transports.DocumentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), + ) + client = DocumentServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DocumentServiceRestInterceptor, "post_update_document") as post, \ + mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_update_document") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_service.UpdateDocumentRequest.pb(document_service.UpdateDocumentRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = document.Document.to_json(document.Document()) + + request = document_service.UpdateDocumentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = document.Document() + + client.update_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_document_rest_bad_request(transport: str = 'rest', request_type=document_service.UpdateDocumentRequest): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'document': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_document(request) + + +def test_update_document_rest_error(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_service.DeleteDocumentRequest, + dict, +]) +def test_delete_document_rest(request_type): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_document(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_document_rest_required_fields(request_type=document_service.DeleteDocumentRequest): + transport_class = transports.DocumentServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_document._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_document._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DocumentServiceClient( + 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 + + response = client.delete_document(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_document_rest_unset_required_fields(): + transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_document._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_document_rest_interceptors(null_interceptor): + transport = transports.DocumentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), + ) + client = DocumentServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_delete_document") as pre: + pre.assert_not_called() + pb_message = document_service.DeleteDocumentRequest.pb(document_service.DeleteDocumentRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = document_service.DeleteDocumentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_document_rest_bad_request(transport: str = 'rest', request_type=document_service.DeleteDocumentRequest): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_document(request) + + +def test_delete_document_rest_flattened(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_document(**mock_args) + + # Establish that the underlying call 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/*/dataStores/*/branches/*/documents/*}" % client.transport._host, args[1]) + + +def test_delete_document_rest_flattened_error(transport: str = 'rest'): + client = DocumentServiceClient( + credentials=ga_credentials.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_document( + document_service.DeleteDocumentRequest(), + name='name_value', + ) + + +def test_delete_document_rest_error(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportDocumentsRequest, + dict, +]) +def test_import_documents_rest(request_type): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.import_documents(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_import_documents_rest_required_fields(request_type=import_config.ImportDocumentsRequest): + transport_class = transports.DocumentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_documents._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_documents._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.import_documents(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_import_documents_rest_unset_required_fields(): + transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.import_documents._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_import_documents_rest_interceptors(null_interceptor): + transport = transports.DocumentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), + ) + client = DocumentServiceClient(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.DocumentServiceRestInterceptor, "post_import_documents") as post, \ + mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_import_documents") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = import_config.ImportDocumentsRequest.pb(import_config.ImportDocumentsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = import_config.ImportDocumentsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.import_documents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_import_documents_rest_bad_request(transport: str = 'rest', request_type=import_config.ImportDocumentsRequest): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.import_documents(request) + + +def test_import_documents_rest_error(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + purge_config.PurgeDocumentsRequest, + dict, +]) +def test_purge_documents_rest(request_type): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.purge_documents(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_purge_documents_rest_required_fields(request_type=purge_config.PurgeDocumentsRequest): + transport_class = transports.DocumentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["filter"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).purge_documents._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + jsonified_request["filter"] = 'filter_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).purge_documents._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "filter" in jsonified_request + assert jsonified_request["filter"] == 'filter_value' + + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.purge_documents(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_purge_documents_rest_unset_required_fields(): + transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.purge_documents._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "filter", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_purge_documents_rest_interceptors(null_interceptor): + transport = transports.DocumentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), + ) + client = DocumentServiceClient(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.DocumentServiceRestInterceptor, "post_purge_documents") as post, \ + mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_purge_documents") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = purge_config.PurgeDocumentsRequest.pb(purge_config.PurgeDocumentsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = purge_config.PurgeDocumentsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.purge_documents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_purge_documents_rest_bad_request(transport: str = 'rest', request_type=purge_config.PurgeDocumentsRequest): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.purge_documents(request) + + +def test_purge_documents_rest_error(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.DocumentServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.DocumentServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DocumentServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.DocumentServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DocumentServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DocumentServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.DocumentServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DocumentServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.DocumentServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = DocumentServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.DocumentServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.DocumentServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.DocumentServiceGrpcTransport, + transports.DocumentServiceGrpcAsyncIOTransport, + transports.DocumentServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = DocumentServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.DocumentServiceGrpcTransport, + ) + +def test_document_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.DocumentServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_document_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.discoveryengine_v1alpha.services.document_service.transports.DocumentServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.DocumentServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_document', + 'list_documents', + 'create_document', + 'update_document', + 'delete_document', + 'import_documents', + 'purge_documents', + 'get_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_document_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.discoveryengine_v1alpha.services.document_service.transports.DocumentServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DocumentServiceTransport( + 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_document_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.discoveryengine_v1alpha.services.document_service.transports.DocumentServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DocumentServiceTransport() + adc.assert_called_once() + + +def test_document_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) + DocumentServiceClient() + 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.DocumentServiceGrpcTransport, + transports.DocumentServiceGrpcAsyncIOTransport, + ], +) +def test_document_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.DocumentServiceGrpcTransport, + transports.DocumentServiceGrpcAsyncIOTransport, + transports.DocumentServiceRestTransport, + ], +) +def test_document_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.DocumentServiceGrpcTransport, grpc_helpers), + (transports.DocumentServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_document_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.DocumentServiceGrpcTransport, transports.DocumentServiceGrpcAsyncIOTransport]) +def test_document_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_document_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.DocumentServiceRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_document_service_rest_lro_client(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_document_service_host_no_port(transport_name): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_document_service_host_with_port(transport_name): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_document_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = DocumentServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = DocumentServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_document._session + session2 = client2.transport.get_document._session + assert session1 != session2 + session1 = client1.transport.list_documents._session + session2 = client2.transport.list_documents._session + assert session1 != session2 + session1 = client1.transport.create_document._session + session2 = client2.transport.create_document._session + assert session1 != session2 + session1 = client1.transport.update_document._session + session2 = client2.transport.update_document._session + assert session1 != session2 + session1 = client1.transport.delete_document._session + session2 = client2.transport.delete_document._session + assert session1 != session2 + session1 = client1.transport.import_documents._session + session2 = client2.transport.import_documents._session + assert session1 != session2 + session1 = client1.transport.purge_documents._session + session2 = client2.transport.purge_documents._session + assert session1 != session2 +def test_document_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DocumentServiceGrpcTransport( + 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_document_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DocumentServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.DocumentServiceGrpcTransport, transports.DocumentServiceGrpcAsyncIOTransport]) +def test_document_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.DocumentServiceGrpcTransport, transports.DocumentServiceGrpcAsyncIOTransport]) +def test_document_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_document_service_grpc_lro_client(): + client = DocumentServiceClient( + 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_document_service_grpc_lro_async_client(): + client = DocumentServiceAsyncClient( + 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_branch_path(): + project = "squid" + location = "clam" + data_store = "whelk" + branch = "octopus" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}".format(project=project, location=location, data_store=data_store, branch=branch, ) + actual = DocumentServiceClient.branch_path(project, location, data_store, branch) + assert expected == actual + + +def test_parse_branch_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "data_store": "cuttlefish", + "branch": "mussel", + } + path = DocumentServiceClient.branch_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentServiceClient.parse_branch_path(path) + assert expected == actual + +def test_document_path(): + project = "winkle" + location = "nautilus" + data_store = "scallop" + branch = "abalone" + document = "squid" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) + actual = DocumentServiceClient.document_path(project, location, data_store, branch, document) + assert expected == actual + + +def test_parse_document_path(): + expected = { + "project": "clam", + "location": "whelk", + "data_store": "octopus", + "branch": "oyster", + "document": "nudibranch", + } + path = DocumentServiceClient.document_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentServiceClient.parse_document_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = DocumentServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = DocumentServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = DocumentServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = DocumentServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = DocumentServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = DocumentServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = DocumentServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = DocumentServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = DocumentServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = DocumentServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentServiceClient.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.DocumentServiceTransport, '_prep_wrapped_messages') as prep: + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.DocumentServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = DocumentServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_get_operation(transport: str = "grpc"): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc"): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DocumentServiceClient( + 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 = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc"): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DocumentServiceClient( + 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 = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = DocumentServiceClient( + 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", [ + (DocumentServiceClient, transports.DocumentServiceGrpcTransport), + (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_engine_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_engine_service.py new file mode 100644 index 000000000000..009616760cdc --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_engine_service.py @@ -0,0 +1,5927 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.discoveryengine_v1alpha.services.engine_service import EngineServiceAsyncClient +from google.cloud.discoveryengine_v1alpha.services.engine_service import EngineServiceClient +from google.cloud.discoveryengine_v1alpha.services.engine_service import pagers +from google.cloud.discoveryengine_v1alpha.services.engine_service import transports +from google.cloud.discoveryengine_v1alpha.types import common +from google.cloud.discoveryengine_v1alpha.types import engine +from google.cloud.discoveryengine_v1alpha.types import engine as gcd_engine +from google.cloud.discoveryengine_v1alpha.types import engine_service +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert EngineServiceClient._get_default_mtls_endpoint(None) is None + assert EngineServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert EngineServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert EngineServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert EngineServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert EngineServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (EngineServiceClient, "grpc"), + (EngineServiceAsyncClient, "grpc_asyncio"), + (EngineServiceClient, "rest"), +]) +def test_engine_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.EngineServiceGrpcTransport, "grpc"), + (transports.EngineServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.EngineServiceRestTransport, "rest"), +]) +def test_engine_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", [ + (EngineServiceClient, "grpc"), + (EngineServiceAsyncClient, "grpc_asyncio"), + (EngineServiceClient, "rest"), +]) +def test_engine_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +def test_engine_service_client_get_transport_class(): + transport = EngineServiceClient.get_transport_class() + available_transports = [ + transports.EngineServiceGrpcTransport, + transports.EngineServiceRestTransport, + ] + assert transport in available_transports + + transport = EngineServiceClient.get_transport_class("grpc") + assert transport == transports.EngineServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (EngineServiceClient, transports.EngineServiceGrpcTransport, "grpc"), + (EngineServiceAsyncClient, transports.EngineServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (EngineServiceClient, transports.EngineServiceRestTransport, "rest"), +]) +@mock.patch.object(EngineServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EngineServiceClient)) +@mock.patch.object(EngineServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EngineServiceAsyncClient)) +def test_engine_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(EngineServiceClient, '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(EngineServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (EngineServiceClient, transports.EngineServiceGrpcTransport, "grpc", "true"), + (EngineServiceAsyncClient, transports.EngineServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (EngineServiceClient, transports.EngineServiceGrpcTransport, "grpc", "false"), + (EngineServiceAsyncClient, transports.EngineServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (EngineServiceClient, transports.EngineServiceRestTransport, "rest", "true"), + (EngineServiceClient, transports.EngineServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(EngineServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EngineServiceClient)) +@mock.patch.object(EngineServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EngineServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_engine_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 + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + EngineServiceClient, EngineServiceAsyncClient +]) +@mock.patch.object(EngineServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EngineServiceClient)) +@mock.patch.object(EngineServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EngineServiceAsyncClient)) +def test_engine_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (EngineServiceClient, transports.EngineServiceGrpcTransport, "grpc"), + (EngineServiceAsyncClient, transports.EngineServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (EngineServiceClient, transports.EngineServiceRestTransport, "rest"), +]) +def test_engine_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, + 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", [ + (EngineServiceClient, transports.EngineServiceGrpcTransport, "grpc", grpc_helpers), + (EngineServiceAsyncClient, transports.EngineServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (EngineServiceClient, transports.EngineServiceRestTransport, "rest", None), +]) +def test_engine_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, + scopes=None, + client_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_engine_service_client_client_options_from_dict(): + with mock.patch('google.cloud.discoveryengine_v1alpha.services.engine_service.transports.EngineServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = EngineServiceClient( + 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", [ + (EngineServiceClient, transports.EngineServiceGrpcTransport, "grpc", grpc_helpers), + (EngineServiceAsyncClient, transports.EngineServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_engine_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, + scopes=None, + client_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + engine_service.CreateEngineRequest, + dict, +]) +def test_create_engine(request_type, transport: str = 'grpc'): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_engine), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_engine(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == engine_service.CreateEngineRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_engine_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_engine), + '__call__') as call: + client.create_engine() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == engine_service.CreateEngineRequest() + +@pytest.mark.asyncio +async def test_create_engine_async(transport: str = 'grpc_asyncio', request_type=engine_service.CreateEngineRequest): + client = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_engine), + '__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_engine(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == engine_service.CreateEngineRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_engine_async_from_dict(): + await test_create_engine_async(request_type=dict) + + +def test_create_engine_field_headers(): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = engine_service.CreateEngineRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_engine), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_engine(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_engine_field_headers_async(): + client = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = engine_service.CreateEngineRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_engine), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_engine(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_engine_flattened(): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_engine), + '__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_engine( + parent='parent_value', + engine=gcd_engine.Engine(similar_documents_config=None), + engine_id='engine_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].engine + mock_val = gcd_engine.Engine(similar_documents_config=None) + assert arg == mock_val + arg = args[0].engine_id + mock_val = 'engine_id_value' + assert arg == mock_val + + +def test_create_engine_flattened_error(): + client = EngineServiceClient( + credentials=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_engine( + engine_service.CreateEngineRequest(), + parent='parent_value', + engine=gcd_engine.Engine(similar_documents_config=None), + engine_id='engine_id_value', + ) + +@pytest.mark.asyncio +async def test_create_engine_flattened_async(): + client = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_engine), + '__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_engine( + parent='parent_value', + engine=gcd_engine.Engine(similar_documents_config=None), + engine_id='engine_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].engine + mock_val = gcd_engine.Engine(similar_documents_config=None) + assert arg == mock_val + arg = args[0].engine_id + mock_val = 'engine_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_engine_flattened_error_async(): + client = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_engine( + engine_service.CreateEngineRequest(), + parent='parent_value', + engine=gcd_engine.Engine(similar_documents_config=None), + engine_id='engine_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + engine_service.DeleteEngineRequest, + dict, +]) +def test_delete_engine(request_type, transport: str = 'grpc'): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_engine), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_engine(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == engine_service.DeleteEngineRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_engine_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_engine), + '__call__') as call: + client.delete_engine() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == engine_service.DeleteEngineRequest() + +@pytest.mark.asyncio +async def test_delete_engine_async(transport: str = 'grpc_asyncio', request_type=engine_service.DeleteEngineRequest): + client = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_engine), + '__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_engine(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == engine_service.DeleteEngineRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_engine_async_from_dict(): + await test_delete_engine_async(request_type=dict) + + +def test_delete_engine_field_headers(): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = engine_service.DeleteEngineRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_engine), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_engine(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_engine_field_headers_async(): + client = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = engine_service.DeleteEngineRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_engine), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_engine(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_engine_flattened(): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_engine), + '__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_engine( + 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_engine_flattened_error(): + client = EngineServiceClient( + credentials=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_engine( + engine_service.DeleteEngineRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_engine_flattened_async(): + client = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_engine), + '__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_engine( + 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_engine_flattened_error_async(): + client = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_engine( + engine_service.DeleteEngineRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + engine_service.UpdateEngineRequest, + dict, +]) +def test_update_engine(request_type, transport: str = 'grpc'): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_engine), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_engine.Engine( + name='name_value', + display_name='display_name_value', + data_store_ids=['data_store_ids_value'], + solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, + industry_vertical=common.IndustryVertical.GENERIC, + ) + response = client.update_engine(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == engine_service.UpdateEngineRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_engine.Engine) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.data_store_ids == ['data_store_ids_value'] + assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION + assert response.industry_vertical == common.IndustryVertical.GENERIC + + +def test_update_engine_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_engine), + '__call__') as call: + client.update_engine() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == engine_service.UpdateEngineRequest() + +@pytest.mark.asyncio +async def test_update_engine_async(transport: str = 'grpc_asyncio', request_type=engine_service.UpdateEngineRequest): + client = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_engine), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_engine.Engine( + name='name_value', + display_name='display_name_value', + data_store_ids=['data_store_ids_value'], + solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, + industry_vertical=common.IndustryVertical.GENERIC, + )) + response = await client.update_engine(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == engine_service.UpdateEngineRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_engine.Engine) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.data_store_ids == ['data_store_ids_value'] + assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION + assert response.industry_vertical == common.IndustryVertical.GENERIC + + +@pytest.mark.asyncio +async def test_update_engine_async_from_dict(): + await test_update_engine_async(request_type=dict) + + +def test_update_engine_field_headers(): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = engine_service.UpdateEngineRequest() + + request.engine.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_engine), + '__call__') as call: + call.return_value = gcd_engine.Engine() + client.update_engine(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'engine.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_engine_field_headers_async(): + client = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = engine_service.UpdateEngineRequest() + + request.engine.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_engine), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_engine.Engine()) + await client.update_engine(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'engine.name=name_value', + ) in kw['metadata'] + + +def test_update_engine_flattened(): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_engine), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_engine.Engine() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_engine( + engine=gcd_engine.Engine(similar_documents_config=None), + 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].engine + mock_val = gcd_engine.Engine(similar_documents_config=None) + 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_engine_flattened_error(): + client = EngineServiceClient( + credentials=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_engine( + engine_service.UpdateEngineRequest(), + engine=gcd_engine.Engine(similar_documents_config=None), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_engine_flattened_async(): + client = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_engine), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_engine.Engine() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_engine.Engine()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_engine( + engine=gcd_engine.Engine(similar_documents_config=None), + 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].engine + mock_val = gcd_engine.Engine(similar_documents_config=None) + 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_engine_flattened_error_async(): + client = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_engine( + engine_service.UpdateEngineRequest(), + engine=gcd_engine.Engine(similar_documents_config=None), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + engine_service.GetEngineRequest, + dict, +]) +def test_get_engine(request_type, transport: str = 'grpc'): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_engine), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = engine.Engine( + name='name_value', + display_name='display_name_value', + data_store_ids=['data_store_ids_value'], + solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, + industry_vertical=common.IndustryVertical.GENERIC, + ) + response = client.get_engine(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == engine_service.GetEngineRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, engine.Engine) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.data_store_ids == ['data_store_ids_value'] + assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION + assert response.industry_vertical == common.IndustryVertical.GENERIC + + +def test_get_engine_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_engine), + '__call__') as call: + client.get_engine() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == engine_service.GetEngineRequest() + +@pytest.mark.asyncio +async def test_get_engine_async(transport: str = 'grpc_asyncio', request_type=engine_service.GetEngineRequest): + client = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_engine), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(engine.Engine( + name='name_value', + display_name='display_name_value', + data_store_ids=['data_store_ids_value'], + solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, + industry_vertical=common.IndustryVertical.GENERIC, + )) + response = await client.get_engine(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == engine_service.GetEngineRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, engine.Engine) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.data_store_ids == ['data_store_ids_value'] + assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION + assert response.industry_vertical == common.IndustryVertical.GENERIC + + +@pytest.mark.asyncio +async def test_get_engine_async_from_dict(): + await test_get_engine_async(request_type=dict) + + +def test_get_engine_field_headers(): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = engine_service.GetEngineRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_engine), + '__call__') as call: + call.return_value = engine.Engine() + client.get_engine(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_engine_field_headers_async(): + client = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = engine_service.GetEngineRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_engine), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(engine.Engine()) + await client.get_engine(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_engine_flattened(): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_engine), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = engine.Engine() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_engine( + 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_engine_flattened_error(): + client = EngineServiceClient( + credentials=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_engine( + engine_service.GetEngineRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_engine_flattened_async(): + client = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_engine), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = engine.Engine() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(engine.Engine()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_engine( + 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_engine_flattened_error_async(): + client = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_engine( + engine_service.GetEngineRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + engine_service.ListEnginesRequest, + dict, +]) +def test_list_engines(request_type, transport: str = 'grpc'): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_engines), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = engine_service.ListEnginesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_engines(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == engine_service.ListEnginesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEnginesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_engines_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_engines), + '__call__') as call: + client.list_engines() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == engine_service.ListEnginesRequest() + +@pytest.mark.asyncio +async def test_list_engines_async(transport: str = 'grpc_asyncio', request_type=engine_service.ListEnginesRequest): + client = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_engines), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(engine_service.ListEnginesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_engines(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == engine_service.ListEnginesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEnginesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_engines_async_from_dict(): + await test_list_engines_async(request_type=dict) + + +def test_list_engines_field_headers(): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = engine_service.ListEnginesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_engines), + '__call__') as call: + call.return_value = engine_service.ListEnginesResponse() + client.list_engines(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_engines_field_headers_async(): + client = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = engine_service.ListEnginesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_engines), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(engine_service.ListEnginesResponse()) + await client.list_engines(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_engines_flattened(): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_engines), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = engine_service.ListEnginesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_engines( + 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_engines_flattened_error(): + client = EngineServiceClient( + credentials=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_engines( + engine_service.ListEnginesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_engines_flattened_async(): + client = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_engines), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = engine_service.ListEnginesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(engine_service.ListEnginesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_engines( + 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_engines_flattened_error_async(): + client = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_engines( + engine_service.ListEnginesRequest(), + parent='parent_value', + ) + + +def test_list_engines_pager(transport_name: str = "grpc"): + client = EngineServiceClient( + 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_engines), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + engine_service.ListEnginesResponse( + engines=[ + engine.Engine(), + engine.Engine(), + engine.Engine(), + ], + next_page_token='abc', + ), + engine_service.ListEnginesResponse( + engines=[], + next_page_token='def', + ), + engine_service.ListEnginesResponse( + engines=[ + engine.Engine(), + ], + next_page_token='ghi', + ), + engine_service.ListEnginesResponse( + engines=[ + engine.Engine(), + engine.Engine(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_engines(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, engine.Engine) + for i in results) +def test_list_engines_pages(transport_name: str = "grpc"): + client = EngineServiceClient( + 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_engines), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + engine_service.ListEnginesResponse( + engines=[ + engine.Engine(), + engine.Engine(), + engine.Engine(), + ], + next_page_token='abc', + ), + engine_service.ListEnginesResponse( + engines=[], + next_page_token='def', + ), + engine_service.ListEnginesResponse( + engines=[ + engine.Engine(), + ], + next_page_token='ghi', + ), + engine_service.ListEnginesResponse( + engines=[ + engine.Engine(), + engine.Engine(), + ], + ), + RuntimeError, + ) + pages = list(client.list_engines(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_engines_async_pager(): + client = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_engines), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + engine_service.ListEnginesResponse( + engines=[ + engine.Engine(), + engine.Engine(), + engine.Engine(), + ], + next_page_token='abc', + ), + engine_service.ListEnginesResponse( + engines=[], + next_page_token='def', + ), + engine_service.ListEnginesResponse( + engines=[ + engine.Engine(), + ], + next_page_token='ghi', + ), + engine_service.ListEnginesResponse( + engines=[ + engine.Engine(), + engine.Engine(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_engines(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, engine.Engine) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_engines_async_pages(): + client = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_engines), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + engine_service.ListEnginesResponse( + engines=[ + engine.Engine(), + engine.Engine(), + engine.Engine(), + ], + next_page_token='abc', + ), + engine_service.ListEnginesResponse( + engines=[], + next_page_token='def', + ), + engine_service.ListEnginesResponse( + engines=[ + engine.Engine(), + ], + next_page_token='ghi', + ), + engine_service.ListEnginesResponse( + engines=[ + engine.Engine(), + engine.Engine(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_engines(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", [ + engine_service.PauseEngineRequest, + dict, +]) +def test_pause_engine(request_type, transport: str = 'grpc'): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.pause_engine), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = engine.Engine( + name='name_value', + display_name='display_name_value', + data_store_ids=['data_store_ids_value'], + solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, + industry_vertical=common.IndustryVertical.GENERIC, + ) + response = client.pause_engine(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == engine_service.PauseEngineRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, engine.Engine) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.data_store_ids == ['data_store_ids_value'] + assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION + assert response.industry_vertical == common.IndustryVertical.GENERIC + + +def test_pause_engine_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.pause_engine), + '__call__') as call: + client.pause_engine() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == engine_service.PauseEngineRequest() + +@pytest.mark.asyncio +async def test_pause_engine_async(transport: str = 'grpc_asyncio', request_type=engine_service.PauseEngineRequest): + client = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.pause_engine), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(engine.Engine( + name='name_value', + display_name='display_name_value', + data_store_ids=['data_store_ids_value'], + solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, + industry_vertical=common.IndustryVertical.GENERIC, + )) + response = await client.pause_engine(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == engine_service.PauseEngineRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, engine.Engine) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.data_store_ids == ['data_store_ids_value'] + assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION + assert response.industry_vertical == common.IndustryVertical.GENERIC + + +@pytest.mark.asyncio +async def test_pause_engine_async_from_dict(): + await test_pause_engine_async(request_type=dict) + + +def test_pause_engine_field_headers(): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = engine_service.PauseEngineRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.pause_engine), + '__call__') as call: + call.return_value = engine.Engine() + client.pause_engine(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_pause_engine_field_headers_async(): + client = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = engine_service.PauseEngineRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.pause_engine), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(engine.Engine()) + await client.pause_engine(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_pause_engine_flattened(): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.pause_engine), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = engine.Engine() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.pause_engine( + 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_pause_engine_flattened_error(): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.pause_engine( + engine_service.PauseEngineRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_pause_engine_flattened_async(): + client = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.pause_engine), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = engine.Engine() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(engine.Engine()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.pause_engine( + 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_pause_engine_flattened_error_async(): + client = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.pause_engine( + engine_service.PauseEngineRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + engine_service.ResumeEngineRequest, + dict, +]) +def test_resume_engine(request_type, transport: str = 'grpc'): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resume_engine), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = engine.Engine( + name='name_value', + display_name='display_name_value', + data_store_ids=['data_store_ids_value'], + solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, + industry_vertical=common.IndustryVertical.GENERIC, + ) + response = client.resume_engine(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == engine_service.ResumeEngineRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, engine.Engine) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.data_store_ids == ['data_store_ids_value'] + assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION + assert response.industry_vertical == common.IndustryVertical.GENERIC + + +def test_resume_engine_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resume_engine), + '__call__') as call: + client.resume_engine() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == engine_service.ResumeEngineRequest() + +@pytest.mark.asyncio +async def test_resume_engine_async(transport: str = 'grpc_asyncio', request_type=engine_service.ResumeEngineRequest): + client = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resume_engine), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(engine.Engine( + name='name_value', + display_name='display_name_value', + data_store_ids=['data_store_ids_value'], + solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, + industry_vertical=common.IndustryVertical.GENERIC, + )) + response = await client.resume_engine(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == engine_service.ResumeEngineRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, engine.Engine) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.data_store_ids == ['data_store_ids_value'] + assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION + assert response.industry_vertical == common.IndustryVertical.GENERIC + + +@pytest.mark.asyncio +async def test_resume_engine_async_from_dict(): + await test_resume_engine_async(request_type=dict) + + +def test_resume_engine_field_headers(): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = engine_service.ResumeEngineRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resume_engine), + '__call__') as call: + call.return_value = engine.Engine() + client.resume_engine(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_resume_engine_field_headers_async(): + client = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = engine_service.ResumeEngineRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resume_engine), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(engine.Engine()) + await client.resume_engine(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_resume_engine_flattened(): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resume_engine), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = engine.Engine() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.resume_engine( + 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_resume_engine_flattened_error(): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.resume_engine( + engine_service.ResumeEngineRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_resume_engine_flattened_async(): + client = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.resume_engine), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = engine.Engine() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(engine.Engine()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.resume_engine( + 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_resume_engine_flattened_error_async(): + client = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.resume_engine( + engine_service.ResumeEngineRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + engine_service.TuneEngineRequest, + dict, +]) +def test_tune_engine(request_type, transport: str = 'grpc'): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.tune_engine), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.tune_engine(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == engine_service.TuneEngineRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_tune_engine_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.tune_engine), + '__call__') as call: + client.tune_engine() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == engine_service.TuneEngineRequest() + +@pytest.mark.asyncio +async def test_tune_engine_async(transport: str = 'grpc_asyncio', request_type=engine_service.TuneEngineRequest): + client = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.tune_engine), + '__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.tune_engine(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == engine_service.TuneEngineRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_tune_engine_async_from_dict(): + await test_tune_engine_async(request_type=dict) + + +def test_tune_engine_field_headers(): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = engine_service.TuneEngineRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.tune_engine), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.tune_engine(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_tune_engine_field_headers_async(): + client = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = engine_service.TuneEngineRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.tune_engine), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.tune_engine(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_tune_engine_flattened(): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.tune_engine), + '__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.tune_engine( + 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_tune_engine_flattened_error(): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.tune_engine( + engine_service.TuneEngineRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_tune_engine_flattened_async(): + client = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.tune_engine), + '__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.tune_engine( + 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_tune_engine_flattened_error_async(): + client = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.tune_engine( + engine_service.TuneEngineRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + engine_service.CreateEngineRequest, + dict, +]) +def test_create_engine_rest(request_type): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/collections/sample3'} + request_init["engine"] = {'similar_documents_config': {}, 'chat_engine_config': {'agent_creation_config': {'business': 'business_value', 'default_language_code': 'default_language_code_value', 'time_zone': 'time_zone_value'}, 'dialogflow_agent_to_link': 'dialogflow_agent_to_link_value'}, 'search_engine_config': {'search_tier': 1, 'search_add_ons': [1]}, 'media_recommendation_engine_config': {'type_': 'type__value', 'optimization_objective': 'optimization_objective_value', 'optimization_objective_config': {'target_field': 'target_field_value', 'target_field_value_float': 0.2523}, 'training_state': 1}, 'recommendation_metadata': {'serving_state': 1, 'data_state': 1, 'last_tune_time': {'seconds': 751, 'nanos': 543}, 'tuning_operation': 'tuning_operation_value'}, 'chat_engine_metadata': {'dialogflow_agent': 'dialogflow_agent_value'}, 'name': 'name_value', 'display_name': 'display_name_value', 'create_time': {}, 'update_time': {}, 'data_store_ids': ['data_store_ids_value1', 'data_store_ids_value2'], 'solution_type': 1, 'industry_vertical': 1, 'common_config': {'company_name': 'company_name_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 = engine_service.CreateEngineRequest.meta.fields["engine"] + + 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["engine"].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["engine"][field])): + del request_init["engine"][field][i][subfield] + else: + del request_init["engine"][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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_engine(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_engine_rest_required_fields(request_type=engine_service.CreateEngineRequest): + transport_class = transports.EngineServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["engine_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "engineId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_engine._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "engineId" in jsonified_request + assert jsonified_request["engineId"] == request_init["engine_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["engineId"] = 'engine_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_engine._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("engine_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "engineId" in jsonified_request + assert jsonified_request["engineId"] == 'engine_id_value' + + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_engine(request) + + expected_params = [ + ( + "engineId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_engine_rest_unset_required_fields(): + transport = transports.EngineServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_engine._get_unset_required_fields({}) + assert set(unset_fields) == (set(("engineId", )) & set(("parent", "engine", "engineId", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_engine_rest_interceptors(null_interceptor): + transport = transports.EngineServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EngineServiceRestInterceptor(), + ) + client = EngineServiceClient(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.EngineServiceRestInterceptor, "post_create_engine") as post, \ + mock.patch.object(transports.EngineServiceRestInterceptor, "pre_create_engine") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = engine_service.CreateEngineRequest.pb(engine_service.CreateEngineRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = engine_service.CreateEngineRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_engine(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_engine_rest_bad_request(transport: str = 'rest', request_type=engine_service.CreateEngineRequest): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/collections/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_engine(request) + + +def test_create_engine_rest_flattened(): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.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/collections/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + engine=gcd_engine.Engine(similar_documents_config=None), + engine_id='engine_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_engine(**mock_args) + + # Establish that the underlying call 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/*/collections/*}/engines" % client.transport._host, args[1]) + + +def test_create_engine_rest_flattened_error(transport: str = 'rest'): + client = EngineServiceClient( + credentials=ga_credentials.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_engine( + engine_service.CreateEngineRequest(), + parent='parent_value', + engine=gcd_engine.Engine(similar_documents_config=None), + engine_id='engine_id_value', + ) + + +def test_create_engine_rest_error(): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + engine_service.DeleteEngineRequest, + dict, +]) +def test_delete_engine_rest(request_type): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/engines/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_engine(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_engine_rest_required_fields(request_type=engine_service.DeleteEngineRequest): + transport_class = transports.EngineServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_engine._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_engine._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_engine(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_engine_rest_unset_required_fields(): + transport = transports.EngineServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_engine._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_engine_rest_interceptors(null_interceptor): + transport = transports.EngineServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EngineServiceRestInterceptor(), + ) + client = EngineServiceClient(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.EngineServiceRestInterceptor, "post_delete_engine") as post, \ + mock.patch.object(transports.EngineServiceRestInterceptor, "pre_delete_engine") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = engine_service.DeleteEngineRequest.pb(engine_service.DeleteEngineRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = engine_service.DeleteEngineRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_engine(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_engine_rest_bad_request(transport: str = 'rest', request_type=engine_service.DeleteEngineRequest): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/engines/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_engine(request) + + +def test_delete_engine_rest_flattened(): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.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/collections/sample3/engines/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_engine(**mock_args) + + # Establish that the underlying call 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/*/collections/*/engines/*}" % client.transport._host, args[1]) + + +def test_delete_engine_rest_flattened_error(transport: str = 'rest'): + client = EngineServiceClient( + credentials=ga_credentials.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_engine( + engine_service.DeleteEngineRequest(), + name='name_value', + ) + + +def test_delete_engine_rest_error(): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + engine_service.UpdateEngineRequest, + dict, +]) +def test_update_engine_rest(request_type): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'engine': {'name': 'projects/sample1/locations/sample2/collections/sample3/engines/sample4'}} + request_init["engine"] = {'similar_documents_config': {}, 'chat_engine_config': {'agent_creation_config': {'business': 'business_value', 'default_language_code': 'default_language_code_value', 'time_zone': 'time_zone_value'}, 'dialogflow_agent_to_link': 'dialogflow_agent_to_link_value'}, 'search_engine_config': {'search_tier': 1, 'search_add_ons': [1]}, 'media_recommendation_engine_config': {'type_': 'type__value', 'optimization_objective': 'optimization_objective_value', 'optimization_objective_config': {'target_field': 'target_field_value', 'target_field_value_float': 0.2523}, 'training_state': 1}, 'recommendation_metadata': {'serving_state': 1, 'data_state': 1, 'last_tune_time': {'seconds': 751, 'nanos': 543}, 'tuning_operation': 'tuning_operation_value'}, 'chat_engine_metadata': {'dialogflow_agent': 'dialogflow_agent_value'}, 'name': 'projects/sample1/locations/sample2/collections/sample3/engines/sample4', 'display_name': 'display_name_value', 'create_time': {}, 'update_time': {}, 'data_store_ids': ['data_store_ids_value1', 'data_store_ids_value2'], 'solution_type': 1, 'industry_vertical': 1, 'common_config': {'company_name': 'company_name_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 = engine_service.UpdateEngineRequest.meta.fields["engine"] + + 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["engine"].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["engine"][field])): + del request_init["engine"][field][i][subfield] + else: + del request_init["engine"][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 = gcd_engine.Engine( + name='name_value', + display_name='display_name_value', + data_store_ids=['data_store_ids_value'], + solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, + industry_vertical=common.IndustryVertical.GENERIC, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcd_engine.Engine.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_engine(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_engine.Engine) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.data_store_ids == ['data_store_ids_value'] + assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION + assert response.industry_vertical == common.IndustryVertical.GENERIC + + +def test_update_engine_rest_required_fields(request_type=engine_service.UpdateEngineRequest): + transport_class = transports.EngineServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_engine._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_engine._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcd_engine.Engine() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcd_engine.Engine.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_engine(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_engine_rest_unset_required_fields(): + transport = transports.EngineServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_engine._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("engine", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_engine_rest_interceptors(null_interceptor): + transport = transports.EngineServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EngineServiceRestInterceptor(), + ) + client = EngineServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.EngineServiceRestInterceptor, "post_update_engine") as post, \ + mock.patch.object(transports.EngineServiceRestInterceptor, "pre_update_engine") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = engine_service.UpdateEngineRequest.pb(engine_service.UpdateEngineRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcd_engine.Engine.to_json(gcd_engine.Engine()) + + request = engine_service.UpdateEngineRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcd_engine.Engine() + + client.update_engine(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_engine_rest_bad_request(transport: str = 'rest', request_type=engine_service.UpdateEngineRequest): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'engine': {'name': 'projects/sample1/locations/sample2/collections/sample3/engines/sample4'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_engine(request) + + +def test_update_engine_rest_flattened(): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcd_engine.Engine() + + # get arguments that satisfy an http rule for this method + sample_request = {'engine': {'name': 'projects/sample1/locations/sample2/collections/sample3/engines/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + engine=gcd_engine.Engine(similar_documents_config=None), + 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 = gcd_engine.Engine.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_engine(**mock_args) + + # Establish that the underlying call 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/{engine.name=projects/*/locations/*/collections/*/engines/*}" % client.transport._host, args[1]) + + +def test_update_engine_rest_flattened_error(transport: str = 'rest'): + client = EngineServiceClient( + credentials=ga_credentials.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_engine( + engine_service.UpdateEngineRequest(), + engine=gcd_engine.Engine(similar_documents_config=None), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_engine_rest_error(): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + engine_service.GetEngineRequest, + dict, +]) +def test_get_engine_rest(request_type): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/engines/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 = engine.Engine( + name='name_value', + display_name='display_name_value', + data_store_ids=['data_store_ids_value'], + solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, + industry_vertical=common.IndustryVertical.GENERIC, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = engine.Engine.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_engine(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, engine.Engine) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.data_store_ids == ['data_store_ids_value'] + assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION + assert response.industry_vertical == common.IndustryVertical.GENERIC + + +def test_get_engine_rest_required_fields(request_type=engine_service.GetEngineRequest): + transport_class = transports.EngineServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_engine._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_engine._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = engine.Engine() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = engine.Engine.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_engine(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_engine_rest_unset_required_fields(): + transport = transports.EngineServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_engine._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_engine_rest_interceptors(null_interceptor): + transport = transports.EngineServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EngineServiceRestInterceptor(), + ) + client = EngineServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.EngineServiceRestInterceptor, "post_get_engine") as post, \ + mock.patch.object(transports.EngineServiceRestInterceptor, "pre_get_engine") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = engine_service.GetEngineRequest.pb(engine_service.GetEngineRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = engine.Engine.to_json(engine.Engine()) + + request = engine_service.GetEngineRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = engine.Engine() + + client.get_engine(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_engine_rest_bad_request(transport: str = 'rest', request_type=engine_service.GetEngineRequest): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/engines/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_engine(request) + + +def test_get_engine_rest_flattened(): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = engine.Engine() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/collections/sample3/engines/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 = engine.Engine.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_engine(**mock_args) + + # Establish that the underlying call 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/*/collections/*/engines/*}" % client.transport._host, args[1]) + + +def test_get_engine_rest_flattened_error(transport: str = 'rest'): + client = EngineServiceClient( + credentials=ga_credentials.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_engine( + engine_service.GetEngineRequest(), + name='name_value', + ) + + +def test_get_engine_rest_error(): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + engine_service.ListEnginesRequest, + dict, +]) +def test_list_engines_rest(request_type): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/collections/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 = engine_service.ListEnginesResponse( + next_page_token='next_page_token_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 = engine_service.ListEnginesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_engines(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEnginesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_engines_rest_required_fields(request_type=engine_service.ListEnginesRequest): + transport_class = transports.EngineServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_engines._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_engines._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = engine_service.ListEnginesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = engine_service.ListEnginesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_engines(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_engines_rest_unset_required_fields(): + transport = transports.EngineServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_engines._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_engines_rest_interceptors(null_interceptor): + transport = transports.EngineServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EngineServiceRestInterceptor(), + ) + client = EngineServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.EngineServiceRestInterceptor, "post_list_engines") as post, \ + mock.patch.object(transports.EngineServiceRestInterceptor, "pre_list_engines") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = engine_service.ListEnginesRequest.pb(engine_service.ListEnginesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = engine_service.ListEnginesResponse.to_json(engine_service.ListEnginesResponse()) + + request = engine_service.ListEnginesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = engine_service.ListEnginesResponse() + + client.list_engines(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_engines_rest_bad_request(transport: str = 'rest', request_type=engine_service.ListEnginesRequest): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/collections/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_engines(request) + + +def test_list_engines_rest_flattened(): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = engine_service.ListEnginesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/collections/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 = engine_service.ListEnginesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_engines(**mock_args) + + # Establish that the underlying call 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/*/collections/*}/engines" % client.transport._host, args[1]) + + +def test_list_engines_rest_flattened_error(transport: str = 'rest'): + client = EngineServiceClient( + credentials=ga_credentials.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_engines( + engine_service.ListEnginesRequest(), + parent='parent_value', + ) + + +def test_list_engines_rest_pager(transport: str = 'rest'): + client = EngineServiceClient( + 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 = ( + engine_service.ListEnginesResponse( + engines=[ + engine.Engine(), + engine.Engine(), + engine.Engine(), + ], + next_page_token='abc', + ), + engine_service.ListEnginesResponse( + engines=[], + next_page_token='def', + ), + engine_service.ListEnginesResponse( + engines=[ + engine.Engine(), + ], + next_page_token='ghi', + ), + engine_service.ListEnginesResponse( + engines=[ + engine.Engine(), + engine.Engine(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(engine_service.ListEnginesResponse.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/collections/sample3'} + + pager = client.list_engines(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, engine.Engine) + for i in results) + + pages = list(client.list_engines(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + engine_service.PauseEngineRequest, + dict, +]) +def test_pause_engine_rest(request_type): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/engines/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 = engine.Engine( + name='name_value', + display_name='display_name_value', + data_store_ids=['data_store_ids_value'], + solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, + industry_vertical=common.IndustryVertical.GENERIC, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = engine.Engine.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.pause_engine(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, engine.Engine) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.data_store_ids == ['data_store_ids_value'] + assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION + assert response.industry_vertical == common.IndustryVertical.GENERIC + + +def test_pause_engine_rest_required_fields(request_type=engine_service.PauseEngineRequest): + transport_class = transports.EngineServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).pause_engine._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).pause_engine._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = engine.Engine() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = engine.Engine.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.pause_engine(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_pause_engine_rest_unset_required_fields(): + transport = transports.EngineServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.pause_engine._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_pause_engine_rest_interceptors(null_interceptor): + transport = transports.EngineServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EngineServiceRestInterceptor(), + ) + client = EngineServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.EngineServiceRestInterceptor, "post_pause_engine") as post, \ + mock.patch.object(transports.EngineServiceRestInterceptor, "pre_pause_engine") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = engine_service.PauseEngineRequest.pb(engine_service.PauseEngineRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = engine.Engine.to_json(engine.Engine()) + + request = engine_service.PauseEngineRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = engine.Engine() + + client.pause_engine(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_pause_engine_rest_bad_request(transport: str = 'rest', request_type=engine_service.PauseEngineRequest): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/engines/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.pause_engine(request) + + +def test_pause_engine_rest_flattened(): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = engine.Engine() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/collections/sample3/engines/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 = engine.Engine.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.pause_engine(**mock_args) + + # Establish that the underlying call 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/*/collections/*/engines/*}:pause" % client.transport._host, args[1]) + + +def test_pause_engine_rest_flattened_error(transport: str = 'rest'): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.pause_engine( + engine_service.PauseEngineRequest(), + name='name_value', + ) + + +def test_pause_engine_rest_error(): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + engine_service.ResumeEngineRequest, + dict, +]) +def test_resume_engine_rest(request_type): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/engines/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 = engine.Engine( + name='name_value', + display_name='display_name_value', + data_store_ids=['data_store_ids_value'], + solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, + industry_vertical=common.IndustryVertical.GENERIC, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = engine.Engine.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.resume_engine(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, engine.Engine) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.data_store_ids == ['data_store_ids_value'] + assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION + assert response.industry_vertical == common.IndustryVertical.GENERIC + + +def test_resume_engine_rest_required_fields(request_type=engine_service.ResumeEngineRequest): + transport_class = transports.EngineServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).resume_engine._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).resume_engine._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = engine.Engine() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = engine.Engine.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.resume_engine(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_resume_engine_rest_unset_required_fields(): + transport = transports.EngineServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.resume_engine._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_resume_engine_rest_interceptors(null_interceptor): + transport = transports.EngineServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EngineServiceRestInterceptor(), + ) + client = EngineServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.EngineServiceRestInterceptor, "post_resume_engine") as post, \ + mock.patch.object(transports.EngineServiceRestInterceptor, "pre_resume_engine") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = engine_service.ResumeEngineRequest.pb(engine_service.ResumeEngineRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = engine.Engine.to_json(engine.Engine()) + + request = engine_service.ResumeEngineRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = engine.Engine() + + client.resume_engine(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_resume_engine_rest_bad_request(transport: str = 'rest', request_type=engine_service.ResumeEngineRequest): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/engines/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.resume_engine(request) + + +def test_resume_engine_rest_flattened(): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = engine.Engine() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/collections/sample3/engines/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 = engine.Engine.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.resume_engine(**mock_args) + + # Establish that the underlying call 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/*/collections/*/engines/*}:resume" % client.transport._host, args[1]) + + +def test_resume_engine_rest_flattened_error(transport: str = 'rest'): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.resume_engine( + engine_service.ResumeEngineRequest(), + name='name_value', + ) + + +def test_resume_engine_rest_error(): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + engine_service.TuneEngineRequest, + dict, +]) +def test_tune_engine_rest(request_type): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/engines/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.tune_engine(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_tune_engine_rest_required_fields(request_type=engine_service.TuneEngineRequest): + transport_class = transports.EngineServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).tune_engine._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).tune_engine._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.tune_engine(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_tune_engine_rest_unset_required_fields(): + transport = transports.EngineServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.tune_engine._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_tune_engine_rest_interceptors(null_interceptor): + transport = transports.EngineServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EngineServiceRestInterceptor(), + ) + client = EngineServiceClient(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.EngineServiceRestInterceptor, "post_tune_engine") as post, \ + mock.patch.object(transports.EngineServiceRestInterceptor, "pre_tune_engine") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = engine_service.TuneEngineRequest.pb(engine_service.TuneEngineRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = engine_service.TuneEngineRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.tune_engine(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_tune_engine_rest_bad_request(transport: str = 'rest', request_type=engine_service.TuneEngineRequest): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/engines/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.tune_engine(request) + + +def test_tune_engine_rest_flattened(): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.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/collections/sample3/engines/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.tune_engine(**mock_args) + + # Establish that the underlying call 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/*/collections/*/engines/*}:tune" % client.transport._host, args[1]) + + +def test_tune_engine_rest_flattened_error(transport: str = 'rest'): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.tune_engine( + engine_service.TuneEngineRequest(), + name='name_value', + ) + + +def test_tune_engine_rest_error(): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.EngineServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.EngineServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EngineServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.EngineServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = EngineServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = EngineServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.EngineServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EngineServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.EngineServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = EngineServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.EngineServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.EngineServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.EngineServiceGrpcTransport, + transports.EngineServiceGrpcAsyncIOTransport, + transports.EngineServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = EngineServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.EngineServiceGrpcTransport, + ) + +def test_engine_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.EngineServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_engine_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.discoveryengine_v1alpha.services.engine_service.transports.EngineServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.EngineServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_engine', + 'delete_engine', + 'update_engine', + 'get_engine', + 'list_engines', + 'pause_engine', + 'resume_engine', + 'tune_engine', + 'get_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_engine_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.discoveryengine_v1alpha.services.engine_service.transports.EngineServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EngineServiceTransport( + 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_engine_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.discoveryengine_v1alpha.services.engine_service.transports.EngineServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EngineServiceTransport() + adc.assert_called_once() + + +def test_engine_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) + EngineServiceClient() + 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.EngineServiceGrpcTransport, + transports.EngineServiceGrpcAsyncIOTransport, + ], +) +def test_engine_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.EngineServiceGrpcTransport, + transports.EngineServiceGrpcAsyncIOTransport, + transports.EngineServiceRestTransport, + ], +) +def test_engine_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.EngineServiceGrpcTransport, grpc_helpers), + (transports.EngineServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_engine_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.EngineServiceGrpcTransport, transports.EngineServiceGrpcAsyncIOTransport]) +def test_engine_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_engine_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.EngineServiceRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_engine_service_rest_lro_client(): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_engine_service_host_no_port(transport_name): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_engine_service_host_with_port(transport_name): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_engine_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = EngineServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = EngineServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_engine._session + session2 = client2.transport.create_engine._session + assert session1 != session2 + session1 = client1.transport.delete_engine._session + session2 = client2.transport.delete_engine._session + assert session1 != session2 + session1 = client1.transport.update_engine._session + session2 = client2.transport.update_engine._session + assert session1 != session2 + session1 = client1.transport.get_engine._session + session2 = client2.transport.get_engine._session + assert session1 != session2 + session1 = client1.transport.list_engines._session + session2 = client2.transport.list_engines._session + assert session1 != session2 + session1 = client1.transport.pause_engine._session + session2 = client2.transport.pause_engine._session + assert session1 != session2 + session1 = client1.transport.resume_engine._session + session2 = client2.transport.resume_engine._session + assert session1 != session2 + session1 = client1.transport.tune_engine._session + session2 = client2.transport.tune_engine._session + assert session1 != session2 +def test_engine_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EngineServiceGrpcTransport( + 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_engine_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EngineServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.EngineServiceGrpcTransport, transports.EngineServiceGrpcAsyncIOTransport]) +def test_engine_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.EngineServiceGrpcTransport, transports.EngineServiceGrpcAsyncIOTransport]) +def test_engine_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_engine_service_grpc_lro_client(): + client = EngineServiceClient( + 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_engine_service_grpc_lro_async_client(): + client = EngineServiceAsyncClient( + 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_collection_path(): + project = "squid" + location = "clam" + collection = "whelk" + expected = "projects/{project}/locations/{location}/collections/{collection}".format(project=project, location=location, collection=collection, ) + actual = EngineServiceClient.collection_path(project, location, collection) + assert expected == actual + + +def test_parse_collection_path(): + expected = { + "project": "octopus", + "location": "oyster", + "collection": "nudibranch", + } + path = EngineServiceClient.collection_path(**expected) + + # Check that the path construction is reversible. + actual = EngineServiceClient.parse_collection_path(path) + assert expected == actual + +def test_engine_path(): + project = "cuttlefish" + location = "mussel" + collection = "winkle" + engine = "nautilus" + expected = "projects/{project}/locations/{location}/collections/{collection}/engines/{engine}".format(project=project, location=location, collection=collection, engine=engine, ) + actual = EngineServiceClient.engine_path(project, location, collection, engine) + assert expected == actual + + +def test_parse_engine_path(): + expected = { + "project": "scallop", + "location": "abalone", + "collection": "squid", + "engine": "clam", + } + path = EngineServiceClient.engine_path(**expected) + + # Check that the path construction is reversible. + actual = EngineServiceClient.parse_engine_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = EngineServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = EngineServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = EngineServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = EngineServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = EngineServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = EngineServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = EngineServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = EngineServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = EngineServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = EngineServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = EngineServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = EngineServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = EngineServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = EngineServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = EngineServiceClient.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.EngineServiceTransport, '_prep_wrapped_messages') as prep: + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.EngineServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = EngineServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_get_operation(transport: str = "grpc"): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc"): + client = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = EngineServiceClient( + 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 = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc"): + client = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = EngineServiceClient( + 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 = EngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = EngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = EngineServiceClient( + 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", [ + (EngineServiceClient, transports.EngineServiceGrpcTransport), + (EngineServiceAsyncClient, transports.EngineServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_recommendation_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_recommendation_service.py new file mode 100644 index 000000000000..1919c3b20e9c --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_recommendation_service.py @@ -0,0 +1,1952 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.discoveryengine_v1alpha.services.recommendation_service import RecommendationServiceAsyncClient +from google.cloud.discoveryengine_v1alpha.services.recommendation_service import RecommendationServiceClient +from google.cloud.discoveryengine_v1alpha.services.recommendation_service import transports +from google.cloud.discoveryengine_v1alpha.types import common +from google.cloud.discoveryengine_v1alpha.types import recommendation_service +from google.cloud.discoveryengine_v1alpha.types import user_event +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert RecommendationServiceClient._get_default_mtls_endpoint(None) is None + assert RecommendationServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert RecommendationServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert RecommendationServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert RecommendationServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert RecommendationServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (RecommendationServiceClient, "grpc"), + (RecommendationServiceAsyncClient, "grpc_asyncio"), + (RecommendationServiceClient, "rest"), +]) +def test_recommendation_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.RecommendationServiceGrpcTransport, "grpc"), + (transports.RecommendationServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.RecommendationServiceRestTransport, "rest"), +]) +def test_recommendation_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", [ + (RecommendationServiceClient, "grpc"), + (RecommendationServiceAsyncClient, "grpc_asyncio"), + (RecommendationServiceClient, "rest"), +]) +def test_recommendation_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +def test_recommendation_service_client_get_transport_class(): + transport = RecommendationServiceClient.get_transport_class() + available_transports = [ + transports.RecommendationServiceGrpcTransport, + transports.RecommendationServiceRestTransport, + ] + assert transport in available_transports + + transport = RecommendationServiceClient.get_transport_class("grpc") + assert transport == transports.RecommendationServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (RecommendationServiceClient, transports.RecommendationServiceGrpcTransport, "grpc"), + (RecommendationServiceAsyncClient, transports.RecommendationServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (RecommendationServiceClient, transports.RecommendationServiceRestTransport, "rest"), +]) +@mock.patch.object(RecommendationServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RecommendationServiceClient)) +@mock.patch.object(RecommendationServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RecommendationServiceAsyncClient)) +def test_recommendation_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(RecommendationServiceClient, '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(RecommendationServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (RecommendationServiceClient, transports.RecommendationServiceGrpcTransport, "grpc", "true"), + (RecommendationServiceAsyncClient, transports.RecommendationServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (RecommendationServiceClient, transports.RecommendationServiceGrpcTransport, "grpc", "false"), + (RecommendationServiceAsyncClient, transports.RecommendationServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (RecommendationServiceClient, transports.RecommendationServiceRestTransport, "rest", "true"), + (RecommendationServiceClient, transports.RecommendationServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(RecommendationServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RecommendationServiceClient)) +@mock.patch.object(RecommendationServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RecommendationServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_recommendation_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 + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + RecommendationServiceClient, RecommendationServiceAsyncClient +]) +@mock.patch.object(RecommendationServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RecommendationServiceClient)) +@mock.patch.object(RecommendationServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RecommendationServiceAsyncClient)) +def test_recommendation_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (RecommendationServiceClient, transports.RecommendationServiceGrpcTransport, "grpc"), + (RecommendationServiceAsyncClient, transports.RecommendationServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (RecommendationServiceClient, transports.RecommendationServiceRestTransport, "rest"), +]) +def test_recommendation_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, + 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", [ + (RecommendationServiceClient, transports.RecommendationServiceGrpcTransport, "grpc", grpc_helpers), + (RecommendationServiceAsyncClient, transports.RecommendationServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (RecommendationServiceClient, transports.RecommendationServiceRestTransport, "rest", None), +]) +def test_recommendation_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, + scopes=None, + client_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_recommendation_service_client_client_options_from_dict(): + with mock.patch('google.cloud.discoveryengine_v1alpha.services.recommendation_service.transports.RecommendationServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = RecommendationServiceClient( + 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", [ + (RecommendationServiceClient, transports.RecommendationServiceGrpcTransport, "grpc", grpc_helpers), + (RecommendationServiceAsyncClient, transports.RecommendationServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_recommendation_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, + scopes=None, + client_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + recommendation_service.RecommendRequest, + dict, +]) +def test_recommend(request_type, transport: str = 'grpc'): + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.recommend), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = recommendation_service.RecommendResponse( + attribution_token='attribution_token_value', + missing_ids=['missing_ids_value'], + validate_only=True, + ) + response = client.recommend(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == recommendation_service.RecommendRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, recommendation_service.RecommendResponse) + assert response.attribution_token == 'attribution_token_value' + assert response.missing_ids == ['missing_ids_value'] + assert response.validate_only is True + + +def test_recommend_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.recommend), + '__call__') as call: + client.recommend() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == recommendation_service.RecommendRequest() + +@pytest.mark.asyncio +async def test_recommend_async(transport: str = 'grpc_asyncio', request_type=recommendation_service.RecommendRequest): + client = RecommendationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.recommend), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(recommendation_service.RecommendResponse( + attribution_token='attribution_token_value', + missing_ids=['missing_ids_value'], + validate_only=True, + )) + response = await client.recommend(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == recommendation_service.RecommendRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, recommendation_service.RecommendResponse) + assert response.attribution_token == 'attribution_token_value' + assert response.missing_ids == ['missing_ids_value'] + assert response.validate_only is True + + +@pytest.mark.asyncio +async def test_recommend_async_from_dict(): + await test_recommend_async(request_type=dict) + + +def test_recommend_field_headers(): + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recommendation_service.RecommendRequest() + + request.serving_config = 'serving_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.recommend), + '__call__') as call: + call.return_value = recommendation_service.RecommendResponse() + client.recommend(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config=serving_config_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_recommend_field_headers_async(): + client = RecommendationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recommendation_service.RecommendRequest() + + request.serving_config = 'serving_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.recommend), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(recommendation_service.RecommendResponse()) + await client.recommend(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config=serving_config_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + recommendation_service.RecommendRequest, + dict, +]) +def test_recommend_rest(request_type): + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'serving_config': 'projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/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 = recommendation_service.RecommendResponse( + attribution_token='attribution_token_value', + missing_ids=['missing_ids_value'], + validate_only=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = recommendation_service.RecommendResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.recommend(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, recommendation_service.RecommendResponse) + assert response.attribution_token == 'attribution_token_value' + assert response.missing_ids == ['missing_ids_value'] + assert response.validate_only is True + + +def test_recommend_rest_required_fields(request_type=recommendation_service.RecommendRequest): + transport_class = transports.RecommendationServiceRestTransport + + request_init = {} + request_init["serving_config"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).recommend._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["servingConfig"] = 'serving_config_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).recommend._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "servingConfig" in jsonified_request + assert jsonified_request["servingConfig"] == 'serving_config_value' + + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = recommendation_service.RecommendResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = recommendation_service.RecommendResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.recommend(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_recommend_rest_unset_required_fields(): + transport = transports.RecommendationServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.recommend._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("servingConfig", "userEvent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_recommend_rest_interceptors(null_interceptor): + transport = transports.RecommendationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RecommendationServiceRestInterceptor(), + ) + client = RecommendationServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RecommendationServiceRestInterceptor, "post_recommend") as post, \ + mock.patch.object(transports.RecommendationServiceRestInterceptor, "pre_recommend") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = recommendation_service.RecommendRequest.pb(recommendation_service.RecommendRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = recommendation_service.RecommendResponse.to_json(recommendation_service.RecommendResponse()) + + request = recommendation_service.RecommendRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = recommendation_service.RecommendResponse() + + client.recommend(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_recommend_rest_bad_request(transport: str = 'rest', request_type=recommendation_service.RecommendRequest): + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'serving_config': 'projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.recommend(request) + + +def test_recommend_rest_error(): + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.RecommendationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.RecommendationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RecommendationServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.RecommendationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RecommendationServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RecommendationServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.RecommendationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RecommendationServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.RecommendationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = RecommendationServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.RecommendationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.RecommendationServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.RecommendationServiceGrpcTransport, + transports.RecommendationServiceGrpcAsyncIOTransport, + transports.RecommendationServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = RecommendationServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.RecommendationServiceGrpcTransport, + ) + +def test_recommendation_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.RecommendationServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_recommendation_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.discoveryengine_v1alpha.services.recommendation_service.transports.RecommendationServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.RecommendationServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'recommend', + 'get_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_recommendation_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.discoveryengine_v1alpha.services.recommendation_service.transports.RecommendationServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RecommendationServiceTransport( + 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_recommendation_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.discoveryengine_v1alpha.services.recommendation_service.transports.RecommendationServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RecommendationServiceTransport() + adc.assert_called_once() + + +def test_recommendation_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) + RecommendationServiceClient() + 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.RecommendationServiceGrpcTransport, + transports.RecommendationServiceGrpcAsyncIOTransport, + ], +) +def test_recommendation_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.RecommendationServiceGrpcTransport, + transports.RecommendationServiceGrpcAsyncIOTransport, + transports.RecommendationServiceRestTransport, + ], +) +def test_recommendation_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.RecommendationServiceGrpcTransport, grpc_helpers), + (transports.RecommendationServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_recommendation_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.RecommendationServiceGrpcTransport, transports.RecommendationServiceGrpcAsyncIOTransport]) +def test_recommendation_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_recommendation_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.RecommendationServiceRestTransport ( + 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_recommendation_service_host_no_port(transport_name): + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_recommendation_service_host_with_port(transport_name): + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_recommendation_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = RecommendationServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = RecommendationServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.recommend._session + session2 = client2.transport.recommend._session + assert session1 != session2 +def test_recommendation_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RecommendationServiceGrpcTransport( + 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_recommendation_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RecommendationServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.RecommendationServiceGrpcTransport, transports.RecommendationServiceGrpcAsyncIOTransport]) +def test_recommendation_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.RecommendationServiceGrpcTransport, transports.RecommendationServiceGrpcAsyncIOTransport]) +def test_recommendation_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_document_path(): + project = "squid" + location = "clam" + data_store = "whelk" + branch = "octopus" + document = "oyster" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) + actual = RecommendationServiceClient.document_path(project, location, data_store, branch, document) + assert expected == actual + + +def test_parse_document_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "data_store": "mussel", + "branch": "winkle", + "document": "nautilus", + } + path = RecommendationServiceClient.document_path(**expected) + + # Check that the path construction is reversible. + actual = RecommendationServiceClient.parse_document_path(path) + assert expected == actual + +def test_serving_config_path(): + project = "scallop" + location = "abalone" + data_store = "squid" + serving_config = "clam" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/servingConfigs/{serving_config}".format(project=project, location=location, data_store=data_store, serving_config=serving_config, ) + actual = RecommendationServiceClient.serving_config_path(project, location, data_store, serving_config) + assert expected == actual + + +def test_parse_serving_config_path(): + expected = { + "project": "whelk", + "location": "octopus", + "data_store": "oyster", + "serving_config": "nudibranch", + } + path = RecommendationServiceClient.serving_config_path(**expected) + + # Check that the path construction is reversible. + actual = RecommendationServiceClient.parse_serving_config_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = RecommendationServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = RecommendationServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = RecommendationServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = RecommendationServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = RecommendationServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = RecommendationServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = RecommendationServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = RecommendationServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = RecommendationServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = RecommendationServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = RecommendationServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = RecommendationServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = RecommendationServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = RecommendationServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = RecommendationServiceClient.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.RecommendationServiceTransport, '_prep_wrapped_messages') as prep: + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.RecommendationServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = RecommendationServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = RecommendationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_get_operation(transport: str = "grpc"): + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc"): + client = RecommendationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = RecommendationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = RecommendationServiceClient( + 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 = RecommendationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc"): + client = RecommendationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = RecommendationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = RecommendationServiceClient( + 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 = RecommendationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = RecommendationServiceClient( + 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", [ + (RecommendationServiceClient, transports.RecommendationServiceGrpcTransport), + (RecommendationServiceAsyncClient, transports.RecommendationServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_schema_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_schema_service.py new file mode 100644 index 000000000000..110f7d7236f5 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_schema_service.py @@ -0,0 +1,4265 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.discoveryengine_v1alpha.services.schema_service import SchemaServiceAsyncClient +from google.cloud.discoveryengine_v1alpha.services.schema_service import SchemaServiceClient +from google.cloud.discoveryengine_v1alpha.services.schema_service import pagers +from google.cloud.discoveryengine_v1alpha.services.schema_service import transports +from google.cloud.discoveryengine_v1alpha.types import schema +from google.cloud.discoveryengine_v1alpha.types import schema as gcd_schema +from google.cloud.discoveryengine_v1alpha.types import schema_service +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert SchemaServiceClient._get_default_mtls_endpoint(None) is None + assert SchemaServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert SchemaServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert SchemaServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert SchemaServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert SchemaServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (SchemaServiceClient, "grpc"), + (SchemaServiceAsyncClient, "grpc_asyncio"), + (SchemaServiceClient, "rest"), +]) +def test_schema_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.SchemaServiceGrpcTransport, "grpc"), + (transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.SchemaServiceRestTransport, "rest"), +]) +def test_schema_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", [ + (SchemaServiceClient, "grpc"), + (SchemaServiceAsyncClient, "grpc_asyncio"), + (SchemaServiceClient, "rest"), +]) +def test_schema_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +def test_schema_service_client_get_transport_class(): + transport = SchemaServiceClient.get_transport_class() + available_transports = [ + transports.SchemaServiceGrpcTransport, + transports.SchemaServiceRestTransport, + ] + assert transport in available_transports + + transport = SchemaServiceClient.get_transport_class("grpc") + assert transport == transports.SchemaServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc"), + (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (SchemaServiceClient, transports.SchemaServiceRestTransport, "rest"), +]) +@mock.patch.object(SchemaServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceClient)) +@mock.patch.object(SchemaServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceAsyncClient)) +def test_schema_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(SchemaServiceClient, '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(SchemaServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc", "true"), + (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc", "false"), + (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (SchemaServiceClient, transports.SchemaServiceRestTransport, "rest", "true"), + (SchemaServiceClient, transports.SchemaServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(SchemaServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceClient)) +@mock.patch.object(SchemaServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_schema_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 + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + SchemaServiceClient, SchemaServiceAsyncClient +]) +@mock.patch.object(SchemaServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceClient)) +@mock.patch.object(SchemaServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceAsyncClient)) +def test_schema_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc"), + (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (SchemaServiceClient, transports.SchemaServiceRestTransport, "rest"), +]) +def test_schema_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, + 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", [ + (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc", grpc_helpers), + (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (SchemaServiceClient, transports.SchemaServiceRestTransport, "rest", None), +]) +def test_schema_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, + scopes=None, + client_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_schema_service_client_client_options_from_dict(): + with mock.patch('google.cloud.discoveryengine_v1alpha.services.schema_service.transports.SchemaServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = SchemaServiceClient( + 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", [ + (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc", grpc_helpers), + (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_schema_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, + scopes=None, + client_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + schema_service.GetSchemaRequest, + dict, +]) +def test_get_schema(request_type, transport: str = 'grpc'): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = schema.Schema( + name='name_value', + json_schema='json_schema_value', + ) + response = client.get_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.GetSchemaRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, schema.Schema) + assert response.name == 'name_value' + + +def test_get_schema_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_schema), + '__call__') as call: + client.get_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.GetSchemaRequest() + +@pytest.mark.asyncio +async def test_get_schema_async(transport: str = 'grpc_asyncio', request_type=schema_service.GetSchemaRequest): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(schema.Schema( + name='name_value', + )) + response = await client.get_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.GetSchemaRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, schema.Schema) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_schema_async_from_dict(): + await test_get_schema_async(request_type=dict) + + +def test_get_schema_field_headers(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema_service.GetSchemaRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_schema), + '__call__') as call: + call.return_value = schema.Schema() + client.get_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_schema_field_headers_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema_service.GetSchemaRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_schema), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.Schema()) + await client.get_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_schema_flattened(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = schema.Schema() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_schema( + 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_schema_flattened_error(): + client = SchemaServiceClient( + credentials=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_schema( + schema_service.GetSchemaRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_schema_flattened_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = schema.Schema() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.Schema()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_schema( + 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_schema_flattened_error_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_schema( + schema_service.GetSchemaRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + schema_service.ListSchemasRequest, + dict, +]) +def test_list_schemas(request_type, transport: str = 'grpc'): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_schemas), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = schema_service.ListSchemasResponse( + next_page_token='next_page_token_value', + ) + response = client.list_schemas(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.ListSchemasRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSchemasPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_schemas_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_schemas), + '__call__') as call: + client.list_schemas() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.ListSchemasRequest() + +@pytest.mark.asyncio +async def test_list_schemas_async(transport: str = 'grpc_asyncio', request_type=schema_service.ListSchemasRequest): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_schemas), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(schema_service.ListSchemasResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_schemas(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.ListSchemasRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSchemasAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_schemas_async_from_dict(): + await test_list_schemas_async(request_type=dict) + + +def test_list_schemas_field_headers(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema_service.ListSchemasRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_schemas), + '__call__') as call: + call.return_value = schema_service.ListSchemasResponse() + client.list_schemas(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_schemas_field_headers_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema_service.ListSchemasRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_schemas), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema_service.ListSchemasResponse()) + await client.list_schemas(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_schemas_flattened(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_schemas), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = schema_service.ListSchemasResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_schemas( + 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_schemas_flattened_error(): + client = SchemaServiceClient( + credentials=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_schemas( + schema_service.ListSchemasRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_schemas_flattened_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_schemas), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = schema_service.ListSchemasResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema_service.ListSchemasResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_schemas( + 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_schemas_flattened_error_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_schemas( + schema_service.ListSchemasRequest(), + parent='parent_value', + ) + + +def test_list_schemas_pager(transport_name: str = "grpc"): + client = SchemaServiceClient( + 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_schemas), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + schema.Schema(), + ], + next_page_token='abc', + ), + schema_service.ListSchemasResponse( + schemas=[], + next_page_token='def', + ), + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + ], + next_page_token='ghi', + ), + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_schemas(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, schema.Schema) + for i in results) +def test_list_schemas_pages(transport_name: str = "grpc"): + client = SchemaServiceClient( + 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_schemas), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + schema.Schema(), + ], + next_page_token='abc', + ), + schema_service.ListSchemasResponse( + schemas=[], + next_page_token='def', + ), + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + ], + next_page_token='ghi', + ), + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + ], + ), + RuntimeError, + ) + pages = list(client.list_schemas(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_schemas_async_pager(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_schemas), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + schema.Schema(), + ], + next_page_token='abc', + ), + schema_service.ListSchemasResponse( + schemas=[], + next_page_token='def', + ), + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + ], + next_page_token='ghi', + ), + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_schemas(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, schema.Schema) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_schemas_async_pages(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_schemas), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + schema.Schema(), + ], + next_page_token='abc', + ), + schema_service.ListSchemasResponse( + schemas=[], + next_page_token='def', + ), + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + ], + next_page_token='ghi', + ), + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_schemas(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", [ + schema_service.CreateSchemaRequest, + dict, +]) +def test_create_schema(request_type, transport: str = 'grpc'): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.CreateSchemaRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_schema_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_schema), + '__call__') as call: + client.create_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.CreateSchemaRequest() + +@pytest.mark.asyncio +async def test_create_schema_async(transport: str = 'grpc_asyncio', request_type=schema_service.CreateSchemaRequest): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_schema), + '__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_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.CreateSchemaRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_schema_async_from_dict(): + await test_create_schema_async(request_type=dict) + + +def test_create_schema_field_headers(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema_service.CreateSchemaRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_schema), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_schema_field_headers_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema_service.CreateSchemaRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_schema), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_schema_flattened(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_schema), + '__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_schema( + parent='parent_value', + schema=gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), + schema_id='schema_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].schema + mock_val = gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})) + assert arg == mock_val + arg = args[0].schema_id + mock_val = 'schema_id_value' + assert arg == mock_val + + +def test_create_schema_flattened_error(): + client = SchemaServiceClient( + credentials=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_schema( + schema_service.CreateSchemaRequest(), + parent='parent_value', + schema=gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), + schema_id='schema_id_value', + ) + +@pytest.mark.asyncio +async def test_create_schema_flattened_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_schema), + '__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_schema( + parent='parent_value', + schema=gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), + schema_id='schema_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].schema + mock_val = gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})) + assert arg == mock_val + arg = args[0].schema_id + mock_val = 'schema_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_schema_flattened_error_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_schema( + schema_service.CreateSchemaRequest(), + parent='parent_value', + schema=gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), + schema_id='schema_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + schema_service.UpdateSchemaRequest, + dict, +]) +def test_update_schema(request_type, transport: str = 'grpc'): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.UpdateSchemaRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_schema_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_schema), + '__call__') as call: + client.update_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.UpdateSchemaRequest() + +@pytest.mark.asyncio +async def test_update_schema_async(transport: str = 'grpc_asyncio', request_type=schema_service.UpdateSchemaRequest): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_schema), + '__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_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.UpdateSchemaRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_schema_async_from_dict(): + await test_update_schema_async(request_type=dict) + + +def test_update_schema_field_headers(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema_service.UpdateSchemaRequest() + + request.schema.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_schema), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'schema.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_schema_field_headers_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema_service.UpdateSchemaRequest() + + request.schema.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_schema), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'schema.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + schema_service.DeleteSchemaRequest, + dict, +]) +def test_delete_schema(request_type, transport: str = 'grpc'): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.DeleteSchemaRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_schema_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_schema), + '__call__') as call: + client.delete_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.DeleteSchemaRequest() + +@pytest.mark.asyncio +async def test_delete_schema_async(transport: str = 'grpc_asyncio', request_type=schema_service.DeleteSchemaRequest): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_schema), + '__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_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.DeleteSchemaRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_schema_async_from_dict(): + await test_delete_schema_async(request_type=dict) + + +def test_delete_schema_field_headers(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema_service.DeleteSchemaRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_schema), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_schema_field_headers_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema_service.DeleteSchemaRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_schema), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_schema_flattened(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_schema), + '__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_schema( + 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_schema_flattened_error(): + client = SchemaServiceClient( + credentials=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_schema( + schema_service.DeleteSchemaRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_schema_flattened_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_schema), + '__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_schema( + 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_schema_flattened_error_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_schema( + schema_service.DeleteSchemaRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + schema_service.GetSchemaRequest, + dict, +]) +def test_get_schema_rest(request_type): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/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 = schema.Schema( + name='name_value', + json_schema='json_schema_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 = schema.Schema.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_schema(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, schema.Schema) + assert response.name == 'name_value' + + +def test_get_schema_rest_required_fields(request_type=schema_service.GetSchemaRequest): + transport_class = transports.SchemaServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = schema.Schema() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = schema.Schema.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_schema(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_schema_rest_unset_required_fields(): + transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_schema._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_schema_rest_interceptors(null_interceptor): + transport = transports.SchemaServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), + ) + client = SchemaServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SchemaServiceRestInterceptor, "post_get_schema") as post, \ + mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_get_schema") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = schema_service.GetSchemaRequest.pb(schema_service.GetSchemaRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = schema.Schema.to_json(schema.Schema()) + + request = schema_service.GetSchemaRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = schema.Schema() + + client.get_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_schema_rest_bad_request(transport: str = 'rest', request_type=schema_service.GetSchemaRequest): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_schema(request) + + +def test_get_schema_rest_flattened(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = schema.Schema() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/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 = schema.Schema.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_schema(**mock_args) + + # Establish that the underlying call 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/*/dataStores/*/schemas/*}" % client.transport._host, args[1]) + + +def test_get_schema_rest_flattened_error(transport: str = 'rest'): + client = SchemaServiceClient( + credentials=ga_credentials.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_schema( + schema_service.GetSchemaRequest(), + name='name_value', + ) + + +def test_get_schema_rest_error(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + schema_service.ListSchemasRequest, + dict, +]) +def test_list_schemas_rest(request_type): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/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 = schema_service.ListSchemasResponse( + next_page_token='next_page_token_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 = schema_service.ListSchemasResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_schemas(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSchemasPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_schemas_rest_required_fields(request_type=schema_service.ListSchemasRequest): + transport_class = transports.SchemaServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_schemas._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_schemas._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = schema_service.ListSchemasResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = schema_service.ListSchemasResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_schemas(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_schemas_rest_unset_required_fields(): + transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_schemas._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_schemas_rest_interceptors(null_interceptor): + transport = transports.SchemaServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), + ) + client = SchemaServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SchemaServiceRestInterceptor, "post_list_schemas") as post, \ + mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_list_schemas") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = schema_service.ListSchemasRequest.pb(schema_service.ListSchemasRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = schema_service.ListSchemasResponse.to_json(schema_service.ListSchemasResponse()) + + request = schema_service.ListSchemasRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = schema_service.ListSchemasResponse() + + client.list_schemas(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_schemas_rest_bad_request(transport: str = 'rest', request_type=schema_service.ListSchemasRequest): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_schemas(request) + + +def test_list_schemas_rest_flattened(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = schema_service.ListSchemasResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/dataStores/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 = schema_service.ListSchemasResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_schemas(**mock_args) + + # Establish that the underlying call 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/*/dataStores/*}/schemas" % client.transport._host, args[1]) + + +def test_list_schemas_rest_flattened_error(transport: str = 'rest'): + client = SchemaServiceClient( + credentials=ga_credentials.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_schemas( + schema_service.ListSchemasRequest(), + parent='parent_value', + ) + + +def test_list_schemas_rest_pager(transport: str = 'rest'): + client = SchemaServiceClient( + 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 = ( + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + schema.Schema(), + ], + next_page_token='abc', + ), + schema_service.ListSchemasResponse( + schemas=[], + next_page_token='def', + ), + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + ], + next_page_token='ghi', + ), + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(schema_service.ListSchemasResponse.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/dataStores/sample3'} + + pager = client.list_schemas(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, schema.Schema) + for i in results) + + pages = list(client.list_schemas(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + schema_service.CreateSchemaRequest, + dict, +]) +def test_create_schema_rest(request_type): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + request_init["schema"] = {'struct_schema': {'fields': {}}, 'json_schema': 'json_schema_value', 'name': 'name_value', 'field_configs': [{'field_path': 'field_path_value', 'field_type': 1, 'indexable_option': 1, 'dynamic_facetable_option': 1, 'searchable_option': 1, 'retrievable_option': 1, 'completable_option': 1, 'recs_filterable_option': 1, 'key_property_type': 'key_property_type_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 = schema_service.CreateSchemaRequest.meta.fields["schema"] + + 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["schema"].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["schema"][field])): + del request_init["schema"][field][i][subfield] + else: + del request_init["schema"][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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_schema(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_schema_rest_required_fields(request_type=schema_service.CreateSchemaRequest): + transport_class = transports.SchemaServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["schema_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "schemaId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "schemaId" in jsonified_request + assert jsonified_request["schemaId"] == request_init["schema_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["schemaId"] = 'schema_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_schema._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("schema_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "schemaId" in jsonified_request + assert jsonified_request["schemaId"] == 'schema_id_value' + + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_schema(request) + + expected_params = [ + ( + "schemaId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_schema_rest_unset_required_fields(): + transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_schema._get_unset_required_fields({}) + assert set(unset_fields) == (set(("schemaId", )) & set(("parent", "schema", "schemaId", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_schema_rest_interceptors(null_interceptor): + transport = transports.SchemaServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), + ) + client = SchemaServiceClient(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.SchemaServiceRestInterceptor, "post_create_schema") as post, \ + mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_create_schema") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = schema_service.CreateSchemaRequest.pb(schema_service.CreateSchemaRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = schema_service.CreateSchemaRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_schema_rest_bad_request(transport: str = 'rest', request_type=schema_service.CreateSchemaRequest): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_schema(request) + + +def test_create_schema_rest_flattened(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.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/dataStores/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + schema=gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), + schema_id='schema_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_schema(**mock_args) + + # Establish that the underlying call 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/*/dataStores/*}/schemas" % client.transport._host, args[1]) + + +def test_create_schema_rest_flattened_error(transport: str = 'rest'): + client = SchemaServiceClient( + credentials=ga_credentials.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_schema( + schema_service.CreateSchemaRequest(), + parent='parent_value', + schema=gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), + schema_id='schema_id_value', + ) + + +def test_create_schema_rest_error(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + schema_service.UpdateSchemaRequest, + dict, +]) +def test_update_schema_rest(request_type): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'schema': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/sample4'}} + request_init["schema"] = {'struct_schema': {'fields': {}}, 'json_schema': 'json_schema_value', 'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/sample4', 'field_configs': [{'field_path': 'field_path_value', 'field_type': 1, 'indexable_option': 1, 'dynamic_facetable_option': 1, 'searchable_option': 1, 'retrievable_option': 1, 'completable_option': 1, 'recs_filterable_option': 1, 'key_property_type': 'key_property_type_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 = schema_service.UpdateSchemaRequest.meta.fields["schema"] + + 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["schema"].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["schema"][field])): + del request_init["schema"][field][i][subfield] + else: + del request_init["schema"][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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_schema(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_schema_rest_required_fields(request_type=schema_service.UpdateSchemaRequest): + transport_class = transports.SchemaServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_schema._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_schema(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_schema_rest_unset_required_fields(): + transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_schema._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", )) & set(("schema", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_schema_rest_interceptors(null_interceptor): + transport = transports.SchemaServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), + ) + client = SchemaServiceClient(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.SchemaServiceRestInterceptor, "post_update_schema") as post, \ + mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_update_schema") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = schema_service.UpdateSchemaRequest.pb(schema_service.UpdateSchemaRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = schema_service.UpdateSchemaRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_schema_rest_bad_request(transport: str = 'rest', request_type=schema_service.UpdateSchemaRequest): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'schema': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/sample4'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_schema(request) + + +def test_update_schema_rest_error(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + schema_service.DeleteSchemaRequest, + dict, +]) +def test_delete_schema_rest(request_type): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_schema(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_schema_rest_required_fields(request_type=schema_service.DeleteSchemaRequest): + transport_class = transports.SchemaServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_schema(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_schema_rest_unset_required_fields(): + transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_schema._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_schema_rest_interceptors(null_interceptor): + transport = transports.SchemaServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), + ) + client = SchemaServiceClient(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.SchemaServiceRestInterceptor, "post_delete_schema") as post, \ + mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_delete_schema") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = schema_service.DeleteSchemaRequest.pb(schema_service.DeleteSchemaRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = schema_service.DeleteSchemaRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_schema_rest_bad_request(transport: str = 'rest', request_type=schema_service.DeleteSchemaRequest): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_schema(request) + + +def test_delete_schema_rest_flattened(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.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/dataStores/sample3/schemas/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_schema(**mock_args) + + # Establish that the underlying call 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/*/dataStores/*/schemas/*}" % client.transport._host, args[1]) + + +def test_delete_schema_rest_flattened_error(transport: str = 'rest'): + client = SchemaServiceClient( + credentials=ga_credentials.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_schema( + schema_service.DeleteSchemaRequest(), + name='name_value', + ) + + +def test_delete_schema_rest_error(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SchemaServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SchemaServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SchemaServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SchemaServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SchemaServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SchemaServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SchemaServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SchemaServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SchemaServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SchemaServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SchemaServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SchemaServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.SchemaServiceGrpcTransport, + transports.SchemaServiceGrpcAsyncIOTransport, + transports.SchemaServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = SchemaServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SchemaServiceGrpcTransport, + ) + +def test_schema_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SchemaServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_schema_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.discoveryengine_v1alpha.services.schema_service.transports.SchemaServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.SchemaServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_schema', + 'list_schemas', + 'create_schema', + 'update_schema', + 'delete_schema', + 'get_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_schema_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.discoveryengine_v1alpha.services.schema_service.transports.SchemaServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SchemaServiceTransport( + 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_schema_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.discoveryengine_v1alpha.services.schema_service.transports.SchemaServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SchemaServiceTransport() + adc.assert_called_once() + + +def test_schema_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) + SchemaServiceClient() + 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.SchemaServiceGrpcTransport, + transports.SchemaServiceGrpcAsyncIOTransport, + ], +) +def test_schema_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.SchemaServiceGrpcTransport, + transports.SchemaServiceGrpcAsyncIOTransport, + transports.SchemaServiceRestTransport, + ], +) +def test_schema_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.SchemaServiceGrpcTransport, grpc_helpers), + (transports.SchemaServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_schema_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.SchemaServiceGrpcTransport, transports.SchemaServiceGrpcAsyncIOTransport]) +def test_schema_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_schema_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.SchemaServiceRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_schema_service_rest_lro_client(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_schema_service_host_no_port(transport_name): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_schema_service_host_with_port(transport_name): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_schema_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = SchemaServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = SchemaServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_schema._session + session2 = client2.transport.get_schema._session + assert session1 != session2 + session1 = client1.transport.list_schemas._session + session2 = client2.transport.list_schemas._session + assert session1 != session2 + session1 = client1.transport.create_schema._session + session2 = client2.transport.create_schema._session + assert session1 != session2 + session1 = client1.transport.update_schema._session + session2 = client2.transport.update_schema._session + assert session1 != session2 + session1 = client1.transport.delete_schema._session + session2 = client2.transport.delete_schema._session + assert session1 != session2 +def test_schema_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SchemaServiceGrpcTransport( + 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_schema_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SchemaServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.SchemaServiceGrpcTransport, transports.SchemaServiceGrpcAsyncIOTransport]) +def test_schema_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.SchemaServiceGrpcTransport, transports.SchemaServiceGrpcAsyncIOTransport]) +def test_schema_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_schema_service_grpc_lro_client(): + client = SchemaServiceClient( + 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_schema_service_grpc_lro_async_client(): + client = SchemaServiceAsyncClient( + 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_data_store_path(): + project = "squid" + location = "clam" + data_store = "whelk" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) + actual = SchemaServiceClient.data_store_path(project, location, data_store) + assert expected == actual + + +def test_parse_data_store_path(): + expected = { + "project": "octopus", + "location": "oyster", + "data_store": "nudibranch", + } + path = SchemaServiceClient.data_store_path(**expected) + + # Check that the path construction is reversible. + actual = SchemaServiceClient.parse_data_store_path(path) + assert expected == actual + +def test_schema_path(): + project = "cuttlefish" + location = "mussel" + data_store = "winkle" + schema = "nautilus" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/schemas/{schema}".format(project=project, location=location, data_store=data_store, schema=schema, ) + actual = SchemaServiceClient.schema_path(project, location, data_store, schema) + assert expected == actual + + +def test_parse_schema_path(): + expected = { + "project": "scallop", + "location": "abalone", + "data_store": "squid", + "schema": "clam", + } + path = SchemaServiceClient.schema_path(**expected) + + # Check that the path construction is reversible. + actual = SchemaServiceClient.parse_schema_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = SchemaServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = SchemaServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SchemaServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = SchemaServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = SchemaServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SchemaServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SchemaServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = SchemaServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SchemaServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = SchemaServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = SchemaServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SchemaServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = SchemaServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = SchemaServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SchemaServiceClient.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.SchemaServiceTransport, '_prep_wrapped_messages') as prep: + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.SchemaServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = SchemaServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_get_operation(transport: str = "grpc"): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc"): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SchemaServiceClient( + 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 = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc"): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SchemaServiceClient( + 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 = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = SchemaServiceClient( + 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", [ + (SchemaServiceClient, transports.SchemaServiceGrpcTransport), + (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_search_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_search_service.py new file mode 100644 index 000000000000..cdc04bdc2165 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_search_service.py @@ -0,0 +1,2239 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.discoveryengine_v1alpha.services.search_service import SearchServiceAsyncClient +from google.cloud.discoveryengine_v1alpha.services.search_service import SearchServiceClient +from google.cloud.discoveryengine_v1alpha.services.search_service import pagers +from google.cloud.discoveryengine_v1alpha.services.search_service import transports +from google.cloud.discoveryengine_v1alpha.types import common +from google.cloud.discoveryengine_v1alpha.types import search_service +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import struct_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert SearchServiceClient._get_default_mtls_endpoint(None) is None + assert SearchServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (SearchServiceClient, "grpc"), + (SearchServiceAsyncClient, "grpc_asyncio"), + (SearchServiceClient, "rest"), +]) +def test_search_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.SearchServiceGrpcTransport, "grpc"), + (transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.SearchServiceRestTransport, "rest"), +]) +def test_search_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", [ + (SearchServiceClient, "grpc"), + (SearchServiceAsyncClient, "grpc_asyncio"), + (SearchServiceClient, "rest"), +]) +def test_search_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +def test_search_service_client_get_transport_class(): + transport = SearchServiceClient.get_transport_class() + available_transports = [ + transports.SearchServiceGrpcTransport, + transports.SearchServiceRestTransport, + ] + assert transport in available_transports + + transport = SearchServiceClient.get_transport_class("grpc") + assert transport == transports.SearchServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (SearchServiceClient, transports.SearchServiceRestTransport, "rest"), +]) +@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) +@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) +def test_search_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(SearchServiceClient, '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(SearchServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "true"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "false"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (SearchServiceClient, transports.SearchServiceRestTransport, "rest", "true"), + (SearchServiceClient, transports.SearchServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) +@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_search_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 + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + SearchServiceClient, SearchServiceAsyncClient +]) +@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) +@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) +def test_search_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (SearchServiceClient, transports.SearchServiceRestTransport, "rest"), +]) +def test_search_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, + 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", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (SearchServiceClient, transports.SearchServiceRestTransport, "rest", None), +]) +def test_search_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, + scopes=None, + client_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_search_service_client_client_options_from_dict(): + with mock.patch('google.cloud.discoveryengine_v1alpha.services.search_service.transports.SearchServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = SearchServiceClient( + 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", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_search_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, + scopes=None, + client_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + search_service.SearchRequest, + dict, +]) +def test_search(request_type, transport: str = 'grpc'): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = search_service.SearchResponse( + total_size=1086, + attribution_token='attribution_token_value', + redirect_uri='redirect_uri_value', + next_page_token='next_page_token_value', + corrected_query='corrected_query_value', + applied_controls=['applied_controls_value'], + ) + response = client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == search_service.SearchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchPager) + assert response.total_size == 1086 + assert response.attribution_token == 'attribution_token_value' + assert response.redirect_uri == 'redirect_uri_value' + assert response.next_page_token == 'next_page_token_value' + assert response.corrected_query == 'corrected_query_value' + assert response.applied_controls == ['applied_controls_value'] + + +def test_search_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + client.search() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == search_service.SearchRequest() + +@pytest.mark.asyncio +async def test_search_async(transport: str = 'grpc_asyncio', request_type=search_service.SearchRequest): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse( + total_size=1086, + attribution_token='attribution_token_value', + redirect_uri='redirect_uri_value', + next_page_token='next_page_token_value', + corrected_query='corrected_query_value', + applied_controls=['applied_controls_value'], + )) + response = await client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == search_service.SearchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAsyncPager) + assert response.total_size == 1086 + assert response.attribution_token == 'attribution_token_value' + assert response.redirect_uri == 'redirect_uri_value' + assert response.next_page_token == 'next_page_token_value' + assert response.corrected_query == 'corrected_query_value' + assert response.applied_controls == ['applied_controls_value'] + + +@pytest.mark.asyncio +async def test_search_async_from_dict(): + await test_search_async(request_type=dict) + + +def test_search_field_headers(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = search_service.SearchRequest() + + request.serving_config = 'serving_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + call.return_value = search_service.SearchResponse() + client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config=serving_config_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_search_field_headers_async(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = search_service.SearchRequest() + + request.serving_config = 'serving_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse()) + await client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config=serving_config_value', + ) in kw['metadata'] + + +def test_search_pager(transport_name: str = "grpc"): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('serving_config', ''), + )), + ) + pager = client.search(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, search_service.SearchResponse.SearchResult) + for i in results) +def test_search_pages(transport_name: str = "grpc"): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + pages = list(client.search(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_search_async_pager(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.search(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, search_service.SearchResponse.SearchResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_search_async_pages(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.search(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", [ + search_service.SearchRequest, + dict, +]) +def test_search_rest(request_type): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'serving_config': 'projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/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 = search_service.SearchResponse( + total_size=1086, + attribution_token='attribution_token_value', + redirect_uri='redirect_uri_value', + next_page_token='next_page_token_value', + corrected_query='corrected_query_value', + applied_controls=['applied_controls_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 = search_service.SearchResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.search(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchPager) + assert response.total_size == 1086 + assert response.attribution_token == 'attribution_token_value' + assert response.redirect_uri == 'redirect_uri_value' + assert response.next_page_token == 'next_page_token_value' + assert response.corrected_query == 'corrected_query_value' + assert response.applied_controls == ['applied_controls_value'] + + +def test_search_rest_required_fields(request_type=search_service.SearchRequest): + transport_class = transports.SearchServiceRestTransport + + request_init = {} + request_init["serving_config"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["servingConfig"] = 'serving_config_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "servingConfig" in jsonified_request + assert jsonified_request["servingConfig"] == 'serving_config_value' + + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = search_service.SearchResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = search_service.SearchResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.search(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_search_rest_unset_required_fields(): + transport = transports.SearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.search._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("servingConfig", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_rest_interceptors(null_interceptor): + transport = transports.SearchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SearchServiceRestInterceptor(), + ) + client = SearchServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SearchServiceRestInterceptor, "post_search") as post, \ + mock.patch.object(transports.SearchServiceRestInterceptor, "pre_search") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = search_service.SearchRequest.pb(search_service.SearchRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = search_service.SearchResponse.to_json(search_service.SearchResponse()) + + request = search_service.SearchRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = search_service.SearchResponse() + + client.search(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_search_rest_bad_request(transport: str = 'rest', request_type=search_service.SearchRequest): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'serving_config': 'projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.search(request) + + +def test_search_rest_pager(transport: str = 'rest'): + client = SearchServiceClient( + 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 = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(search_service.SearchResponse.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 = {'serving_config': 'projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/sample4'} + + pager = client.search(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, search_service.SearchResponse.SearchResult) + for i in results) + + pages = list(client.search(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.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SearchServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SearchServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.SearchServiceGrpcTransport, + transports.SearchServiceGrpcAsyncIOTransport, + transports.SearchServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = SearchServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SearchServiceGrpcTransport, + ) + +def test_search_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SearchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_search_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.discoveryengine_v1alpha.services.search_service.transports.SearchServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.SearchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'search', + 'get_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_search_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.discoveryengine_v1alpha.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SearchServiceTransport( + 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_search_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.discoveryengine_v1alpha.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SearchServiceTransport() + adc.assert_called_once() + + +def test_search_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) + SearchServiceClient() + 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.SearchServiceGrpcTransport, + transports.SearchServiceGrpcAsyncIOTransport, + ], +) +def test_search_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.SearchServiceGrpcTransport, + transports.SearchServiceGrpcAsyncIOTransport, + transports.SearchServiceRestTransport, + ], +) +def test_search_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.SearchServiceGrpcTransport, grpc_helpers), + (transports.SearchServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_search_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) +def test_search_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_search_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.SearchServiceRestTransport ( + 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_search_service_host_no_port(transport_name): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_search_service_host_with_port(transport_name): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_search_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = SearchServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = SearchServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.search._session + session2 = client2.transport.search._session + assert session1 != session2 +def test_search_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SearchServiceGrpcTransport( + 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_search_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SearchServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) +def test_search_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.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) +def test_search_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_branch_path(): + project = "squid" + location = "clam" + data_store = "whelk" + branch = "octopus" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}".format(project=project, location=location, data_store=data_store, branch=branch, ) + actual = SearchServiceClient.branch_path(project, location, data_store, branch) + assert expected == actual + + +def test_parse_branch_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "data_store": "cuttlefish", + "branch": "mussel", + } + path = SearchServiceClient.branch_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_branch_path(path) + assert expected == actual + +def test_document_path(): + project = "winkle" + location = "nautilus" + data_store = "scallop" + branch = "abalone" + document = "squid" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) + actual = SearchServiceClient.document_path(project, location, data_store, branch, document) + assert expected == actual + + +def test_parse_document_path(): + expected = { + "project": "clam", + "location": "whelk", + "data_store": "octopus", + "branch": "oyster", + "document": "nudibranch", + } + path = SearchServiceClient.document_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_document_path(path) + assert expected == actual + +def test_serving_config_path(): + project = "cuttlefish" + location = "mussel" + data_store = "winkle" + serving_config = "nautilus" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/servingConfigs/{serving_config}".format(project=project, location=location, data_store=data_store, serving_config=serving_config, ) + actual = SearchServiceClient.serving_config_path(project, location, data_store, serving_config) + assert expected == actual + + +def test_parse_serving_config_path(): + expected = { + "project": "scallop", + "location": "abalone", + "data_store": "squid", + "serving_config": "clam", + } + path = SearchServiceClient.serving_config_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_serving_config_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = SearchServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = SearchServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = SearchServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = SearchServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SearchServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = SearchServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = SearchServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = SearchServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = SearchServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = SearchServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.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.SearchServiceTransport, '_prep_wrapped_messages') as prep: + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = SearchServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_get_operation(transport: str = "grpc"): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc"): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SearchServiceClient( + 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 = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc"): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SearchServiceClient( + 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 = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = SearchServiceClient( + 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", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_site_search_engine_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_site_search_engine_service.py new file mode 100644 index 000000000000..f81202d1d8f6 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_site_search_engine_service.py @@ -0,0 +1,1961 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.discoveryengine_v1alpha.services.site_search_engine_service import SiteSearchEngineServiceAsyncClient +from google.cloud.discoveryengine_v1alpha.services.site_search_engine_service import SiteSearchEngineServiceClient +from google.cloud.discoveryengine_v1alpha.services.site_search_engine_service import transports +from google.cloud.discoveryengine_v1alpha.types import site_search_engine_service +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert SiteSearchEngineServiceClient._get_default_mtls_endpoint(None) is None + assert SiteSearchEngineServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert SiteSearchEngineServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert SiteSearchEngineServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert SiteSearchEngineServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert SiteSearchEngineServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (SiteSearchEngineServiceClient, "grpc"), + (SiteSearchEngineServiceAsyncClient, "grpc_asyncio"), + (SiteSearchEngineServiceClient, "rest"), +]) +def test_site_search_engine_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.SiteSearchEngineServiceGrpcTransport, "grpc"), + (transports.SiteSearchEngineServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.SiteSearchEngineServiceRestTransport, "rest"), +]) +def test_site_search_engine_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", [ + (SiteSearchEngineServiceClient, "grpc"), + (SiteSearchEngineServiceAsyncClient, "grpc_asyncio"), + (SiteSearchEngineServiceClient, "rest"), +]) +def test_site_search_engine_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +def test_site_search_engine_service_client_get_transport_class(): + transport = SiteSearchEngineServiceClient.get_transport_class() + available_transports = [ + transports.SiteSearchEngineServiceGrpcTransport, + transports.SiteSearchEngineServiceRestTransport, + ] + assert transport in available_transports + + transport = SiteSearchEngineServiceClient.get_transport_class("grpc") + assert transport == transports.SiteSearchEngineServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SiteSearchEngineServiceClient, transports.SiteSearchEngineServiceGrpcTransport, "grpc"), + (SiteSearchEngineServiceAsyncClient, transports.SiteSearchEngineServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (SiteSearchEngineServiceClient, transports.SiteSearchEngineServiceRestTransport, "rest"), +]) +@mock.patch.object(SiteSearchEngineServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SiteSearchEngineServiceClient)) +@mock.patch.object(SiteSearchEngineServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SiteSearchEngineServiceAsyncClient)) +def test_site_search_engine_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(SiteSearchEngineServiceClient, '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(SiteSearchEngineServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (SiteSearchEngineServiceClient, transports.SiteSearchEngineServiceGrpcTransport, "grpc", "true"), + (SiteSearchEngineServiceAsyncClient, transports.SiteSearchEngineServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SiteSearchEngineServiceClient, transports.SiteSearchEngineServiceGrpcTransport, "grpc", "false"), + (SiteSearchEngineServiceAsyncClient, transports.SiteSearchEngineServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (SiteSearchEngineServiceClient, transports.SiteSearchEngineServiceRestTransport, "rest", "true"), + (SiteSearchEngineServiceClient, transports.SiteSearchEngineServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(SiteSearchEngineServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SiteSearchEngineServiceClient)) +@mock.patch.object(SiteSearchEngineServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SiteSearchEngineServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_site_search_engine_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 + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + SiteSearchEngineServiceClient, SiteSearchEngineServiceAsyncClient +]) +@mock.patch.object(SiteSearchEngineServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SiteSearchEngineServiceClient)) +@mock.patch.object(SiteSearchEngineServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SiteSearchEngineServiceAsyncClient)) +def test_site_search_engine_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SiteSearchEngineServiceClient, transports.SiteSearchEngineServiceGrpcTransport, "grpc"), + (SiteSearchEngineServiceAsyncClient, transports.SiteSearchEngineServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (SiteSearchEngineServiceClient, transports.SiteSearchEngineServiceRestTransport, "rest"), +]) +def test_site_search_engine_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, + 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", [ + (SiteSearchEngineServiceClient, transports.SiteSearchEngineServiceGrpcTransport, "grpc", grpc_helpers), + (SiteSearchEngineServiceAsyncClient, transports.SiteSearchEngineServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (SiteSearchEngineServiceClient, transports.SiteSearchEngineServiceRestTransport, "rest", None), +]) +def test_site_search_engine_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, + scopes=None, + client_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_site_search_engine_service_client_client_options_from_dict(): + with mock.patch('google.cloud.discoveryengine_v1alpha.services.site_search_engine_service.transports.SiteSearchEngineServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = SiteSearchEngineServiceClient( + 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", [ + (SiteSearchEngineServiceClient, transports.SiteSearchEngineServiceGrpcTransport, "grpc", grpc_helpers), + (SiteSearchEngineServiceAsyncClient, transports.SiteSearchEngineServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_site_search_engine_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, + scopes=None, + client_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + site_search_engine_service.RecrawlUrisRequest, + dict, +]) +def test_recrawl_uris(request_type, transport: str = 'grpc'): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.recrawl_uris), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.recrawl_uris(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == site_search_engine_service.RecrawlUrisRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_recrawl_uris_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.recrawl_uris), + '__call__') as call: + client.recrawl_uris() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == site_search_engine_service.RecrawlUrisRequest() + +@pytest.mark.asyncio +async def test_recrawl_uris_async(transport: str = 'grpc_asyncio', request_type=site_search_engine_service.RecrawlUrisRequest): + client = SiteSearchEngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.recrawl_uris), + '__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.recrawl_uris(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == site_search_engine_service.RecrawlUrisRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_recrawl_uris_async_from_dict(): + await test_recrawl_uris_async(request_type=dict) + + +def test_recrawl_uris_field_headers(): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = site_search_engine_service.RecrawlUrisRequest() + + request.site_search_engine = 'site_search_engine_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.recrawl_uris), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.recrawl_uris(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'site_search_engine=site_search_engine_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_recrawl_uris_field_headers_async(): + client = SiteSearchEngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = site_search_engine_service.RecrawlUrisRequest() + + request.site_search_engine = 'site_search_engine_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.recrawl_uris), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.recrawl_uris(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'site_search_engine=site_search_engine_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + site_search_engine_service.RecrawlUrisRequest, + dict, +]) +def test_recrawl_uris_rest(request_type): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'site_search_engine': 'projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.recrawl_uris(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_recrawl_uris_rest_required_fields(request_type=site_search_engine_service.RecrawlUrisRequest): + transport_class = transports.SiteSearchEngineServiceRestTransport + + request_init = {} + request_init["site_search_engine"] = "" + request_init["uris"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).recrawl_uris._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["siteSearchEngine"] = 'site_search_engine_value' + jsonified_request["uris"] = 'uris_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).recrawl_uris._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "siteSearchEngine" in jsonified_request + assert jsonified_request["siteSearchEngine"] == 'site_search_engine_value' + assert "uris" in jsonified_request + assert jsonified_request["uris"] == 'uris_value' + + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.recrawl_uris(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_recrawl_uris_rest_unset_required_fields(): + transport = transports.SiteSearchEngineServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.recrawl_uris._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("siteSearchEngine", "uris", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_recrawl_uris_rest_interceptors(null_interceptor): + transport = transports.SiteSearchEngineServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SiteSearchEngineServiceRestInterceptor(), + ) + client = SiteSearchEngineServiceClient(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.SiteSearchEngineServiceRestInterceptor, "post_recrawl_uris") as post, \ + mock.patch.object(transports.SiteSearchEngineServiceRestInterceptor, "pre_recrawl_uris") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = site_search_engine_service.RecrawlUrisRequest.pb(site_search_engine_service.RecrawlUrisRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = site_search_engine_service.RecrawlUrisRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.recrawl_uris(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_recrawl_uris_rest_bad_request(transport: str = 'rest', request_type=site_search_engine_service.RecrawlUrisRequest): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'site_search_engine': 'projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.recrawl_uris(request) + + +def test_recrawl_uris_rest_error(): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SiteSearchEngineServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SiteSearchEngineServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SiteSearchEngineServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SiteSearchEngineServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SiteSearchEngineServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SiteSearchEngineServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SiteSearchEngineServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SiteSearchEngineServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SiteSearchEngineServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SiteSearchEngineServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SiteSearchEngineServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SiteSearchEngineServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.SiteSearchEngineServiceGrpcTransport, + transports.SiteSearchEngineServiceGrpcAsyncIOTransport, + transports.SiteSearchEngineServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = SiteSearchEngineServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SiteSearchEngineServiceGrpcTransport, + ) + +def test_site_search_engine_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SiteSearchEngineServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_site_search_engine_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.discoveryengine_v1alpha.services.site_search_engine_service.transports.SiteSearchEngineServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.SiteSearchEngineServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'recrawl_uris', + 'get_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_site_search_engine_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.discoveryengine_v1alpha.services.site_search_engine_service.transports.SiteSearchEngineServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SiteSearchEngineServiceTransport( + 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_site_search_engine_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.discoveryengine_v1alpha.services.site_search_engine_service.transports.SiteSearchEngineServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SiteSearchEngineServiceTransport() + adc.assert_called_once() + + +def test_site_search_engine_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) + SiteSearchEngineServiceClient() + 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.SiteSearchEngineServiceGrpcTransport, + transports.SiteSearchEngineServiceGrpcAsyncIOTransport, + ], +) +def test_site_search_engine_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.SiteSearchEngineServiceGrpcTransport, + transports.SiteSearchEngineServiceGrpcAsyncIOTransport, + transports.SiteSearchEngineServiceRestTransport, + ], +) +def test_site_search_engine_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.SiteSearchEngineServiceGrpcTransport, grpc_helpers), + (transports.SiteSearchEngineServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_site_search_engine_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.SiteSearchEngineServiceGrpcTransport, transports.SiteSearchEngineServiceGrpcAsyncIOTransport]) +def test_site_search_engine_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_site_search_engine_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.SiteSearchEngineServiceRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_site_search_engine_service_rest_lro_client(): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_site_search_engine_service_host_no_port(transport_name): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_site_search_engine_service_host_with_port(transport_name): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_site_search_engine_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = SiteSearchEngineServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = SiteSearchEngineServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.recrawl_uris._session + session2 = client2.transport.recrawl_uris._session + assert session1 != session2 +def test_site_search_engine_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SiteSearchEngineServiceGrpcTransport( + 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_site_search_engine_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SiteSearchEngineServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.SiteSearchEngineServiceGrpcTransport, transports.SiteSearchEngineServiceGrpcAsyncIOTransport]) +def test_site_search_engine_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.SiteSearchEngineServiceGrpcTransport, transports.SiteSearchEngineServiceGrpcAsyncIOTransport]) +def test_site_search_engine_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_site_search_engine_service_grpc_lro_client(): + client = SiteSearchEngineServiceClient( + 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_site_search_engine_service_grpc_lro_async_client(): + client = SiteSearchEngineServiceAsyncClient( + 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_site_search_engine_path(): + project = "squid" + location = "clam" + data_store = "whelk" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/siteSearchEngine".format(project=project, location=location, data_store=data_store, ) + actual = SiteSearchEngineServiceClient.site_search_engine_path(project, location, data_store) + assert expected == actual + + +def test_parse_site_search_engine_path(): + expected = { + "project": "octopus", + "location": "oyster", + "data_store": "nudibranch", + } + path = SiteSearchEngineServiceClient.site_search_engine_path(**expected) + + # Check that the path construction is reversible. + actual = SiteSearchEngineServiceClient.parse_site_search_engine_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = SiteSearchEngineServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = SiteSearchEngineServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SiteSearchEngineServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = SiteSearchEngineServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = SiteSearchEngineServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SiteSearchEngineServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SiteSearchEngineServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = SiteSearchEngineServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SiteSearchEngineServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = SiteSearchEngineServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = SiteSearchEngineServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SiteSearchEngineServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = SiteSearchEngineServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = SiteSearchEngineServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SiteSearchEngineServiceClient.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.SiteSearchEngineServiceTransport, '_prep_wrapped_messages') as prep: + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.SiteSearchEngineServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = SiteSearchEngineServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = SiteSearchEngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_get_operation(transport: str = "grpc"): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc"): + client = SiteSearchEngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SiteSearchEngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SiteSearchEngineServiceClient( + 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 = SiteSearchEngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc"): + client = SiteSearchEngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SiteSearchEngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SiteSearchEngineServiceClient( + 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 = SiteSearchEngineServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = SiteSearchEngineServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = SiteSearchEngineServiceClient( + 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", [ + (SiteSearchEngineServiceClient, transports.SiteSearchEngineServiceGrpcTransport), + (SiteSearchEngineServiceAsyncClient, transports.SiteSearchEngineServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_user_event_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_user_event_service.py new file mode 100644 index 000000000000..36088e10e67e --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_user_event_service.py @@ -0,0 +1,3118 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.discoveryengine_v1alpha.services.user_event_service import UserEventServiceAsyncClient +from google.cloud.discoveryengine_v1alpha.services.user_event_service import UserEventServiceClient +from google.cloud.discoveryengine_v1alpha.services.user_event_service import transports +from google.cloud.discoveryengine_v1alpha.types import common +from google.cloud.discoveryengine_v1alpha.types import import_config +from google.cloud.discoveryengine_v1alpha.types import purge_config +from google.cloud.discoveryengine_v1alpha.types import user_event +from google.cloud.discoveryengine_v1alpha.types import user_event_service +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert UserEventServiceClient._get_default_mtls_endpoint(None) is None + assert UserEventServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (UserEventServiceClient, "grpc"), + (UserEventServiceAsyncClient, "grpc_asyncio"), + (UserEventServiceClient, "rest"), +]) +def test_user_event_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.UserEventServiceGrpcTransport, "grpc"), + (transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.UserEventServiceRestTransport, "rest"), +]) +def test_user_event_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", [ + (UserEventServiceClient, "grpc"), + (UserEventServiceAsyncClient, "grpc_asyncio"), + (UserEventServiceClient, "rest"), +]) +def test_user_event_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +def test_user_event_service_client_get_transport_class(): + transport = UserEventServiceClient.get_transport_class() + available_transports = [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceRestTransport, + ] + assert transport in available_transports + + transport = UserEventServiceClient.get_transport_class("grpc") + assert transport == transports.UserEventServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (UserEventServiceClient, transports.UserEventServiceRestTransport, "rest"), +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +def test_user_event_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(UserEventServiceClient, '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(UserEventServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "true"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "false"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (UserEventServiceClient, transports.UserEventServiceRestTransport, "rest", "true"), + (UserEventServiceClient, transports.UserEventServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_user_event_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 + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + UserEventServiceClient, UserEventServiceAsyncClient +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +def test_user_event_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (UserEventServiceClient, transports.UserEventServiceRestTransport, "rest"), +]) +def test_user_event_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, + 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", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (UserEventServiceClient, transports.UserEventServiceRestTransport, "rest", None), +]) +def test_user_event_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, + scopes=None, + client_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_user_event_service_client_client_options_from_dict(): + with mock.patch('google.cloud.discoveryengine_v1alpha.services.user_event_service.transports.UserEventServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = UserEventServiceClient( + 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", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_user_event_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, + scopes=None, + client_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + user_event_service.WriteUserEventRequest, + dict, +]) +def test_write_user_event(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = user_event.UserEvent( + event_type='event_type_value', + user_pseudo_id='user_pseudo_id_value', + direct_user_request=True, + session_id='session_id_value', + attribution_token='attribution_token_value', + filter='filter_value', + tag_ids=['tag_ids_value'], + promotion_ids=['promotion_ids_value'], + ) + response = client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, user_event.UserEvent) + assert response.event_type == 'event_type_value' + assert response.user_pseudo_id == 'user_pseudo_id_value' + assert response.direct_user_request is True + assert response.session_id == 'session_id_value' + assert response.attribution_token == 'attribution_token_value' + assert response.filter == 'filter_value' + assert response.tag_ids == ['tag_ids_value'] + assert response.promotion_ids == ['promotion_ids_value'] + + +def test_write_user_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + client.write_user_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + +@pytest.mark.asyncio +async def test_write_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.WriteUserEventRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent( + event_type='event_type_value', + user_pseudo_id='user_pseudo_id_value', + direct_user_request=True, + session_id='session_id_value', + attribution_token='attribution_token_value', + filter='filter_value', + tag_ids=['tag_ids_value'], + promotion_ids=['promotion_ids_value'], + )) + response = await client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, user_event.UserEvent) + assert response.event_type == 'event_type_value' + assert response.user_pseudo_id == 'user_pseudo_id_value' + assert response.direct_user_request is True + assert response.session_id == 'session_id_value' + assert response.attribution_token == 'attribution_token_value' + assert response.filter == 'filter_value' + assert response.tag_ids == ['tag_ids_value'] + assert response.promotion_ids == ['promotion_ids_value'] + + +@pytest.mark.asyncio +async def test_write_user_event_async_from_dict(): + await test_write_user_event_async(request_type=dict) + + +def test_write_user_event_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.WriteUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + call.return_value = user_event.UserEvent() + client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_write_user_event_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.WriteUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent()) + await client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + user_event_service.CollectUserEventRequest, + dict, +]) +def test_collect_user_event(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + ) + response = client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +def test_collect_user_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + client.collect_user_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + +@pytest.mark.asyncio +async def test_collect_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.CollectUserEventRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + )) + response = await client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +@pytest.mark.asyncio +async def test_collect_user_event_async_from_dict(): + await test_collect_user_event_async(request_type=dict) + + +def test_collect_user_event_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.CollectUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + call.return_value = httpbody_pb2.HttpBody() + client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_collect_user_event_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.CollectUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody()) + await client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + purge_config.PurgeUserEventsRequest, + dict, +]) +def test_purge_user_events(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_purge_user_events_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + client.purge_user_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeUserEventsRequest() + +@pytest.mark.asyncio +async def test_purge_user_events_async(transport: str = 'grpc_asyncio', request_type=purge_config.PurgeUserEventsRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__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.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_purge_user_events_async_from_dict(): + await test_purge_user_events_async(request_type=dict) + + +def test_purge_user_events_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = purge_config.PurgeUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_purge_user_events_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = purge_config.PurgeUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_user_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.purge_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportUserEventsRequest, + dict, +]) +def test_import_user_events(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_user_events_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + client.import_user_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportUserEventsRequest() + +@pytest.mark.asyncio +async def test_import_user_events_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportUserEventsRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__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_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_user_events_async_from_dict(): + await test_import_user_events_async(request_type=dict) + + +def test_import_user_events_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_import_user_events_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + user_event_service.WriteUserEventRequest, + dict, +]) +def test_write_user_event_rest(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + request_init["user_event"] = {'event_type': 'event_type_value', 'user_pseudo_id': 'user_pseudo_id_value', 'event_time': {'seconds': 751, 'nanos': 543}, 'user_info': {'user_id': 'user_id_value', 'user_agent': 'user_agent_value'}, 'direct_user_request': True, 'session_id': 'session_id_value', 'page_info': {'pageview_id': 'pageview_id_value', 'page_category': 'page_category_value', 'uri': 'uri_value', 'referrer_uri': 'referrer_uri_value'}, 'attribution_token': 'attribution_token_value', 'filter': 'filter_value', 'documents': [{'id': 'id_value', 'name': 'name_value', 'uri': 'uri_value', 'quantity': 895, 'promotion_ids': ['promotion_ids_value1', 'promotion_ids_value2']}], 'panel': {'panel_id': 'panel_id_value', 'display_name': 'display_name_value', 'panel_position': 1508, 'total_panels': 1286}, 'search_info': {'search_query': 'search_query_value', 'order_by': 'order_by_value', 'offset': 647}, 'completion_info': {'selected_suggestion': 'selected_suggestion_value', 'selected_position': 1821}, 'transaction_info': {'value': 0.541, 'currency': 'currency_value', 'transaction_id': 'transaction_id_value', 'tax': 0.333, 'cost': 0.441, 'discount_value': 0.1509}, 'tag_ids': ['tag_ids_value1', 'tag_ids_value2'], 'promotion_ids': ['promotion_ids_value1', 'promotion_ids_value2'], 'attributes': {}, 'media_info': {'media_progress_duration': {'seconds': 751, 'nanos': 543}, 'media_progress_percentage': 0.2641}} + # 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 = user_event_service.WriteUserEventRequest.meta.fields["user_event"] + + 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_event"].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_event"][field])): + del request_init["user_event"][field][i][subfield] + else: + del request_init["user_event"][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 = user_event.UserEvent( + event_type='event_type_value', + user_pseudo_id='user_pseudo_id_value', + direct_user_request=True, + session_id='session_id_value', + attribution_token='attribution_token_value', + filter='filter_value', + tag_ids=['tag_ids_value'], + promotion_ids=['promotion_ids_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 = user_event.UserEvent.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.write_user_event(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, user_event.UserEvent) + assert response.event_type == 'event_type_value' + assert response.user_pseudo_id == 'user_pseudo_id_value' + assert response.direct_user_request is True + assert response.session_id == 'session_id_value' + assert response.attribution_token == 'attribution_token_value' + assert response.filter == 'filter_value' + assert response.tag_ids == ['tag_ids_value'] + assert response.promotion_ids == ['promotion_ids_value'] + + +def test_write_user_event_rest_required_fields(request_type=user_event_service.WriteUserEventRequest): + transport_class = transports.UserEventServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).write_user_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).write_user_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = user_event.UserEvent() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = user_event.UserEvent.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.write_user_event(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_write_user_event_rest_unset_required_fields(): + transport = transports.UserEventServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.write_user_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "userEvent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_write_user_event_rest_interceptors(null_interceptor): + transport = transports.UserEventServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.UserEventServiceRestInterceptor(), + ) + client = UserEventServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.UserEventServiceRestInterceptor, "post_write_user_event") as post, \ + mock.patch.object(transports.UserEventServiceRestInterceptor, "pre_write_user_event") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = user_event_service.WriteUserEventRequest.pb(user_event_service.WriteUserEventRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = user_event.UserEvent.to_json(user_event.UserEvent()) + + request = user_event_service.WriteUserEventRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = user_event.UserEvent() + + client.write_user_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_write_user_event_rest_bad_request(transport: str = 'rest', request_type=user_event_service.WriteUserEventRequest): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.write_user_event(request) + + +def test_write_user_event_rest_error(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + user_event_service.CollectUserEventRequest, + dict, +]) +def test_collect_user_event_rest(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/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 = httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.collect_user_event(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +def test_collect_user_event_rest_required_fields(request_type=user_event_service.CollectUserEventRequest): + transport_class = transports.UserEventServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["user_event"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "userEvent" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).collect_user_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "userEvent" in jsonified_request + assert jsonified_request["userEvent"] == request_init["user_event"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["userEvent"] = 'user_event_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).collect_user_event._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("ets", "uri", "user_event", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "userEvent" in jsonified_request + assert jsonified_request["userEvent"] == 'user_event_value' + + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = httpbody_pb2.HttpBody() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 + + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.collect_user_event(request) + + expected_params = [ + ( + "userEvent", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_collect_user_event_rest_unset_required_fields(): + transport = transports.UserEventServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.collect_user_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(("ets", "uri", "userEvent", )) & set(("parent", "userEvent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_collect_user_event_rest_interceptors(null_interceptor): + transport = transports.UserEventServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.UserEventServiceRestInterceptor(), + ) + client = UserEventServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.UserEventServiceRestInterceptor, "post_collect_user_event") as post, \ + mock.patch.object(transports.UserEventServiceRestInterceptor, "pre_collect_user_event") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = user_event_service.CollectUserEventRequest.pb(user_event_service.CollectUserEventRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(httpbody_pb2.HttpBody()) + + request = user_event_service.CollectUserEventRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = httpbody_pb2.HttpBody() + + client.collect_user_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_collect_user_event_rest_bad_request(transport: str = 'rest', request_type=user_event_service.CollectUserEventRequest): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.collect_user_event(request) + + +def test_collect_user_event_rest_error(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + purge_config.PurgeUserEventsRequest, + dict, +]) +def test_purge_user_events_rest(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.purge_user_events(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_purge_user_events_rest_required_fields(request_type=purge_config.PurgeUserEventsRequest): + transport_class = transports.UserEventServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["filter"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).purge_user_events._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + jsonified_request["filter"] = 'filter_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).purge_user_events._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "filter" in jsonified_request + assert jsonified_request["filter"] == 'filter_value' + + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.purge_user_events(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_purge_user_events_rest_unset_required_fields(): + transport = transports.UserEventServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.purge_user_events._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "filter", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_purge_user_events_rest_interceptors(null_interceptor): + transport = transports.UserEventServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.UserEventServiceRestInterceptor(), + ) + client = UserEventServiceClient(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.UserEventServiceRestInterceptor, "post_purge_user_events") as post, \ + mock.patch.object(transports.UserEventServiceRestInterceptor, "pre_purge_user_events") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = purge_config.PurgeUserEventsRequest.pb(purge_config.PurgeUserEventsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = purge_config.PurgeUserEventsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.purge_user_events(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_purge_user_events_rest_bad_request(transport: str = 'rest', request_type=purge_config.PurgeUserEventsRequest): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.purge_user_events(request) + + +def test_purge_user_events_rest_error(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportUserEventsRequest, + dict, +]) +def test_import_user_events_rest(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.import_user_events(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_import_user_events_rest_required_fields(request_type=import_config.ImportUserEventsRequest): + transport_class = transports.UserEventServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_user_events._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_user_events._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.import_user_events(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_import_user_events_rest_unset_required_fields(): + transport = transports.UserEventServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.import_user_events._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_import_user_events_rest_interceptors(null_interceptor): + transport = transports.UserEventServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.UserEventServiceRestInterceptor(), + ) + client = UserEventServiceClient(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.UserEventServiceRestInterceptor, "post_import_user_events") as post, \ + mock.patch.object(transports.UserEventServiceRestInterceptor, "pre_import_user_events") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = import_config.ImportUserEventsRequest.pb(import_config.ImportUserEventsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = import_config.ImportUserEventsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.import_user_events(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_import_user_events_rest_bad_request(transport: str = 'rest', request_type=import_config.ImportUserEventsRequest): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.import_user_events(request) + + +def test_import_user_events_rest_error(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = UserEventServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.UserEventServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, + transports.UserEventServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = UserEventServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.UserEventServiceGrpcTransport, + ) + +def test_user_event_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.UserEventServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_user_event_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.discoveryengine_v1alpha.services.user_event_service.transports.UserEventServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.UserEventServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'write_user_event', + 'collect_user_event', + 'purge_user_events', + 'import_user_events', + 'get_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_user_event_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.discoveryengine_v1alpha.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.UserEventServiceTransport( + 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_user_event_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.discoveryengine_v1alpha.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.UserEventServiceTransport() + adc.assert_called_once() + + +def test_user_event_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) + UserEventServiceClient() + 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.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, + ], +) +def test_user_event_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.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, + transports.UserEventServiceRestTransport, + ], +) +def test_user_event_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.UserEventServiceGrpcTransport, grpc_helpers), + (transports.UserEventServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_user_event_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_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_user_event_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.UserEventServiceRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_user_event_service_rest_lro_client(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_user_event_service_host_no_port(transport_name): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_user_event_service_host_with_port(transport_name): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_user_event_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = UserEventServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = UserEventServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.write_user_event._session + session2 = client2.transport.write_user_event._session + assert session1 != session2 + session1 = client1.transport.collect_user_event._session + session2 = client2.transport.collect_user_event._session + assert session1 != session2 + session1 = client1.transport.purge_user_events._session + session2 = client2.transport.purge_user_events._session + assert session1 != session2 + session1 = client1.transport.import_user_events._session + session2 = client2.transport.import_user_events._session + assert session1 != session2 +def test_user_event_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.UserEventServiceGrpcTransport( + 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_user_event_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.UserEventServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_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.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_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_user_event_service_grpc_lro_client(): + client = UserEventServiceClient( + 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_user_event_service_grpc_lro_async_client(): + client = UserEventServiceAsyncClient( + 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_data_store_path(): + project = "squid" + location = "clam" + data_store = "whelk" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) + actual = UserEventServiceClient.data_store_path(project, location, data_store) + assert expected == actual + + +def test_parse_data_store_path(): + expected = { + "project": "octopus", + "location": "oyster", + "data_store": "nudibranch", + } + path = UserEventServiceClient.data_store_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_data_store_path(path) + assert expected == actual + +def test_document_path(): + project = "cuttlefish" + location = "mussel" + data_store = "winkle" + branch = "nautilus" + document = "scallop" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) + actual = UserEventServiceClient.document_path(project, location, data_store, branch, document) + assert expected == actual + + +def test_parse_document_path(): + expected = { + "project": "abalone", + "location": "squid", + "data_store": "clam", + "branch": "whelk", + "document": "octopus", + } + path = UserEventServiceClient.document_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_document_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = UserEventServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = UserEventServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = UserEventServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = UserEventServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = UserEventServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = UserEventServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = UserEventServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = UserEventServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = UserEventServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = UserEventServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.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.UserEventServiceTransport, '_prep_wrapped_messages') as prep: + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = UserEventServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_get_operation(transport: str = "grpc"): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc"): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = UserEventServiceClient( + 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 = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc"): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = UserEventServiceClient( + 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 = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = UserEventServiceClient( + 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", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/.coveragerc b/owl-bot-staging/google-cloud-discoveryengine/v1beta/.coveragerc new file mode 100644 index 000000000000..f2c9bc595be9 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/discoveryengine/__init__.py + google/cloud/discoveryengine/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/.flake8 b/owl-bot-staging/google-cloud-discoveryengine/v1beta/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/MANIFEST.in b/owl-bot-staging/google-cloud-discoveryengine/v1beta/MANIFEST.in new file mode 100644 index 000000000000..a4ea2c8c7cd8 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/discoveryengine *.py +recursive-include google/cloud/discoveryengine_v1beta *.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/README.rst b/owl-bot-staging/google-cloud-discoveryengine/v1beta/README.rst new file mode 100644 index 000000000000..25f579284266 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Discoveryengine API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Cloud Discoveryengine API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/_static/custom.css b/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/conf.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/conf.py new file mode 100644 index 000000000000..9852ef988546 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-discoveryengine documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-cloud-discoveryengine" +copyright = u"2023, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = 'en' + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-discoveryengine-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-cloud-discoveryengine.tex", + u"google-cloud-discoveryengine Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + root_doc, + "google-cloud-discoveryengine", + u"Google Cloud Discoveryengine Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-cloud-discoveryengine", + u"google-cloud-discoveryengine Documentation", + author, + "google-cloud-discoveryengine", + "GAPIC library for Google Cloud Discoveryengine API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/completion_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/completion_service.rst new file mode 100644 index 000000000000..9e9b191d4bcb --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/completion_service.rst @@ -0,0 +1,6 @@ +CompletionService +----------------------------------- + +.. automodule:: google.cloud.discoveryengine_v1beta.services.completion_service + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/conversational_search_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/conversational_search_service.rst new file mode 100644 index 000000000000..c66aac5cccba --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/conversational_search_service.rst @@ -0,0 +1,10 @@ +ConversationalSearchService +--------------------------------------------- + +.. automodule:: google.cloud.discoveryengine_v1beta.services.conversational_search_service + :members: + :inherited-members: + +.. automodule:: google.cloud.discoveryengine_v1beta.services.conversational_search_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/document_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/document_service.rst new file mode 100644 index 000000000000..edc7b754e3ff --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/document_service.rst @@ -0,0 +1,10 @@ +DocumentService +--------------------------------- + +.. automodule:: google.cloud.discoveryengine_v1beta.services.document_service + :members: + :inherited-members: + +.. automodule:: google.cloud.discoveryengine_v1beta.services.document_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/recommendation_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/recommendation_service.rst new file mode 100644 index 000000000000..97c376350840 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/recommendation_service.rst @@ -0,0 +1,6 @@ +RecommendationService +--------------------------------------- + +.. automodule:: google.cloud.discoveryengine_v1beta.services.recommendation_service + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/schema_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/schema_service.rst new file mode 100644 index 000000000000..abb2fd929203 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/schema_service.rst @@ -0,0 +1,10 @@ +SchemaService +------------------------------- + +.. automodule:: google.cloud.discoveryengine_v1beta.services.schema_service + :members: + :inherited-members: + +.. automodule:: google.cloud.discoveryengine_v1beta.services.schema_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/search_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/search_service.rst new file mode 100644 index 000000000000..5d3bbc22240d --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/search_service.rst @@ -0,0 +1,10 @@ +SearchService +------------------------------- + +.. automodule:: google.cloud.discoveryengine_v1beta.services.search_service + :members: + :inherited-members: + +.. automodule:: google.cloud.discoveryengine_v1beta.services.search_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/services_.rst b/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/services_.rst new file mode 100644 index 000000000000..ad346c2c29fe --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/services_.rst @@ -0,0 +1,12 @@ +Services for Google Cloud Discoveryengine v1beta API +==================================================== +.. toctree:: + :maxdepth: 2 + + completion_service + conversational_search_service + document_service + recommendation_service + schema_service + search_service + user_event_service diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/types_.rst b/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/types_.rst new file mode 100644 index 000000000000..7dbc3a11568c --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Discoveryengine v1beta API +================================================= + +.. automodule:: google.cloud.discoveryengine_v1beta.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/user_event_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/user_event_service.rst new file mode 100644 index 000000000000..fe6a6dc5fd95 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/user_event_service.rst @@ -0,0 +1,6 @@ +UserEventService +---------------------------------- + +.. automodule:: google.cloud.discoveryengine_v1beta.services.user_event_service + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/index.rst b/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/index.rst new file mode 100644 index 000000000000..35629474edc6 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + discoveryengine_v1beta/services + discoveryengine_v1beta/types diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine/__init__.py new file mode 100644 index 000000000000..634b5649e939 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine/__init__.py @@ -0,0 +1,175 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.discoveryengine import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.discoveryengine_v1beta.services.completion_service.client import CompletionServiceClient +from google.cloud.discoveryengine_v1beta.services.completion_service.async_client import CompletionServiceAsyncClient +from google.cloud.discoveryengine_v1beta.services.conversational_search_service.client import ConversationalSearchServiceClient +from google.cloud.discoveryengine_v1beta.services.conversational_search_service.async_client import ConversationalSearchServiceAsyncClient +from google.cloud.discoveryengine_v1beta.services.document_service.client import DocumentServiceClient +from google.cloud.discoveryengine_v1beta.services.document_service.async_client import DocumentServiceAsyncClient +from google.cloud.discoveryengine_v1beta.services.recommendation_service.client import RecommendationServiceClient +from google.cloud.discoveryengine_v1beta.services.recommendation_service.async_client import RecommendationServiceAsyncClient +from google.cloud.discoveryengine_v1beta.services.schema_service.client import SchemaServiceClient +from google.cloud.discoveryengine_v1beta.services.schema_service.async_client import SchemaServiceAsyncClient +from google.cloud.discoveryengine_v1beta.services.search_service.client import SearchServiceClient +from google.cloud.discoveryengine_v1beta.services.search_service.async_client import SearchServiceAsyncClient +from google.cloud.discoveryengine_v1beta.services.user_event_service.client import UserEventServiceClient +from google.cloud.discoveryengine_v1beta.services.user_event_service.async_client import UserEventServiceAsyncClient + +from google.cloud.discoveryengine_v1beta.types.common import CustomAttribute +from google.cloud.discoveryengine_v1beta.types.common import DoubleList +from google.cloud.discoveryengine_v1beta.types.common import Interval +from google.cloud.discoveryengine_v1beta.types.common import UserInfo +from google.cloud.discoveryengine_v1beta.types.completion_service import CompleteQueryRequest +from google.cloud.discoveryengine_v1beta.types.completion_service import CompleteQueryResponse +from google.cloud.discoveryengine_v1beta.types.conversation import Conversation +from google.cloud.discoveryengine_v1beta.types.conversation import ConversationContext +from google.cloud.discoveryengine_v1beta.types.conversation import ConversationMessage +from google.cloud.discoveryengine_v1beta.types.conversation import Reply +from google.cloud.discoveryengine_v1beta.types.conversation import TextInput +from google.cloud.discoveryengine_v1beta.types.conversational_search_service import ConverseConversationRequest +from google.cloud.discoveryengine_v1beta.types.conversational_search_service import ConverseConversationResponse +from google.cloud.discoveryengine_v1beta.types.conversational_search_service import CreateConversationRequest +from google.cloud.discoveryengine_v1beta.types.conversational_search_service import DeleteConversationRequest +from google.cloud.discoveryengine_v1beta.types.conversational_search_service import GetConversationRequest +from google.cloud.discoveryengine_v1beta.types.conversational_search_service import ListConversationsRequest +from google.cloud.discoveryengine_v1beta.types.conversational_search_service import ListConversationsResponse +from google.cloud.discoveryengine_v1beta.types.conversational_search_service import UpdateConversationRequest +from google.cloud.discoveryengine_v1beta.types.document import Document +from google.cloud.discoveryengine_v1beta.types.document_service import CreateDocumentRequest +from google.cloud.discoveryengine_v1beta.types.document_service import DeleteDocumentRequest +from google.cloud.discoveryengine_v1beta.types.document_service import GetDocumentRequest +from google.cloud.discoveryengine_v1beta.types.document_service import ListDocumentsRequest +from google.cloud.discoveryengine_v1beta.types.document_service import ListDocumentsResponse +from google.cloud.discoveryengine_v1beta.types.document_service import UpdateDocumentRequest +from google.cloud.discoveryengine_v1beta.types.import_config import BigQuerySource +from google.cloud.discoveryengine_v1beta.types.import_config import GcsSource +from google.cloud.discoveryengine_v1beta.types.import_config import ImportDocumentsMetadata +from google.cloud.discoveryengine_v1beta.types.import_config import ImportDocumentsRequest +from google.cloud.discoveryengine_v1beta.types.import_config import ImportDocumentsResponse +from google.cloud.discoveryengine_v1beta.types.import_config import ImportErrorConfig +from google.cloud.discoveryengine_v1beta.types.import_config import ImportUserEventsMetadata +from google.cloud.discoveryengine_v1beta.types.import_config import ImportUserEventsRequest +from google.cloud.discoveryengine_v1beta.types.import_config import ImportUserEventsResponse +from google.cloud.discoveryengine_v1beta.types.purge_config import PurgeDocumentsMetadata +from google.cloud.discoveryengine_v1beta.types.purge_config import PurgeDocumentsRequest +from google.cloud.discoveryengine_v1beta.types.purge_config import PurgeDocumentsResponse +from google.cloud.discoveryengine_v1beta.types.recommendation_service import RecommendRequest +from google.cloud.discoveryengine_v1beta.types.recommendation_service import RecommendResponse +from google.cloud.discoveryengine_v1beta.types.schema import Schema +from google.cloud.discoveryengine_v1beta.types.schema_service import CreateSchemaMetadata +from google.cloud.discoveryengine_v1beta.types.schema_service import CreateSchemaRequest +from google.cloud.discoveryengine_v1beta.types.schema_service import DeleteSchemaMetadata +from google.cloud.discoveryengine_v1beta.types.schema_service import DeleteSchemaRequest +from google.cloud.discoveryengine_v1beta.types.schema_service import GetSchemaRequest +from google.cloud.discoveryengine_v1beta.types.schema_service import ListSchemasRequest +from google.cloud.discoveryengine_v1beta.types.schema_service import ListSchemasResponse +from google.cloud.discoveryengine_v1beta.types.schema_service import UpdateSchemaMetadata +from google.cloud.discoveryengine_v1beta.types.schema_service import UpdateSchemaRequest +from google.cloud.discoveryengine_v1beta.types.search_service import SearchRequest +from google.cloud.discoveryengine_v1beta.types.search_service import SearchResponse +from google.cloud.discoveryengine_v1beta.types.user_event import CompletionInfo +from google.cloud.discoveryengine_v1beta.types.user_event import DocumentInfo +from google.cloud.discoveryengine_v1beta.types.user_event import MediaInfo +from google.cloud.discoveryengine_v1beta.types.user_event import PageInfo +from google.cloud.discoveryengine_v1beta.types.user_event import PanelInfo +from google.cloud.discoveryengine_v1beta.types.user_event import SearchInfo +from google.cloud.discoveryengine_v1beta.types.user_event import TransactionInfo +from google.cloud.discoveryengine_v1beta.types.user_event import UserEvent +from google.cloud.discoveryengine_v1beta.types.user_event_service import CollectUserEventRequest +from google.cloud.discoveryengine_v1beta.types.user_event_service import WriteUserEventRequest + +__all__ = ('CompletionServiceClient', + 'CompletionServiceAsyncClient', + 'ConversationalSearchServiceClient', + 'ConversationalSearchServiceAsyncClient', + 'DocumentServiceClient', + 'DocumentServiceAsyncClient', + 'RecommendationServiceClient', + 'RecommendationServiceAsyncClient', + 'SchemaServiceClient', + 'SchemaServiceAsyncClient', + 'SearchServiceClient', + 'SearchServiceAsyncClient', + 'UserEventServiceClient', + 'UserEventServiceAsyncClient', + 'CustomAttribute', + 'DoubleList', + 'Interval', + 'UserInfo', + 'CompleteQueryRequest', + 'CompleteQueryResponse', + 'Conversation', + 'ConversationContext', + 'ConversationMessage', + 'Reply', + 'TextInput', + 'ConverseConversationRequest', + 'ConverseConversationResponse', + 'CreateConversationRequest', + 'DeleteConversationRequest', + 'GetConversationRequest', + 'ListConversationsRequest', + 'ListConversationsResponse', + 'UpdateConversationRequest', + 'Document', + 'CreateDocumentRequest', + 'DeleteDocumentRequest', + 'GetDocumentRequest', + 'ListDocumentsRequest', + 'ListDocumentsResponse', + 'UpdateDocumentRequest', + 'BigQuerySource', + 'GcsSource', + 'ImportDocumentsMetadata', + 'ImportDocumentsRequest', + 'ImportDocumentsResponse', + 'ImportErrorConfig', + 'ImportUserEventsMetadata', + 'ImportUserEventsRequest', + 'ImportUserEventsResponse', + 'PurgeDocumentsMetadata', + 'PurgeDocumentsRequest', + 'PurgeDocumentsResponse', + 'RecommendRequest', + 'RecommendResponse', + 'Schema', + 'CreateSchemaMetadata', + 'CreateSchemaRequest', + 'DeleteSchemaMetadata', + 'DeleteSchemaRequest', + 'GetSchemaRequest', + 'ListSchemasRequest', + 'ListSchemasResponse', + 'UpdateSchemaMetadata', + 'UpdateSchemaRequest', + 'SearchRequest', + 'SearchResponse', + 'CompletionInfo', + 'DocumentInfo', + 'MediaInfo', + 'PageInfo', + 'PanelInfo', + 'SearchInfo', + 'TransactionInfo', + 'UserEvent', + 'CollectUserEventRequest', + 'WriteUserEventRequest', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine/gapic_version.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine/gapic_version.py new file mode 100644 index 000000000000..360a0d13ebdd --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine/py.typed b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine/py.typed new file mode 100644 index 000000000000..2ff6437cf473 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-discoveryengine package uses inline types. diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/__init__.py new file mode 100644 index 000000000000..d49951ee6fba --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/__init__.py @@ -0,0 +1,176 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.discoveryengine_v1beta import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.completion_service import CompletionServiceClient +from .services.completion_service import CompletionServiceAsyncClient +from .services.conversational_search_service import ConversationalSearchServiceClient +from .services.conversational_search_service import ConversationalSearchServiceAsyncClient +from .services.document_service import DocumentServiceClient +from .services.document_service import DocumentServiceAsyncClient +from .services.recommendation_service import RecommendationServiceClient +from .services.recommendation_service import RecommendationServiceAsyncClient +from .services.schema_service import SchemaServiceClient +from .services.schema_service import SchemaServiceAsyncClient +from .services.search_service import SearchServiceClient +from .services.search_service import SearchServiceAsyncClient +from .services.user_event_service import UserEventServiceClient +from .services.user_event_service import UserEventServiceAsyncClient + +from .types.common import CustomAttribute +from .types.common import DoubleList +from .types.common import Interval +from .types.common import UserInfo +from .types.completion_service import CompleteQueryRequest +from .types.completion_service import CompleteQueryResponse +from .types.conversation import Conversation +from .types.conversation import ConversationContext +from .types.conversation import ConversationMessage +from .types.conversation import Reply +from .types.conversation import TextInput +from .types.conversational_search_service import ConverseConversationRequest +from .types.conversational_search_service import ConverseConversationResponse +from .types.conversational_search_service import CreateConversationRequest +from .types.conversational_search_service import DeleteConversationRequest +from .types.conversational_search_service import GetConversationRequest +from .types.conversational_search_service import ListConversationsRequest +from .types.conversational_search_service import ListConversationsResponse +from .types.conversational_search_service import UpdateConversationRequest +from .types.document import Document +from .types.document_service import CreateDocumentRequest +from .types.document_service import DeleteDocumentRequest +from .types.document_service import GetDocumentRequest +from .types.document_service import ListDocumentsRequest +from .types.document_service import ListDocumentsResponse +from .types.document_service import UpdateDocumentRequest +from .types.import_config import BigQuerySource +from .types.import_config import GcsSource +from .types.import_config import ImportDocumentsMetadata +from .types.import_config import ImportDocumentsRequest +from .types.import_config import ImportDocumentsResponse +from .types.import_config import ImportErrorConfig +from .types.import_config import ImportUserEventsMetadata +from .types.import_config import ImportUserEventsRequest +from .types.import_config import ImportUserEventsResponse +from .types.purge_config import PurgeDocumentsMetadata +from .types.purge_config import PurgeDocumentsRequest +from .types.purge_config import PurgeDocumentsResponse +from .types.recommendation_service import RecommendRequest +from .types.recommendation_service import RecommendResponse +from .types.schema import Schema +from .types.schema_service import CreateSchemaMetadata +from .types.schema_service import CreateSchemaRequest +from .types.schema_service import DeleteSchemaMetadata +from .types.schema_service import DeleteSchemaRequest +from .types.schema_service import GetSchemaRequest +from .types.schema_service import ListSchemasRequest +from .types.schema_service import ListSchemasResponse +from .types.schema_service import UpdateSchemaMetadata +from .types.schema_service import UpdateSchemaRequest +from .types.search_service import SearchRequest +from .types.search_service import SearchResponse +from .types.user_event import CompletionInfo +from .types.user_event import DocumentInfo +from .types.user_event import MediaInfo +from .types.user_event import PageInfo +from .types.user_event import PanelInfo +from .types.user_event import SearchInfo +from .types.user_event import TransactionInfo +from .types.user_event import UserEvent +from .types.user_event_service import CollectUserEventRequest +from .types.user_event_service import WriteUserEventRequest + +__all__ = ( + 'CompletionServiceAsyncClient', + 'ConversationalSearchServiceAsyncClient', + 'DocumentServiceAsyncClient', + 'RecommendationServiceAsyncClient', + 'SchemaServiceAsyncClient', + 'SearchServiceAsyncClient', + 'UserEventServiceAsyncClient', +'BigQuerySource', +'CollectUserEventRequest', +'CompleteQueryRequest', +'CompleteQueryResponse', +'CompletionInfo', +'CompletionServiceClient', +'Conversation', +'ConversationContext', +'ConversationMessage', +'ConversationalSearchServiceClient', +'ConverseConversationRequest', +'ConverseConversationResponse', +'CreateConversationRequest', +'CreateDocumentRequest', +'CreateSchemaMetadata', +'CreateSchemaRequest', +'CustomAttribute', +'DeleteConversationRequest', +'DeleteDocumentRequest', +'DeleteSchemaMetadata', +'DeleteSchemaRequest', +'Document', +'DocumentInfo', +'DocumentServiceClient', +'DoubleList', +'GcsSource', +'GetConversationRequest', +'GetDocumentRequest', +'GetSchemaRequest', +'ImportDocumentsMetadata', +'ImportDocumentsRequest', +'ImportDocumentsResponse', +'ImportErrorConfig', +'ImportUserEventsMetadata', +'ImportUserEventsRequest', +'ImportUserEventsResponse', +'Interval', +'ListConversationsRequest', +'ListConversationsResponse', +'ListDocumentsRequest', +'ListDocumentsResponse', +'ListSchemasRequest', +'ListSchemasResponse', +'MediaInfo', +'PageInfo', +'PanelInfo', +'PurgeDocumentsMetadata', +'PurgeDocumentsRequest', +'PurgeDocumentsResponse', +'RecommendRequest', +'RecommendResponse', +'RecommendationServiceClient', +'Reply', +'Schema', +'SchemaServiceClient', +'SearchInfo', +'SearchRequest', +'SearchResponse', +'SearchServiceClient', +'TextInput', +'TransactionInfo', +'UpdateConversationRequest', +'UpdateDocumentRequest', +'UpdateSchemaMetadata', +'UpdateSchemaRequest', +'UserEvent', +'UserEventServiceClient', +'UserInfo', +'WriteUserEventRequest', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/gapic_metadata.json b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/gapic_metadata.json new file mode 100644 index 000000000000..88141f3bd79e --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/gapic_metadata.json @@ -0,0 +1,502 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.discoveryengine_v1beta", + "protoPackage": "google.cloud.discoveryengine.v1beta", + "schema": "1.0", + "services": { + "CompletionService": { + "clients": { + "grpc": { + "libraryClient": "CompletionServiceClient", + "rpcs": { + "CompleteQuery": { + "methods": [ + "complete_query" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CompletionServiceAsyncClient", + "rpcs": { + "CompleteQuery": { + "methods": [ + "complete_query" + ] + } + } + }, + "rest": { + "libraryClient": "CompletionServiceClient", + "rpcs": { + "CompleteQuery": { + "methods": [ + "complete_query" + ] + } + } + } + } + }, + "ConversationalSearchService": { + "clients": { + "grpc": { + "libraryClient": "ConversationalSearchServiceClient", + "rpcs": { + "ConverseConversation": { + "methods": [ + "converse_conversation" + ] + }, + "CreateConversation": { + "methods": [ + "create_conversation" + ] + }, + "DeleteConversation": { + "methods": [ + "delete_conversation" + ] + }, + "GetConversation": { + "methods": [ + "get_conversation" + ] + }, + "ListConversations": { + "methods": [ + "list_conversations" + ] + }, + "UpdateConversation": { + "methods": [ + "update_conversation" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ConversationalSearchServiceAsyncClient", + "rpcs": { + "ConverseConversation": { + "methods": [ + "converse_conversation" + ] + }, + "CreateConversation": { + "methods": [ + "create_conversation" + ] + }, + "DeleteConversation": { + "methods": [ + "delete_conversation" + ] + }, + "GetConversation": { + "methods": [ + "get_conversation" + ] + }, + "ListConversations": { + "methods": [ + "list_conversations" + ] + }, + "UpdateConversation": { + "methods": [ + "update_conversation" + ] + } + } + }, + "rest": { + "libraryClient": "ConversationalSearchServiceClient", + "rpcs": { + "ConverseConversation": { + "methods": [ + "converse_conversation" + ] + }, + "CreateConversation": { + "methods": [ + "create_conversation" + ] + }, + "DeleteConversation": { + "methods": [ + "delete_conversation" + ] + }, + "GetConversation": { + "methods": [ + "get_conversation" + ] + }, + "ListConversations": { + "methods": [ + "list_conversations" + ] + }, + "UpdateConversation": { + "methods": [ + "update_conversation" + ] + } + } + } + } + }, + "DocumentService": { + "clients": { + "grpc": { + "libraryClient": "DocumentServiceClient", + "rpcs": { + "CreateDocument": { + "methods": [ + "create_document" + ] + }, + "DeleteDocument": { + "methods": [ + "delete_document" + ] + }, + "GetDocument": { + "methods": [ + "get_document" + ] + }, + "ImportDocuments": { + "methods": [ + "import_documents" + ] + }, + "ListDocuments": { + "methods": [ + "list_documents" + ] + }, + "PurgeDocuments": { + "methods": [ + "purge_documents" + ] + }, + "UpdateDocument": { + "methods": [ + "update_document" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DocumentServiceAsyncClient", + "rpcs": { + "CreateDocument": { + "methods": [ + "create_document" + ] + }, + "DeleteDocument": { + "methods": [ + "delete_document" + ] + }, + "GetDocument": { + "methods": [ + "get_document" + ] + }, + "ImportDocuments": { + "methods": [ + "import_documents" + ] + }, + "ListDocuments": { + "methods": [ + "list_documents" + ] + }, + "PurgeDocuments": { + "methods": [ + "purge_documents" + ] + }, + "UpdateDocument": { + "methods": [ + "update_document" + ] + } + } + }, + "rest": { + "libraryClient": "DocumentServiceClient", + "rpcs": { + "CreateDocument": { + "methods": [ + "create_document" + ] + }, + "DeleteDocument": { + "methods": [ + "delete_document" + ] + }, + "GetDocument": { + "methods": [ + "get_document" + ] + }, + "ImportDocuments": { + "methods": [ + "import_documents" + ] + }, + "ListDocuments": { + "methods": [ + "list_documents" + ] + }, + "PurgeDocuments": { + "methods": [ + "purge_documents" + ] + }, + "UpdateDocument": { + "methods": [ + "update_document" + ] + } + } + } + } + }, + "RecommendationService": { + "clients": { + "grpc": { + "libraryClient": "RecommendationServiceClient", + "rpcs": { + "Recommend": { + "methods": [ + "recommend" + ] + } + } + }, + "grpc-async": { + "libraryClient": "RecommendationServiceAsyncClient", + "rpcs": { + "Recommend": { + "methods": [ + "recommend" + ] + } + } + }, + "rest": { + "libraryClient": "RecommendationServiceClient", + "rpcs": { + "Recommend": { + "methods": [ + "recommend" + ] + } + } + } + } + }, + "SchemaService": { + "clients": { + "grpc": { + "libraryClient": "SchemaServiceClient", + "rpcs": { + "CreateSchema": { + "methods": [ + "create_schema" + ] + }, + "DeleteSchema": { + "methods": [ + "delete_schema" + ] + }, + "GetSchema": { + "methods": [ + "get_schema" + ] + }, + "ListSchemas": { + "methods": [ + "list_schemas" + ] + }, + "UpdateSchema": { + "methods": [ + "update_schema" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SchemaServiceAsyncClient", + "rpcs": { + "CreateSchema": { + "methods": [ + "create_schema" + ] + }, + "DeleteSchema": { + "methods": [ + "delete_schema" + ] + }, + "GetSchema": { + "methods": [ + "get_schema" + ] + }, + "ListSchemas": { + "methods": [ + "list_schemas" + ] + }, + "UpdateSchema": { + "methods": [ + "update_schema" + ] + } + } + }, + "rest": { + "libraryClient": "SchemaServiceClient", + "rpcs": { + "CreateSchema": { + "methods": [ + "create_schema" + ] + }, + "DeleteSchema": { + "methods": [ + "delete_schema" + ] + }, + "GetSchema": { + "methods": [ + "get_schema" + ] + }, + "ListSchemas": { + "methods": [ + "list_schemas" + ] + }, + "UpdateSchema": { + "methods": [ + "update_schema" + ] + } + } + } + } + }, + "SearchService": { + "clients": { + "grpc": { + "libraryClient": "SearchServiceClient", + "rpcs": { + "Search": { + "methods": [ + "search" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SearchServiceAsyncClient", + "rpcs": { + "Search": { + "methods": [ + "search" + ] + } + } + }, + "rest": { + "libraryClient": "SearchServiceClient", + "rpcs": { + "Search": { + "methods": [ + "search" + ] + } + } + } + } + }, + "UserEventService": { + "clients": { + "grpc": { + "libraryClient": "UserEventServiceClient", + "rpcs": { + "CollectUserEvent": { + "methods": [ + "collect_user_event" + ] + }, + "ImportUserEvents": { + "methods": [ + "import_user_events" + ] + }, + "WriteUserEvent": { + "methods": [ + "write_user_event" + ] + } + } + }, + "grpc-async": { + "libraryClient": "UserEventServiceAsyncClient", + "rpcs": { + "CollectUserEvent": { + "methods": [ + "collect_user_event" + ] + }, + "ImportUserEvents": { + "methods": [ + "import_user_events" + ] + }, + "WriteUserEvent": { + "methods": [ + "write_user_event" + ] + } + } + }, + "rest": { + "libraryClient": "UserEventServiceClient", + "rpcs": { + "CollectUserEvent": { + "methods": [ + "collect_user_event" + ] + }, + "ImportUserEvents": { + "methods": [ + "import_user_events" + ] + }, + "WriteUserEvent": { + "methods": [ + "write_user_event" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/gapic_version.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/gapic_version.py new file mode 100644 index 000000000000..360a0d13ebdd --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/py.typed b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/py.typed new file mode 100644 index 000000000000..2ff6437cf473 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-discoveryengine package uses inline types. diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/__init__.py new file mode 100644 index 000000000000..89a37dc92c5a --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/__init__.py new file mode 100644 index 000000000000..440cbfb40963 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import CompletionServiceClient +from .async_client import CompletionServiceAsyncClient + +__all__ = ( + 'CompletionServiceClient', + 'CompletionServiceAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/async_client.py new file mode 100644 index 000000000000..b2bd38ba29cf --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/async_client.py @@ -0,0 +1,386 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.discoveryengine_v1beta.types import completion_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport +from .client import CompletionServiceClient + + +class CompletionServiceAsyncClient: + """Service for Auto-Completion.""" + + _client: CompletionServiceClient + + DEFAULT_ENDPOINT = CompletionServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = CompletionServiceClient.DEFAULT_MTLS_ENDPOINT + + data_store_path = staticmethod(CompletionServiceClient.data_store_path) + parse_data_store_path = staticmethod(CompletionServiceClient.parse_data_store_path) + common_billing_account_path = staticmethod(CompletionServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(CompletionServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(CompletionServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(CompletionServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(CompletionServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(CompletionServiceClient.parse_common_organization_path) + common_project_path = staticmethod(CompletionServiceClient.common_project_path) + parse_common_project_path = staticmethod(CompletionServiceClient.parse_common_project_path) + common_location_path = staticmethod(CompletionServiceClient.common_location_path) + parse_common_location_path = staticmethod(CompletionServiceClient.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: + CompletionServiceAsyncClient: The constructed client. + """ + return CompletionServiceClient.from_service_account_info.__func__(CompletionServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceAsyncClient: The constructed client. + """ + return CompletionServiceClient.from_service_account_file.__func__(CompletionServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return CompletionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> CompletionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CompletionServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(CompletionServiceClient).get_transport_class, type(CompletionServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, CompletionServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the completion 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 (Union[str, ~.CompletionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = CompletionServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def complete_query(self, + request: Optional[Union[completion_service.CompleteQueryRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> completion_service.CompleteQueryResponse: + r"""Completes the specified user input with keyword + suggestions. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_complete_query(): + # Create a client + client = discoveryengine_v1beta.CompletionServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.CompleteQueryRequest( + data_store="data_store_value", + query="query_value", + ) + + # Make the request + response = await client.complete_query(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.CompleteQueryRequest, dict]]): + The request object. Request message for + [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1beta.CompletionService.CompleteQuery] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.types.CompleteQueryResponse: + Response message for + [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1beta.CompletionService.CompleteQuery] + method. + + """ + # Create or coerce a protobuf request object. + request = completion_service.CompleteQueryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.complete_query, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("data_store", request.data_store), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "CompletionServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "CompletionServiceAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/client.py new file mode 100644 index 000000000000..c19b68b93438 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/client.py @@ -0,0 +1,594 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.discoveryengine_v1beta.types import completion_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import CompletionServiceGrpcTransport +from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport +from .transports.rest import CompletionServiceRestTransport + + +class CompletionServiceClientMeta(type): + """Metaclass for the CompletionService 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[CompletionServiceTransport]] + _transport_registry["grpc"] = CompletionServiceGrpcTransport + _transport_registry["grpc_asyncio"] = CompletionServiceGrpcAsyncIOTransport + _transport_registry["rest"] = CompletionServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[CompletionServiceTransport]: + """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 CompletionServiceClient(metaclass=CompletionServiceClientMeta): + """Service for Auto-Completion.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + CompletionServiceClient: 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: + CompletionServiceClient: 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) -> CompletionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + CompletionServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def data_store_path(project: str,location: str,data_store: str,) -> str: + """Returns a fully-qualified data_store string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) + + @staticmethod + def parse_data_store_path(path: str) -> Dict[str,str]: + """Parses a data_store path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, CompletionServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the completion 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 (Union[str, CompletionServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, CompletionServiceTransport): + # transport is a CompletionServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def complete_query(self, + request: Optional[Union[completion_service.CompleteQueryRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> completion_service.CompleteQueryResponse: + r"""Completes the specified user input with keyword + suggestions. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_complete_query(): + # Create a client + client = discoveryengine_v1beta.CompletionServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.CompleteQueryRequest( + data_store="data_store_value", + query="query_value", + ) + + # Make the request + response = client.complete_query(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.CompleteQueryRequest, dict]): + The request object. Request message for + [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1beta.CompletionService.CompleteQuery] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.types.CompleteQueryResponse: + Response message for + [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1beta.CompletionService.CompleteQuery] + method. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a completion_service.CompleteQueryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, completion_service.CompleteQueryRequest): + request = completion_service.CompleteQueryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.complete_query] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("data_store", request.data_store), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "CompletionServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "CompletionServiceClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/__init__.py new file mode 100644 index 000000000000..f32ad4419b13 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import CompletionServiceTransport +from .grpc import CompletionServiceGrpcTransport +from .grpc_asyncio import CompletionServiceGrpcAsyncIOTransport +from .rest import CompletionServiceRestTransport +from .rest import CompletionServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] +_transport_registry['grpc'] = CompletionServiceGrpcTransport +_transport_registry['grpc_asyncio'] = CompletionServiceGrpcAsyncIOTransport +_transport_registry['rest'] = CompletionServiceRestTransport + +__all__ = ( + 'CompletionServiceTransport', + 'CompletionServiceGrpcTransport', + 'CompletionServiceGrpcAsyncIOTransport', + 'CompletionServiceRestTransport', + 'CompletionServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/base.py new file mode 100644 index 000000000000..2828065a3195 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/base.py @@ -0,0 +1,168 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.discoveryengine_v1beta.types import completion_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class CompletionServiceTransport(abc.ABC): + """Abstract transport class for CompletionService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'discoveryengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.complete_query: gapic_v1.method.wrap_method( + self.complete_query, + 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 complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + Union[ + completion_service.CompleteQueryResponse, + Awaitable[completion_service.CompleteQueryResponse] + ]]: + 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 kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'CompletionServiceTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/grpc.py new file mode 100644 index 000000000000..497a5bdf3aca --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/grpc.py @@ -0,0 +1,303 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.discoveryengine_v1beta.types import completion_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO + + +class CompletionServiceGrpcTransport(CompletionServiceTransport): + """gRPC backend transport for CompletionService. + + Service for Auto-Completion. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + completion_service.CompleteQueryResponse]: + r"""Return a callable for the complete query method over gRPC. + + Completes the specified user input with keyword + suggestions. + + Returns: + Callable[[~.CompleteQueryRequest], + ~.CompleteQueryResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'complete_query' not in self._stubs: + self._stubs['complete_query'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.CompletionService/CompleteQuery', + request_serializer=completion_service.CompleteQueryRequest.serialize, + response_deserializer=completion_service.CompleteQueryResponse.deserialize, + ) + return self._stubs['complete_query'] + + def close(self): + self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'CompletionServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..1a09ba0df8f6 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/grpc_asyncio.py @@ -0,0 +1,302 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.discoveryengine_v1beta.types import completion_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import CompletionServiceGrpcTransport + + +class CompletionServiceGrpcAsyncIOTransport(CompletionServiceTransport): + """gRPC AsyncIO backend transport for CompletionService. + + Service for Auto-Completion. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + Awaitable[completion_service.CompleteQueryResponse]]: + r"""Return a callable for the complete query method over gRPC. + + Completes the specified user input with keyword + suggestions. + + Returns: + Callable[[~.CompleteQueryRequest], + Awaitable[~.CompleteQueryResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'complete_query' not in self._stubs: + self._stubs['complete_query'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.CompletionService/CompleteQuery', + request_serializer=completion_service.CompleteQueryRequest.serialize, + response_deserializer=completion_service.CompleteQueryResponse.deserialize, + ) + return self._stubs['complete_query'] + + def close(self): + return self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ( + 'CompletionServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/rest.py new file mode 100644 index 000000000000..e36c91d06daa --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/rest.py @@ -0,0 +1,566 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.cloud.location import locations_pb2 # type: ignore +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.discoveryengine_v1beta.types import completion_service +from google.longrunning import operations_pb2 # type: ignore + +from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class CompletionServiceRestInterceptor: + """Interceptor for CompletionService. + + 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 CompletionServiceRestTransport. + + .. code-block:: python + class MyCustomCompletionServiceInterceptor(CompletionServiceRestInterceptor): + def pre_complete_query(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_complete_query(self, response): + logging.log(f"Received response: {response}") + return response + + transport = CompletionServiceRestTransport(interceptor=MyCustomCompletionServiceInterceptor()) + client = CompletionServiceClient(transport=transport) + + + """ + def pre_complete_query(self, request: completion_service.CompleteQueryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[completion_service.CompleteQueryRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for complete_query + + Override in a subclass to manipulate the request or metadata + before they are sent to the CompletionService server. + """ + return request, metadata + + def post_complete_query(self, response: completion_service.CompleteQueryResponse) -> completion_service.CompleteQueryResponse: + """Post-rpc interceptor for complete_query + + Override in a subclass to manipulate the response + after it is returned by the CompletionService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the CompletionService 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 CompletionService server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the CompletionService 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 CompletionService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class CompletionServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: CompletionServiceRestInterceptor + + +class CompletionServiceRestTransport(CompletionServiceTransport): + """REST backend transport for CompletionService. + + Service for Auto-Completion. + + 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 = 'discoveryengine.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[CompletionServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or CompletionServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CompleteQuery(CompletionServiceRestStub): + def __hash__(self): + return hash("CompleteQuery") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "query" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: completion_service.CompleteQueryRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> completion_service.CompleteQueryResponse: + r"""Call the complete query method over HTTP. + + Args: + request (~.completion_service.CompleteQueryRequest): + The request object. Request message for + [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1beta.CompletionService.CompleteQuery] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.completion_service.CompleteQueryResponse: + Response message for + [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1beta.CompletionService.CompleteQuery] + method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{data_store=projects/*/locations/*/dataStores/*}:completeQuery', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{data_store=projects/*/locations/*/collections/*/dataStores/*}:completeQuery', + }, + ] + request, metadata = self._interceptor.pre_complete_query(request, metadata) + pb_request = completion_service.CompleteQueryRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = completion_service.CompleteQueryResponse() + pb_resp = completion_service.CompleteQueryResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_complete_query(resp) + return resp + + @property + def complete_query(self) -> Callable[ + [completion_service.CompleteQueryRequest], + completion_service.CompleteQueryResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CompleteQuery(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(CompletionServiceRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(CompletionServiceRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'CompletionServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/__init__.py new file mode 100644 index 000000000000..4bf42b241a8b --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import ConversationalSearchServiceClient +from .async_client import ConversationalSearchServiceAsyncClient + +__all__ = ( + 'ConversationalSearchServiceClient', + 'ConversationalSearchServiceAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/async_client.py new file mode 100644 index 000000000000..d1253ea0826d --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/async_client.py @@ -0,0 +1,971 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.discoveryengine_v1beta.services.conversational_search_service import pagers +from google.cloud.discoveryengine_v1beta.types import conversation +from google.cloud.discoveryengine_v1beta.types import conversation as gcd_conversation +from google.cloud.discoveryengine_v1beta.types import conversational_search_service +from google.cloud.discoveryengine_v1beta.types import search_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ConversationalSearchServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ConversationalSearchServiceGrpcAsyncIOTransport +from .client import ConversationalSearchServiceClient + + +class ConversationalSearchServiceAsyncClient: + """Service for conversational search.""" + + _client: ConversationalSearchServiceClient + + DEFAULT_ENDPOINT = ConversationalSearchServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ConversationalSearchServiceClient.DEFAULT_MTLS_ENDPOINT + + conversation_path = staticmethod(ConversationalSearchServiceClient.conversation_path) + parse_conversation_path = staticmethod(ConversationalSearchServiceClient.parse_conversation_path) + data_store_path = staticmethod(ConversationalSearchServiceClient.data_store_path) + parse_data_store_path = staticmethod(ConversationalSearchServiceClient.parse_data_store_path) + document_path = staticmethod(ConversationalSearchServiceClient.document_path) + parse_document_path = staticmethod(ConversationalSearchServiceClient.parse_document_path) + serving_config_path = staticmethod(ConversationalSearchServiceClient.serving_config_path) + parse_serving_config_path = staticmethod(ConversationalSearchServiceClient.parse_serving_config_path) + common_billing_account_path = staticmethod(ConversationalSearchServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ConversationalSearchServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ConversationalSearchServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(ConversationalSearchServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(ConversationalSearchServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(ConversationalSearchServiceClient.parse_common_organization_path) + common_project_path = staticmethod(ConversationalSearchServiceClient.common_project_path) + parse_common_project_path = staticmethod(ConversationalSearchServiceClient.parse_common_project_path) + common_location_path = staticmethod(ConversationalSearchServiceClient.common_location_path) + parse_common_location_path = staticmethod(ConversationalSearchServiceClient.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: + ConversationalSearchServiceAsyncClient: The constructed client. + """ + return ConversationalSearchServiceClient.from_service_account_info.__func__(ConversationalSearchServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ConversationalSearchServiceAsyncClient: The constructed client. + """ + return ConversationalSearchServiceClient.from_service_account_file.__func__(ConversationalSearchServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return ConversationalSearchServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ConversationalSearchServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ConversationalSearchServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ConversationalSearchServiceClient).get_transport_class, type(ConversationalSearchServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ConversationalSearchServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the conversational search 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 (Union[str, ~.ConversationalSearchServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ConversationalSearchServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def converse_conversation(self, + request: Optional[Union[conversational_search_service.ConverseConversationRequest, dict]] = None, + *, + name: Optional[str] = None, + query: Optional[conversation.TextInput] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversational_search_service.ConverseConversationResponse: + r"""Converses 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 discoveryengine_v1beta + + async def sample_converse_conversation(): + # Create a client + client = discoveryengine_v1beta.ConversationalSearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ConverseConversationRequest( + name="name_value", + ) + + # Make the request + response = await client.converse_conversation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.ConverseConversationRequest, dict]]): + The request object. Request message for + [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1beta.ConversationalSearchService.ConverseConversation] + method. + name (:class:`str`): + Required. The resource name of the Conversation to get. + Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}``. + Use + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/-`` + to activate auto session mode, which automatically + creates a new conversation inside a ConverseConversation + session. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + query (:class:`google.cloud.discoveryengine_v1beta.types.TextInput`): + Required. Current user input. + This corresponds to the ``query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.types.ConverseConversationResponse: + Response message for + [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1beta.ConversationalSearchService.ConverseConversation] + method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, query]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = conversational_search_service.ConverseConversationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if query is not None: + request.query = query + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.converse_conversation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_conversation(self, + request: Optional[Union[conversational_search_service.CreateConversationRequest, dict]] = None, + *, + parent: Optional[str] = None, + conversation: Optional[gcd_conversation.Conversation] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_conversation.Conversation: + r"""Creates a Conversation. + + If the + [Conversation][google.cloud.discoveryengine.v1beta.Conversation] + to create already exists, an ALREADY_EXISTS error is returned. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_create_conversation(): + # Create a client + client = discoveryengine_v1beta.ConversationalSearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.CreateConversationRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_conversation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.CreateConversationRequest, dict]]): + The request object. Request for CreateConversation + method. + parent (:class:`str`): + Required. Full resource name of parent data store. + Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + conversation (:class:`google.cloud.discoveryengine_v1beta.types.Conversation`): + Required. The conversation to create. + This corresponds to the ``conversation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.types.Conversation: + External conversation proto + definition. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, conversation]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = conversational_search_service.CreateConversationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if conversation is not None: + request.conversation = conversation + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_conversation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_conversation(self, + request: Optional[Union[conversational_search_service.DeleteConversationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a Conversation. + + If the + [Conversation][google.cloud.discoveryengine.v1beta.Conversation] + to delete does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_delete_conversation(): + # Create a client + client = discoveryengine_v1beta.ConversationalSearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.DeleteConversationRequest( + name="name_value", + ) + + # Make the request + await client.delete_conversation(request=request) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.DeleteConversationRequest, dict]]): + The request object. Request for DeleteConversation + method. + name (:class:`str`): + Required. The resource name of the Conversation to + delete. Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = conversational_search_service.DeleteConversationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_conversation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def update_conversation(self, + request: Optional[Union[conversational_search_service.UpdateConversationRequest, dict]] = None, + *, + conversation: Optional[gcd_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, str]] = (), + ) -> gcd_conversation.Conversation: + r"""Updates a Conversation. + + [Conversation][google.cloud.discoveryengine.v1beta.Conversation] + action type cannot be changed. If the + [Conversation][google.cloud.discoveryengine.v1beta.Conversation] + to update does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_update_conversation(): + # Create a client + client = discoveryengine_v1beta.ConversationalSearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.UpdateConversationRequest( + ) + + # Make the request + response = await client.update_conversation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.UpdateConversationRequest, dict]]): + The request object. Request for UpdateConversation + method. + conversation (:class:`google.cloud.discoveryengine_v1beta.types.Conversation`): + Required. The Conversation to update. + 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`): + Indicates which fields in the provided + [Conversation][google.cloud.discoveryengine.v1beta.Conversation] + to update. The following are NOT supported: + + - [conversation.name][] + + If not set or empty, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.types.Conversation: + External conversation proto + definition. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([conversation, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = conversational_search_service.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 = gapic_v1.method_async.wrap_method( + self._client._transport.update_conversation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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), + )), + ) + + # 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[conversational_search_service.GetConversationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversation.Conversation: + r"""Gets 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 discoveryengine_v1beta + + async def sample_get_conversation(): + # Create a client + client = discoveryengine_v1beta.ConversationalSearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GetConversationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_conversation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.GetConversationRequest, dict]]): + The request object. Request for GetConversation method. + name (:class:`str`): + Required. The resource name of the Conversation to get. + Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.types.Conversation: + External conversation proto + definition. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = conversational_search_service.GetConversationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_conversation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_conversations(self, + request: Optional[Union[conversational_search_service.ListConversationsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListConversationsAsyncPager: + r"""Lists all Conversations by their parent + [DataStore][google.cloud.discoveryengine.v1beta.DataStore]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_list_conversations(): + # Create a client + client = discoveryengine_v1beta.ConversationalSearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ListConversationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_conversations(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.ListConversationsRequest, dict]]): + The request object. Request for ListConversations method. + parent (:class:`str`): + Required. The data store resource name. Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.services.conversational_search_service.pagers.ListConversationsAsyncPager: + Response for ListConversations + method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = conversational_search_service.ListConversationsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_conversations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListConversationsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "ConversationalSearchServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "ConversationalSearchServiceAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/client.py new file mode 100644 index 000000000000..ec51b16e7090 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/client.py @@ -0,0 +1,1205 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.discoveryengine_v1beta.services.conversational_search_service import pagers +from google.cloud.discoveryengine_v1beta.types import conversation +from google.cloud.discoveryengine_v1beta.types import conversation as gcd_conversation +from google.cloud.discoveryengine_v1beta.types import conversational_search_service +from google.cloud.discoveryengine_v1beta.types import search_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ConversationalSearchServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ConversationalSearchServiceGrpcTransport +from .transports.grpc_asyncio import ConversationalSearchServiceGrpcAsyncIOTransport +from .transports.rest import ConversationalSearchServiceRestTransport + + +class ConversationalSearchServiceClientMeta(type): + """Metaclass for the ConversationalSearchService 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[ConversationalSearchServiceTransport]] + _transport_registry["grpc"] = ConversationalSearchServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ConversationalSearchServiceGrpcAsyncIOTransport + _transport_registry["rest"] = ConversationalSearchServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[ConversationalSearchServiceTransport]: + """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 ConversationalSearchServiceClient(metaclass=ConversationalSearchServiceClientMeta): + """Service for conversational search.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ConversationalSearchServiceClient: 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: + ConversationalSearchServiceClient: 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) -> ConversationalSearchServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ConversationalSearchServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def conversation_path(project: str,location: str,data_store: str,conversation: str,) -> str: + """Returns a fully-qualified conversation string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/conversations/{conversation}".format(project=project, location=location, data_store=data_store, conversation=conversation, ) + + @staticmethod + def parse_conversation_path(path: str) -> Dict[str,str]: + """Parses a conversation path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/conversations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def data_store_path(project: str,location: str,data_store: str,) -> str: + """Returns a fully-qualified data_store string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) + + @staticmethod + def parse_data_store_path(path: str) -> Dict[str,str]: + """Parses a data_store path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def document_path(project: str,location: str,data_store: str,branch: str,document: str,) -> str: + """Returns a fully-qualified document string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) + + @staticmethod + def parse_document_path(path: str) -> Dict[str,str]: + """Parses a document path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)/documents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def serving_config_path(project: str,location: str,data_store: str,serving_config: str,) -> str: + """Returns a fully-qualified serving_config string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/servingConfigs/{serving_config}".format(project=project, location=location, data_store=data_store, serving_config=serving_config, ) + + @staticmethod + def parse_serving_config_path(path: str) -> Dict[str,str]: + """Parses a serving_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/servingConfigs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ConversationalSearchServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the conversational search 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 (Union[str, ConversationalSearchServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ConversationalSearchServiceTransport): + # transport is a ConversationalSearchServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def converse_conversation(self, + request: Optional[Union[conversational_search_service.ConverseConversationRequest, dict]] = None, + *, + name: Optional[str] = None, + query: Optional[conversation.TextInput] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversational_search_service.ConverseConversationResponse: + r"""Converses 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 discoveryengine_v1beta + + def sample_converse_conversation(): + # Create a client + client = discoveryengine_v1beta.ConversationalSearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ConverseConversationRequest( + name="name_value", + ) + + # Make the request + response = client.converse_conversation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.ConverseConversationRequest, dict]): + The request object. Request message for + [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1beta.ConversationalSearchService.ConverseConversation] + method. + name (str): + Required. The resource name of the Conversation to get. + Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}``. + Use + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/-`` + to activate auto session mode, which automatically + creates a new conversation inside a ConverseConversation + session. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + query (google.cloud.discoveryengine_v1beta.types.TextInput): + Required. Current user input. + This corresponds to the ``query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.types.ConverseConversationResponse: + Response message for + [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1beta.ConversationalSearchService.ConverseConversation] + method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, query]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a conversational_search_service.ConverseConversationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, conversational_search_service.ConverseConversationRequest): + request = conversational_search_service.ConverseConversationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if query is not None: + request.query = query + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.converse_conversation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_conversation(self, + request: Optional[Union[conversational_search_service.CreateConversationRequest, dict]] = None, + *, + parent: Optional[str] = None, + conversation: Optional[gcd_conversation.Conversation] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_conversation.Conversation: + r"""Creates a Conversation. + + If the + [Conversation][google.cloud.discoveryengine.v1beta.Conversation] + to create already exists, an ALREADY_EXISTS error is returned. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_create_conversation(): + # Create a client + client = discoveryengine_v1beta.ConversationalSearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.CreateConversationRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_conversation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.CreateConversationRequest, dict]): + The request object. Request for CreateConversation + method. + parent (str): + Required. Full resource name of parent data store. + Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + conversation (google.cloud.discoveryengine_v1beta.types.Conversation): + Required. The conversation to create. + This corresponds to the ``conversation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.types.Conversation: + External conversation proto + definition. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, conversation]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a conversational_search_service.CreateConversationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, conversational_search_service.CreateConversationRequest): + request = conversational_search_service.CreateConversationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if conversation is not None: + request.conversation = conversation + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_conversation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_conversation(self, + request: Optional[Union[conversational_search_service.DeleteConversationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a Conversation. + + If the + [Conversation][google.cloud.discoveryengine.v1beta.Conversation] + to delete does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_delete_conversation(): + # Create a client + client = discoveryengine_v1beta.ConversationalSearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.DeleteConversationRequest( + name="name_value", + ) + + # Make the request + client.delete_conversation(request=request) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.DeleteConversationRequest, dict]): + The request object. Request for DeleteConversation + method. + name (str): + Required. The resource name of the Conversation to + delete. Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a conversational_search_service.DeleteConversationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, conversational_search_service.DeleteConversationRequest): + request = conversational_search_service.DeleteConversationRequest(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_conversation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def update_conversation(self, + request: Optional[Union[conversational_search_service.UpdateConversationRequest, dict]] = None, + *, + conversation: Optional[gcd_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, str]] = (), + ) -> gcd_conversation.Conversation: + r"""Updates a Conversation. + + [Conversation][google.cloud.discoveryengine.v1beta.Conversation] + action type cannot be changed. If the + [Conversation][google.cloud.discoveryengine.v1beta.Conversation] + to update does not exist, a NOT_FOUND error is returned. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_update_conversation(): + # Create a client + client = discoveryengine_v1beta.ConversationalSearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.UpdateConversationRequest( + ) + + # Make the request + response = client.update_conversation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.UpdateConversationRequest, dict]): + The request object. Request for UpdateConversation + method. + conversation (google.cloud.discoveryengine_v1beta.types.Conversation): + Required. The Conversation to update. + 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): + Indicates which fields in the provided + [Conversation][google.cloud.discoveryengine.v1beta.Conversation] + to update. The following are NOT supported: + + - [conversation.name][] + + If not set or empty, all supported fields are updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.types.Conversation: + External conversation proto + definition. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([conversation, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a conversational_search_service.UpdateConversationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, conversational_search_service.UpdateConversationRequest): + request = conversational_search_service.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), + )), + ) + + # 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[conversational_search_service.GetConversationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> conversation.Conversation: + r"""Gets 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 discoveryengine_v1beta + + def sample_get_conversation(): + # Create a client + client = discoveryengine_v1beta.ConversationalSearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GetConversationRequest( + name="name_value", + ) + + # Make the request + response = client.get_conversation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.GetConversationRequest, dict]): + The request object. Request for GetConversation method. + name (str): + Required. The resource name of the Conversation to get. + Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.types.Conversation: + External conversation proto + definition. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a conversational_search_service.GetConversationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, conversational_search_service.GetConversationRequest): + request = conversational_search_service.GetConversationRequest(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_conversation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_conversations(self, + request: Optional[Union[conversational_search_service.ListConversationsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListConversationsPager: + r"""Lists all Conversations by their parent + [DataStore][google.cloud.discoveryengine.v1beta.DataStore]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_list_conversations(): + # Create a client + client = discoveryengine_v1beta.ConversationalSearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ListConversationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_conversations(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.ListConversationsRequest, dict]): + The request object. Request for ListConversations method. + parent (str): + Required. The data store resource name. Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.services.conversational_search_service.pagers.ListConversationsPager: + Response for ListConversations + method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a conversational_search_service.ListConversationsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, conversational_search_service.ListConversationsRequest): + request = conversational_search_service.ListConversationsRequest(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_conversations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListConversationsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "ConversationalSearchServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "ConversationalSearchServiceClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/pagers.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/pagers.py new file mode 100644 index 000000000000..d378dd65b0f9 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.discoveryengine_v1beta.types import conversation +from google.cloud.discoveryengine_v1beta.types import conversational_search_service + + +class ListConversationsPager: + """A pager for iterating through ``list_conversations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1beta.types.ListConversationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``conversations`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListConversations`` requests and continue to iterate + through the ``conversations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1beta.types.ListConversationsResponse` + 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[..., conversational_search_service.ListConversationsResponse], + request: conversational_search_service.ListConversationsRequest, + response: conversational_search_service.ListConversationsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.discoveryengine_v1beta.types.ListConversationsRequest): + The initial request object. + response (google.cloud.discoveryengine_v1beta.types.ListConversationsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = conversational_search_service.ListConversationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[conversational_search_service.ListConversationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[conversation.Conversation]: + for page in self.pages: + yield from page.conversations + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListConversationsAsyncPager: + """A pager for iterating through ``list_conversations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1beta.types.ListConversationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``conversations`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListConversations`` requests and continue to iterate + through the ``conversations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1beta.types.ListConversationsResponse` + 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[conversational_search_service.ListConversationsResponse]], + request: conversational_search_service.ListConversationsRequest, + response: conversational_search_service.ListConversationsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.discoveryengine_v1beta.types.ListConversationsRequest): + The initial request object. + response (google.cloud.discoveryengine_v1beta.types.ListConversationsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = conversational_search_service.ListConversationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[conversational_search_service.ListConversationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[conversation.Conversation]: + async def async_generator(): + async for page in self.pages: + for response in page.conversations: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/__init__.py new file mode 100644 index 000000000000..f49b63e4b6cd --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import ConversationalSearchServiceTransport +from .grpc import ConversationalSearchServiceGrpcTransport +from .grpc_asyncio import ConversationalSearchServiceGrpcAsyncIOTransport +from .rest import ConversationalSearchServiceRestTransport +from .rest import ConversationalSearchServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ConversationalSearchServiceTransport]] +_transport_registry['grpc'] = ConversationalSearchServiceGrpcTransport +_transport_registry['grpc_asyncio'] = ConversationalSearchServiceGrpcAsyncIOTransport +_transport_registry['rest'] = ConversationalSearchServiceRestTransport + +__all__ = ( + 'ConversationalSearchServiceTransport', + 'ConversationalSearchServiceGrpcTransport', + 'ConversationalSearchServiceGrpcAsyncIOTransport', + 'ConversationalSearchServiceRestTransport', + 'ConversationalSearchServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/base.py new file mode 100644 index 000000000000..c567612a8840 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/base.py @@ -0,0 +1,241 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.discoveryengine_v1beta.types import conversation +from google.cloud.discoveryengine_v1beta.types import conversation as gcd_conversation +from google.cloud.discoveryengine_v1beta.types import conversational_search_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class ConversationalSearchServiceTransport(abc.ABC): + """Abstract transport class for ConversationalSearchService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'discoveryengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.converse_conversation: gapic_v1.method.wrap_method( + self.converse_conversation, + default_timeout=None, + client_info=client_info, + ), + self.create_conversation: gapic_v1.method.wrap_method( + self.create_conversation, + default_timeout=None, + client_info=client_info, + ), + self.delete_conversation: gapic_v1.method.wrap_method( + self.delete_conversation, + 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, + client_info=client_info, + ), + self.list_conversations: gapic_v1.method.wrap_method( + self.list_conversations, + 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 converse_conversation(self) -> Callable[ + [conversational_search_service.ConverseConversationRequest], + Union[ + conversational_search_service.ConverseConversationResponse, + Awaitable[conversational_search_service.ConverseConversationResponse] + ]]: + raise NotImplementedError() + + @property + def create_conversation(self) -> Callable[ + [conversational_search_service.CreateConversationRequest], + Union[ + gcd_conversation.Conversation, + Awaitable[gcd_conversation.Conversation] + ]]: + raise NotImplementedError() + + @property + def delete_conversation(self) -> Callable[ + [conversational_search_service.DeleteConversationRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_conversation(self) -> Callable[ + [conversational_search_service.UpdateConversationRequest], + Union[ + gcd_conversation.Conversation, + Awaitable[gcd_conversation.Conversation] + ]]: + raise NotImplementedError() + + @property + def get_conversation(self) -> Callable[ + [conversational_search_service.GetConversationRequest], + Union[ + conversation.Conversation, + Awaitable[conversation.Conversation] + ]]: + raise NotImplementedError() + + @property + def list_conversations(self) -> Callable[ + [conversational_search_service.ListConversationsRequest], + Union[ + conversational_search_service.ListConversationsResponse, + Awaitable[conversational_search_service.ListConversationsResponse] + ]]: + 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 kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'ConversationalSearchServiceTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/grpc.py new file mode 100644 index 000000000000..b311f3141b76 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/grpc.py @@ -0,0 +1,449 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.discoveryengine_v1beta.types import conversation +from google.cloud.discoveryengine_v1beta.types import conversation as gcd_conversation +from google.cloud.discoveryengine_v1beta.types import conversational_search_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import ConversationalSearchServiceTransport, DEFAULT_CLIENT_INFO + + +class ConversationalSearchServiceGrpcTransport(ConversationalSearchServiceTransport): + """gRPC backend transport for ConversationalSearchService. + + Service for conversational search. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def converse_conversation(self) -> Callable[ + [conversational_search_service.ConverseConversationRequest], + conversational_search_service.ConverseConversationResponse]: + r"""Return a callable for the converse conversation method over gRPC. + + Converses a conversation. + + Returns: + Callable[[~.ConverseConversationRequest], + ~.ConverseConversationResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'converse_conversation' not in self._stubs: + self._stubs['converse_conversation'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.ConversationalSearchService/ConverseConversation', + request_serializer=conversational_search_service.ConverseConversationRequest.serialize, + response_deserializer=conversational_search_service.ConverseConversationResponse.deserialize, + ) + return self._stubs['converse_conversation'] + + @property + def create_conversation(self) -> Callable[ + [conversational_search_service.CreateConversationRequest], + gcd_conversation.Conversation]: + r"""Return a callable for the create conversation method over gRPC. + + Creates a Conversation. + + If the + [Conversation][google.cloud.discoveryengine.v1beta.Conversation] + to create already exists, an ALREADY_EXISTS error is returned. + + Returns: + Callable[[~.CreateConversationRequest], + ~.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 'create_conversation' not in self._stubs: + self._stubs['create_conversation'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.ConversationalSearchService/CreateConversation', + request_serializer=conversational_search_service.CreateConversationRequest.serialize, + response_deserializer=gcd_conversation.Conversation.deserialize, + ) + return self._stubs['create_conversation'] + + @property + def delete_conversation(self) -> Callable[ + [conversational_search_service.DeleteConversationRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete conversation method over gRPC. + + Deletes a Conversation. + + If the + [Conversation][google.cloud.discoveryengine.v1beta.Conversation] + to delete does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.DeleteConversationRequest], + ~.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_conversation' not in self._stubs: + self._stubs['delete_conversation'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.ConversationalSearchService/DeleteConversation', + request_serializer=conversational_search_service.DeleteConversationRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_conversation'] + + @property + def update_conversation(self) -> Callable[ + [conversational_search_service.UpdateConversationRequest], + gcd_conversation.Conversation]: + r"""Return a callable for the update conversation method over gRPC. + + Updates a Conversation. + + [Conversation][google.cloud.discoveryengine.v1beta.Conversation] + action type cannot be changed. If the + [Conversation][google.cloud.discoveryengine.v1beta.Conversation] + to update does not exist, a NOT_FOUND error is returned. + + 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.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.ConversationalSearchService/UpdateConversation', + request_serializer=conversational_search_service.UpdateConversationRequest.serialize, + response_deserializer=gcd_conversation.Conversation.deserialize, + ) + return self._stubs['update_conversation'] + + @property + def get_conversation(self) -> Callable[ + [conversational_search_service.GetConversationRequest], + conversation.Conversation]: + r"""Return a callable for the get conversation method over gRPC. + + Gets a Conversation. + + Returns: + Callable[[~.GetConversationRequest], + ~.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 'get_conversation' not in self._stubs: + self._stubs['get_conversation'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.ConversationalSearchService/GetConversation', + request_serializer=conversational_search_service.GetConversationRequest.serialize, + response_deserializer=conversation.Conversation.deserialize, + ) + return self._stubs['get_conversation'] + + @property + def list_conversations(self) -> Callable[ + [conversational_search_service.ListConversationsRequest], + conversational_search_service.ListConversationsResponse]: + r"""Return a callable for the list conversations method over gRPC. + + Lists all Conversations by their parent + [DataStore][google.cloud.discoveryengine.v1beta.DataStore]. + + Returns: + Callable[[~.ListConversationsRequest], + ~.ListConversationsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversations' not in self._stubs: + self._stubs['list_conversations'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.ConversationalSearchService/ListConversations', + request_serializer=conversational_search_service.ListConversationsRequest.serialize, + response_deserializer=conversational_search_service.ListConversationsResponse.deserialize, + ) + return self._stubs['list_conversations'] + + def close(self): + self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ConversationalSearchServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..b0bcfa494853 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/grpc_asyncio.py @@ -0,0 +1,448 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.discoveryengine_v1beta.types import conversation +from google.cloud.discoveryengine_v1beta.types import conversation as gcd_conversation +from google.cloud.discoveryengine_v1beta.types import conversational_search_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import ConversationalSearchServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import ConversationalSearchServiceGrpcTransport + + +class ConversationalSearchServiceGrpcAsyncIOTransport(ConversationalSearchServiceTransport): + """gRPC AsyncIO backend transport for ConversationalSearchService. + + Service for conversational search. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def converse_conversation(self) -> Callable[ + [conversational_search_service.ConverseConversationRequest], + Awaitable[conversational_search_service.ConverseConversationResponse]]: + r"""Return a callable for the converse conversation method over gRPC. + + Converses a conversation. + + Returns: + Callable[[~.ConverseConversationRequest], + Awaitable[~.ConverseConversationResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'converse_conversation' not in self._stubs: + self._stubs['converse_conversation'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.ConversationalSearchService/ConverseConversation', + request_serializer=conversational_search_service.ConverseConversationRequest.serialize, + response_deserializer=conversational_search_service.ConverseConversationResponse.deserialize, + ) + return self._stubs['converse_conversation'] + + @property + def create_conversation(self) -> Callable[ + [conversational_search_service.CreateConversationRequest], + Awaitable[gcd_conversation.Conversation]]: + r"""Return a callable for the create conversation method over gRPC. + + Creates a Conversation. + + If the + [Conversation][google.cloud.discoveryengine.v1beta.Conversation] + to create already exists, an ALREADY_EXISTS error is returned. + + Returns: + Callable[[~.CreateConversationRequest], + 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 'create_conversation' not in self._stubs: + self._stubs['create_conversation'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.ConversationalSearchService/CreateConversation', + request_serializer=conversational_search_service.CreateConversationRequest.serialize, + response_deserializer=gcd_conversation.Conversation.deserialize, + ) + return self._stubs['create_conversation'] + + @property + def delete_conversation(self) -> Callable[ + [conversational_search_service.DeleteConversationRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete conversation method over gRPC. + + Deletes a Conversation. + + If the + [Conversation][google.cloud.discoveryengine.v1beta.Conversation] + to delete does not exist, a NOT_FOUND error is returned. + + Returns: + Callable[[~.DeleteConversationRequest], + 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_conversation' not in self._stubs: + self._stubs['delete_conversation'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.ConversationalSearchService/DeleteConversation', + request_serializer=conversational_search_service.DeleteConversationRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_conversation'] + + @property + def update_conversation(self) -> Callable[ + [conversational_search_service.UpdateConversationRequest], + Awaitable[gcd_conversation.Conversation]]: + r"""Return a callable for the update conversation method over gRPC. + + Updates a Conversation. + + [Conversation][google.cloud.discoveryengine.v1beta.Conversation] + action type cannot be changed. If the + [Conversation][google.cloud.discoveryengine.v1beta.Conversation] + to update does not exist, a NOT_FOUND error is returned. + + 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.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.ConversationalSearchService/UpdateConversation', + request_serializer=conversational_search_service.UpdateConversationRequest.serialize, + response_deserializer=gcd_conversation.Conversation.deserialize, + ) + return self._stubs['update_conversation'] + + @property + def get_conversation(self) -> Callable[ + [conversational_search_service.GetConversationRequest], + Awaitable[conversation.Conversation]]: + r"""Return a callable for the get conversation method over gRPC. + + Gets a Conversation. + + Returns: + Callable[[~.GetConversationRequest], + 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 'get_conversation' not in self._stubs: + self._stubs['get_conversation'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.ConversationalSearchService/GetConversation', + request_serializer=conversational_search_service.GetConversationRequest.serialize, + response_deserializer=conversation.Conversation.deserialize, + ) + return self._stubs['get_conversation'] + + @property + def list_conversations(self) -> Callable[ + [conversational_search_service.ListConversationsRequest], + Awaitable[conversational_search_service.ListConversationsResponse]]: + r"""Return a callable for the list conversations method over gRPC. + + Lists all Conversations by their parent + [DataStore][google.cloud.discoveryengine.v1beta.DataStore]. + + Returns: + Callable[[~.ListConversationsRequest], + Awaitable[~.ListConversationsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversations' not in self._stubs: + self._stubs['list_conversations'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.ConversationalSearchService/ListConversations', + request_serializer=conversational_search_service.ListConversationsRequest.serialize, + response_deserializer=conversational_search_service.ListConversationsResponse.deserialize, + ) + return self._stubs['list_conversations'] + + def close(self): + return self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ( + 'ConversationalSearchServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/rest.py new file mode 100644 index 000000000000..687df749d8a3 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/rest.py @@ -0,0 +1,1156 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.cloud.location import locations_pb2 # type: ignore +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.discoveryengine_v1beta.types import conversation +from google.cloud.discoveryengine_v1beta.types import conversation as gcd_conversation +from google.cloud.discoveryengine_v1beta.types import conversational_search_service +from google.protobuf import empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from .base import ConversationalSearchServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class ConversationalSearchServiceRestInterceptor: + """Interceptor for ConversationalSearchService. + + 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 ConversationalSearchServiceRestTransport. + + .. code-block:: python + class MyCustomConversationalSearchServiceInterceptor(ConversationalSearchServiceRestInterceptor): + def pre_converse_conversation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_converse_conversation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_conversation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_conversation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_conversation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_conversation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_conversation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_conversations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_conversations(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 = ConversationalSearchServiceRestTransport(interceptor=MyCustomConversationalSearchServiceInterceptor()) + client = ConversationalSearchServiceClient(transport=transport) + + + """ + def pre_converse_conversation(self, request: conversational_search_service.ConverseConversationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversational_search_service.ConverseConversationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for converse_conversation + + Override in a subclass to manipulate the request or metadata + before they are sent to the ConversationalSearchService server. + """ + return request, metadata + + def post_converse_conversation(self, response: conversational_search_service.ConverseConversationResponse) -> conversational_search_service.ConverseConversationResponse: + """Post-rpc interceptor for converse_conversation + + Override in a subclass to manipulate the response + after it is returned by the ConversationalSearchService server but before + it is returned to user code. + """ + return response + def pre_create_conversation(self, request: conversational_search_service.CreateConversationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversational_search_service.CreateConversationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_conversation + + Override in a subclass to manipulate the request or metadata + before they are sent to the ConversationalSearchService server. + """ + return request, metadata + + def post_create_conversation(self, response: gcd_conversation.Conversation) -> gcd_conversation.Conversation: + """Post-rpc interceptor for create_conversation + + Override in a subclass to manipulate the response + after it is returned by the ConversationalSearchService server but before + it is returned to user code. + """ + return response + def pre_delete_conversation(self, request: conversational_search_service.DeleteConversationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversational_search_service.DeleteConversationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_conversation + + Override in a subclass to manipulate the request or metadata + before they are sent to the ConversationalSearchService server. + """ + return request, metadata + + def pre_get_conversation(self, request: conversational_search_service.GetConversationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversational_search_service.GetConversationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_conversation + + Override in a subclass to manipulate the request or metadata + before they are sent to the ConversationalSearchService server. + """ + return request, metadata + + def post_get_conversation(self, response: conversation.Conversation) -> conversation.Conversation: + """Post-rpc interceptor for get_conversation + + Override in a subclass to manipulate the response + after it is returned by the ConversationalSearchService server but before + it is returned to user code. + """ + return response + def pre_list_conversations(self, request: conversational_search_service.ListConversationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversational_search_service.ListConversationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_conversations + + Override in a subclass to manipulate the request or metadata + before they are sent to the ConversationalSearchService server. + """ + return request, metadata + + def post_list_conversations(self, response: conversational_search_service.ListConversationsResponse) -> conversational_search_service.ListConversationsResponse: + """Post-rpc interceptor for list_conversations + + Override in a subclass to manipulate the response + after it is returned by the ConversationalSearchService server but before + it is returned to user code. + """ + return response + def pre_update_conversation(self, request: conversational_search_service.UpdateConversationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversational_search_service.UpdateConversationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_conversation + + Override in a subclass to manipulate the request or metadata + before they are sent to the ConversationalSearchService server. + """ + return request, metadata + + def post_update_conversation(self, response: gcd_conversation.Conversation) -> gcd_conversation.Conversation: + """Post-rpc interceptor for update_conversation + + Override in a subclass to manipulate the response + after it is returned by the ConversationalSearchService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the ConversationalSearchService 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 ConversationalSearchService server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the ConversationalSearchService 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 ConversationalSearchService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class ConversationalSearchServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ConversationalSearchServiceRestInterceptor + + +class ConversationalSearchServiceRestTransport(ConversationalSearchServiceTransport): + """REST backend transport for ConversationalSearchService. + + Service for conversational search. + + 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 = 'discoveryengine.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[ConversationalSearchServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or ConversationalSearchServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _ConverseConversation(ConversationalSearchServiceRestStub): + def __hash__(self): + return hash("ConverseConversation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: conversational_search_service.ConverseConversationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> conversational_search_service.ConverseConversationResponse: + r"""Call the converse conversation method over HTTP. + + Args: + request (~.conversational_search_service.ConverseConversationRequest): + The request object. Request message for + [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1beta.ConversationalSearchService.ConverseConversation] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.conversational_search_service.ConverseConversationResponse: + Response message for + [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1beta.ConversationalSearchService.ConverseConversation] + method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/conversations/*}:converse', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/conversations/*}:converse', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_converse_conversation(request, metadata) + pb_request = conversational_search_service.ConverseConversationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = conversational_search_service.ConverseConversationResponse() + pb_resp = conversational_search_service.ConverseConversationResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_converse_conversation(resp) + return resp + + class _CreateConversation(ConversationalSearchServiceRestStub): + def __hash__(self): + return hash("CreateConversation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: conversational_search_service.CreateConversationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcd_conversation.Conversation: + r"""Call the create conversation method over HTTP. + + Args: + request (~.conversational_search_service.CreateConversationRequest): + The request object. Request for CreateConversation + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcd_conversation.Conversation: + External conversation proto + definition. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{parent=projects/*/locations/*/dataStores/*}/conversations', + 'body': 'conversation', + }, +{ + 'method': 'post', + 'uri': '/v1beta/{parent=projects/*/locations/*/collections/*/dataStores/*}/conversations', + 'body': 'conversation', + }, + ] + request, metadata = self._interceptor.pre_create_conversation(request, metadata) + pb_request = conversational_search_service.CreateConversationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcd_conversation.Conversation() + pb_resp = gcd_conversation.Conversation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_conversation(resp) + return resp + + class _DeleteConversation(ConversationalSearchServiceRestStub): + def __hash__(self): + return hash("DeleteConversation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: conversational_search_service.DeleteConversationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete conversation method over HTTP. + + Args: + request (~.conversational_search_service.DeleteConversationRequest): + The request object. Request for DeleteConversation + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/conversations/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/conversations/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_conversation(request, metadata) + pb_request = conversational_search_service.DeleteConversationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _GetConversation(ConversationalSearchServiceRestStub): + def __hash__(self): + return hash("GetConversation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: conversational_search_service.GetConversationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> conversation.Conversation: + r"""Call the get conversation method over HTTP. + + Args: + request (~.conversational_search_service.GetConversationRequest): + The request object. Request for GetConversation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.conversation.Conversation: + External conversation proto + definition. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/conversations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/conversations/*}', + }, + ] + request, metadata = self._interceptor.pre_get_conversation(request, metadata) + pb_request = conversational_search_service.GetConversationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = conversation.Conversation() + pb_resp = conversation.Conversation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_conversation(resp) + return resp + + class _ListConversations(ConversationalSearchServiceRestStub): + def __hash__(self): + return hash("ListConversations") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: conversational_search_service.ListConversationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> conversational_search_service.ListConversationsResponse: + r"""Call the list conversations method over HTTP. + + Args: + request (~.conversational_search_service.ListConversationsRequest): + The request object. Request for ListConversations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.conversational_search_service.ListConversationsResponse: + Response for ListConversations + method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=projects/*/locations/*/dataStores/*}/conversations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{parent=projects/*/locations/*/collections/*/dataStores/*}/conversations', + }, + ] + request, metadata = self._interceptor.pre_list_conversations(request, metadata) + pb_request = conversational_search_service.ListConversationsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = conversational_search_service.ListConversationsResponse() + pb_resp = conversational_search_service.ListConversationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_conversations(resp) + return resp + + class _UpdateConversation(ConversationalSearchServiceRestStub): + def __hash__(self): + return hash("UpdateConversation") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: conversational_search_service.UpdateConversationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcd_conversation.Conversation: + r"""Call the update conversation method over HTTP. + + Args: + request (~.conversational_search_service.UpdateConversationRequest): + The request object. Request for UpdateConversation + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcd_conversation.Conversation: + External conversation proto + definition. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1beta/{conversation.name=projects/*/locations/*/dataStores/*/conversations/*}', + 'body': 'conversation', + }, +{ + 'method': 'patch', + 'uri': '/v1beta/{conversation.name=projects/*/locations/*/collections/*/dataStores/*/conversations/*}', + 'body': 'conversation', + }, + ] + request, metadata = self._interceptor.pre_update_conversation(request, metadata) + pb_request = conversational_search_service.UpdateConversationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcd_conversation.Conversation() + pb_resp = gcd_conversation.Conversation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_conversation(resp) + return resp + + @property + def converse_conversation(self) -> Callable[ + [conversational_search_service.ConverseConversationRequest], + conversational_search_service.ConverseConversationResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ConverseConversation(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_conversation(self) -> Callable[ + [conversational_search_service.CreateConversationRequest], + gcd_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._CreateConversation(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_conversation(self) -> Callable[ + [conversational_search_service.DeleteConversationRequest], + 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._DeleteConversation(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_conversation(self) -> Callable[ + [conversational_search_service.GetConversationRequest], + 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._GetConversation(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_conversations(self) -> Callable[ + [conversational_search_service.ListConversationsRequest], + conversational_search_service.ListConversationsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListConversations(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_conversation(self) -> Callable[ + [conversational_search_service.UpdateConversationRequest], + gcd_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_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(ConversationalSearchServiceRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(ConversationalSearchServiceRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'ConversationalSearchServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/__init__.py new file mode 100644 index 000000000000..e4f0b808a498 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import DocumentServiceClient +from .async_client import DocumentServiceAsyncClient + +__all__ = ( + 'DocumentServiceClient', + 'DocumentServiceAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/async_client.py new file mode 100644 index 000000000000..11462d9f2f62 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/async_client.py @@ -0,0 +1,1112 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.discoveryengine_v1beta.services.document_service import pagers +from google.cloud.discoveryengine_v1beta.types import document +from google.cloud.discoveryengine_v1beta.types import document as gcd_document +from google.cloud.discoveryengine_v1beta.types import document_service +from google.cloud.discoveryengine_v1beta.types import import_config +from google.cloud.discoveryengine_v1beta.types import purge_config +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from .transports.base import DocumentServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import DocumentServiceGrpcAsyncIOTransport +from .client import DocumentServiceClient + + +class DocumentServiceAsyncClient: + """Service for ingesting + [Document][google.cloud.discoveryengine.v1beta.Document] information + of the customer's website. + """ + + _client: DocumentServiceClient + + DEFAULT_ENDPOINT = DocumentServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = DocumentServiceClient.DEFAULT_MTLS_ENDPOINT + + branch_path = staticmethod(DocumentServiceClient.branch_path) + parse_branch_path = staticmethod(DocumentServiceClient.parse_branch_path) + document_path = staticmethod(DocumentServiceClient.document_path) + parse_document_path = staticmethod(DocumentServiceClient.parse_document_path) + common_billing_account_path = staticmethod(DocumentServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(DocumentServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(DocumentServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(DocumentServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(DocumentServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(DocumentServiceClient.parse_common_organization_path) + common_project_path = staticmethod(DocumentServiceClient.common_project_path) + parse_common_project_path = staticmethod(DocumentServiceClient.parse_common_project_path) + common_location_path = staticmethod(DocumentServiceClient.common_location_path) + parse_common_location_path = staticmethod(DocumentServiceClient.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: + DocumentServiceAsyncClient: The constructed client. + """ + return DocumentServiceClient.from_service_account_info.__func__(DocumentServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DocumentServiceAsyncClient: The constructed client. + """ + return DocumentServiceClient.from_service_account_file.__func__(DocumentServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return DocumentServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> DocumentServiceTransport: + """Returns the transport used by the client instance. + + Returns: + DocumentServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(DocumentServiceClient).get_transport_class, type(DocumentServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, DocumentServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the document 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 (Union[str, ~.DocumentServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = DocumentServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def get_document(self, + request: Optional[Union[document_service.GetDocumentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> document.Document: + r"""Gets a [Document][google.cloud.discoveryengine.v1beta.Document]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_get_document(): + # Create a client + client = discoveryengine_v1beta.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GetDocumentRequest( + name="name_value", + ) + + # Make the request + response = await client.get_document(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.GetDocumentRequest, dict]]): + The request object. Request message for + [DocumentService.GetDocument][google.cloud.discoveryengine.v1beta.DocumentService.GetDocument] + method. + name (:class:`str`): + Required. Full resource name of + [Document][google.cloud.discoveryengine.v1beta.Document], + such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. + + If the caller does not have permission to access the + [Document][google.cloud.discoveryengine.v1beta.Document], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the requested + [Document][google.cloud.discoveryengine.v1beta.Document] + does not exist, a ``NOT_FOUND`` error is returned. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.types.Document: + Document captures all raw metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = document_service.GetDocumentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_document, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_documents(self, + request: Optional[Union[document_service.ListDocumentsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDocumentsAsyncPager: + r"""Gets a list of + [Document][google.cloud.discoveryengine.v1beta.Document]s. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_list_documents(): + # Create a client + client = discoveryengine_v1beta.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ListDocumentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_documents(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.ListDocumentsRequest, dict]]): + The request object. Request message for + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1beta.DocumentService.ListDocuments] + method. + parent (:class:`str`): + Required. The parent branch resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. + Use ``default_branch`` as the branch ID, to list + documents under the default branch. + + If the caller does not have permission to list + [Document][google.cloud.discoveryengine.v1beta.Document]s + under this branch, regardless of whether or not this + branch exists, a ``PERMISSION_DENIED`` error is + returned. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.services.document_service.pagers.ListDocumentsAsyncPager: + Response message for + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1beta.DocumentService.ListDocuments] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = document_service.ListDocumentsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_documents, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListDocumentsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_document(self, + request: Optional[Union[document_service.CreateDocumentRequest, dict]] = None, + *, + parent: Optional[str] = None, + document: Optional[gcd_document.Document] = None, + document_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_document.Document: + r"""Creates a + [Document][google.cloud.discoveryengine.v1beta.Document]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_create_document(): + # Create a client + client = discoveryengine_v1beta.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.CreateDocumentRequest( + parent="parent_value", + document_id="document_id_value", + ) + + # Make the request + response = await client.create_document(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.CreateDocumentRequest, dict]]): + The request object. Request message for + [DocumentService.CreateDocument][google.cloud.discoveryengine.v1beta.DocumentService.CreateDocument] + method. + parent (:class:`str`): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + document (:class:`google.cloud.discoveryengine_v1beta.types.Document`): + Required. The + [Document][google.cloud.discoveryengine.v1beta.Document] + to create. + + This corresponds to the ``document`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + document_id (:class:`str`): + Required. The ID to use for the + [Document][google.cloud.discoveryengine.v1beta.Document], + which will become the final component of the + [Document.name][google.cloud.discoveryengine.v1beta.Document.name]. + + If the caller does not have permission to create the + [Document][google.cloud.discoveryengine.v1beta.Document], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + This field must be unique among all + [Document][google.cloud.discoveryengine.v1beta.Document]s + with the same + [parent][google.cloud.discoveryengine.v1beta.CreateDocumentRequest.parent]. + Otherwise, an ``ALREADY_EXISTS`` error is returned. + + This field must conform to + `RFC-1034 `__ + standard with a length limit of 63 characters. + Otherwise, an ``INVALID_ARGUMENT`` error is returned. + + This corresponds to the ``document_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.types.Document: + Document captures all raw metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, document, document_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = document_service.CreateDocumentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if document is not None: + request.document = document + if document_id is not None: + request.document_id = document_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_document, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_document(self, + request: Optional[Union[document_service.UpdateDocumentRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> document.Document: + r"""Updates a + [Document][google.cloud.discoveryengine.v1beta.Document]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_update_document(): + # Create a client + client = discoveryengine_v1beta.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.UpdateDocumentRequest( + ) + + # Make the request + response = await client.update_document(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.UpdateDocumentRequest, dict]]): + The request object. Request message for + [DocumentService.UpdateDocument][google.cloud.discoveryengine.v1beta.DocumentService.UpdateDocument] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.types.Document: + Document captures all raw metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + request = document_service.UpdateDocumentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_document, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("document.name", request.document.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_document(self, + request: Optional[Union[document_service.DeleteDocumentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a + [Document][google.cloud.discoveryengine.v1beta.Document]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_delete_document(): + # Create a client + client = discoveryengine_v1beta.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.DeleteDocumentRequest( + name="name_value", + ) + + # Make the request + await client.delete_document(request=request) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.DeleteDocumentRequest, dict]]): + The request object. Request message for + [DocumentService.DeleteDocument][google.cloud.discoveryengine.v1beta.DocumentService.DeleteDocument] + method. + name (:class:`str`): + Required. Full resource name of + [Document][google.cloud.discoveryengine.v1beta.Document], + such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. + + If the caller does not have permission to delete the + [Document][google.cloud.discoveryengine.v1beta.Document], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [Document][google.cloud.discoveryengine.v1beta.Document] + to delete does not exist, a ``NOT_FOUND`` error is + returned. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = document_service.DeleteDocumentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_document, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def import_documents(self, + request: Optional[Union[import_config.ImportDocumentsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of multiple + [Document][google.cloud.discoveryengine.v1beta.Document]s. + Request processing may be synchronous. Non-existing items will + be created. + + Note: It is possible for a subset of the + [Document][google.cloud.discoveryengine.v1beta.Document]s to be + successfully updated. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_import_documents(): + # Create a client + client = discoveryengine_v1beta.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ImportDocumentsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.import_documents(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.ImportDocumentsRequest, dict]]): + The request object. Request message for Import methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1beta.types.ImportDocumentsResponse` Response of the + [ImportDocumentsRequest][google.cloud.discoveryengine.v1beta.ImportDocumentsRequest]. + If the long running operation is done, then this + message is returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + request = import_config.ImportDocumentsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_documents, + default_retry=retries.Retry( +initial=1.0,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_config.ImportDocumentsResponse, + metadata_type=import_config.ImportDocumentsMetadata, + ) + + # Done; return the response. + return response + + async def purge_documents(self, + request: Optional[Union[purge_config.PurgeDocumentsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Permanently deletes all selected + [Document][google.cloud.discoveryengine.v1beta.Document]s in a + branch. + + This process is asynchronous. Depending on the number of + [Document][google.cloud.discoveryengine.v1beta.Document]s to be + deleted, this operation can take hours to complete. Before the + delete operation completes, some + [Document][google.cloud.discoveryengine.v1beta.Document]s might + still be returned by + [DocumentService.GetDocument][google.cloud.discoveryengine.v1beta.DocumentService.GetDocument] + or + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1beta.DocumentService.ListDocuments]. + + To get a list of the + [Document][google.cloud.discoveryengine.v1beta.Document]s to be + deleted, set + [PurgeDocumentsRequest.force][google.cloud.discoveryengine.v1beta.PurgeDocumentsRequest.force] + to false. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_purge_documents(): + # Create a client + client = discoveryengine_v1beta.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.PurgeDocumentsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_documents(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.PurgeDocumentsRequest, dict]]): + The request object. Request message for + [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1beta.DocumentService.PurgeDocuments] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1beta.types.PurgeDocumentsResponse` Response message for + [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1beta.DocumentService.PurgeDocuments] + method. If the long running operation is successfully + done, then this message is returned by the + google.longrunning.Operations.response field. + + """ + # Create or coerce a protobuf request object. + request = purge_config.PurgeDocumentsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.purge_documents, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + purge_config.PurgeDocumentsResponse, + metadata_type=purge_config.PurgeDocumentsMetadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "DocumentServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "DocumentServiceAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/client.py new file mode 100644 index 000000000000..828d1d7ba421 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/client.py @@ -0,0 +1,1325 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.discoveryengine_v1beta.services.document_service import pagers +from google.cloud.discoveryengine_v1beta.types import document +from google.cloud.discoveryengine_v1beta.types import document as gcd_document +from google.cloud.discoveryengine_v1beta.types import document_service +from google.cloud.discoveryengine_v1beta.types import import_config +from google.cloud.discoveryengine_v1beta.types import purge_config +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from .transports.base import DocumentServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import DocumentServiceGrpcTransport +from .transports.grpc_asyncio import DocumentServiceGrpcAsyncIOTransport +from .transports.rest import DocumentServiceRestTransport + + +class DocumentServiceClientMeta(type): + """Metaclass for the DocumentService 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[DocumentServiceTransport]] + _transport_registry["grpc"] = DocumentServiceGrpcTransport + _transport_registry["grpc_asyncio"] = DocumentServiceGrpcAsyncIOTransport + _transport_registry["rest"] = DocumentServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[DocumentServiceTransport]: + """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 DocumentServiceClient(metaclass=DocumentServiceClientMeta): + """Service for ingesting + [Document][google.cloud.discoveryengine.v1beta.Document] information + of the customer's website. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + DocumentServiceClient: 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: + DocumentServiceClient: 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) -> DocumentServiceTransport: + """Returns the transport used by the client instance. + + Returns: + DocumentServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def branch_path(project: str,location: str,data_store: str,branch: str,) -> str: + """Returns a fully-qualified branch string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}".format(project=project, location=location, data_store=data_store, branch=branch, ) + + @staticmethod + def parse_branch_path(path: str) -> Dict[str,str]: + """Parses a branch path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def document_path(project: str,location: str,data_store: str,branch: str,document: str,) -> str: + """Returns a fully-qualified document string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) + + @staticmethod + def parse_document_path(path: str) -> Dict[str,str]: + """Parses a document path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)/documents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, DocumentServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the document 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 (Union[str, DocumentServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, DocumentServiceTransport): + # transport is a DocumentServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def get_document(self, + request: Optional[Union[document_service.GetDocumentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> document.Document: + r"""Gets a [Document][google.cloud.discoveryengine.v1beta.Document]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_get_document(): + # Create a client + client = discoveryengine_v1beta.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GetDocumentRequest( + name="name_value", + ) + + # Make the request + response = client.get_document(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.GetDocumentRequest, dict]): + The request object. Request message for + [DocumentService.GetDocument][google.cloud.discoveryengine.v1beta.DocumentService.GetDocument] + method. + name (str): + Required. Full resource name of + [Document][google.cloud.discoveryengine.v1beta.Document], + such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. + + If the caller does not have permission to access the + [Document][google.cloud.discoveryengine.v1beta.Document], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the requested + [Document][google.cloud.discoveryengine.v1beta.Document] + does not exist, a ``NOT_FOUND`` error is returned. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.types.Document: + Document captures all raw metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a document_service.GetDocumentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, document_service.GetDocumentRequest): + request = document_service.GetDocumentRequest(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_document] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_documents(self, + request: Optional[Union[document_service.ListDocumentsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDocumentsPager: + r"""Gets a list of + [Document][google.cloud.discoveryengine.v1beta.Document]s. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_list_documents(): + # Create a client + client = discoveryengine_v1beta.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ListDocumentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_documents(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.ListDocumentsRequest, dict]): + The request object. Request message for + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1beta.DocumentService.ListDocuments] + method. + parent (str): + Required. The parent branch resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. + Use ``default_branch`` as the branch ID, to list + documents under the default branch. + + If the caller does not have permission to list + [Document][google.cloud.discoveryengine.v1beta.Document]s + under this branch, regardless of whether or not this + branch exists, a ``PERMISSION_DENIED`` error is + returned. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.services.document_service.pagers.ListDocumentsPager: + Response message for + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1beta.DocumentService.ListDocuments] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a document_service.ListDocumentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, document_service.ListDocumentsRequest): + request = document_service.ListDocumentsRequest(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_documents] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListDocumentsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_document(self, + request: Optional[Union[document_service.CreateDocumentRequest, dict]] = None, + *, + parent: Optional[str] = None, + document: Optional[gcd_document.Document] = None, + document_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_document.Document: + r"""Creates a + [Document][google.cloud.discoveryengine.v1beta.Document]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_create_document(): + # Create a client + client = discoveryengine_v1beta.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.CreateDocumentRequest( + parent="parent_value", + document_id="document_id_value", + ) + + # Make the request + response = client.create_document(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.CreateDocumentRequest, dict]): + The request object. Request message for + [DocumentService.CreateDocument][google.cloud.discoveryengine.v1beta.DocumentService.CreateDocument] + method. + parent (str): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + document (google.cloud.discoveryengine_v1beta.types.Document): + Required. The + [Document][google.cloud.discoveryengine.v1beta.Document] + to create. + + This corresponds to the ``document`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + document_id (str): + Required. The ID to use for the + [Document][google.cloud.discoveryengine.v1beta.Document], + which will become the final component of the + [Document.name][google.cloud.discoveryengine.v1beta.Document.name]. + + If the caller does not have permission to create the + [Document][google.cloud.discoveryengine.v1beta.Document], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + This field must be unique among all + [Document][google.cloud.discoveryengine.v1beta.Document]s + with the same + [parent][google.cloud.discoveryengine.v1beta.CreateDocumentRequest.parent]. + Otherwise, an ``ALREADY_EXISTS`` error is returned. + + This field must conform to + `RFC-1034 `__ + standard with a length limit of 63 characters. + Otherwise, an ``INVALID_ARGUMENT`` error is returned. + + This corresponds to the ``document_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.types.Document: + Document captures all raw metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, document, document_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a document_service.CreateDocumentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, document_service.CreateDocumentRequest): + request = document_service.CreateDocumentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if document is not None: + request.document = document + if document_id is not None: + request.document_id = document_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_document] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_document(self, + request: Optional[Union[document_service.UpdateDocumentRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> document.Document: + r"""Updates a + [Document][google.cloud.discoveryengine.v1beta.Document]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_update_document(): + # Create a client + client = discoveryengine_v1beta.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.UpdateDocumentRequest( + ) + + # Make the request + response = client.update_document(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.UpdateDocumentRequest, dict]): + The request object. Request message for + [DocumentService.UpdateDocument][google.cloud.discoveryengine.v1beta.DocumentService.UpdateDocument] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.types.Document: + Document captures all raw metadata + information of items to be recommended + or searched. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a document_service.UpdateDocumentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, document_service.UpdateDocumentRequest): + request = document_service.UpdateDocumentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_document] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("document.name", request.document.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_document(self, + request: Optional[Union[document_service.DeleteDocumentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a + [Document][google.cloud.discoveryengine.v1beta.Document]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_delete_document(): + # Create a client + client = discoveryengine_v1beta.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.DeleteDocumentRequest( + name="name_value", + ) + + # Make the request + client.delete_document(request=request) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.DeleteDocumentRequest, dict]): + The request object. Request message for + [DocumentService.DeleteDocument][google.cloud.discoveryengine.v1beta.DocumentService.DeleteDocument] + method. + name (str): + Required. Full resource name of + [Document][google.cloud.discoveryengine.v1beta.Document], + such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. + + If the caller does not have permission to delete the + [Document][google.cloud.discoveryengine.v1beta.Document], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [Document][google.cloud.discoveryengine.v1beta.Document] + to delete does not exist, a ``NOT_FOUND`` error is + returned. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a document_service.DeleteDocumentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, document_service.DeleteDocumentRequest): + request = document_service.DeleteDocumentRequest(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_document] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def import_documents(self, + request: Optional[Union[import_config.ImportDocumentsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Bulk import of multiple + [Document][google.cloud.discoveryengine.v1beta.Document]s. + Request processing may be synchronous. Non-existing items will + be created. + + Note: It is possible for a subset of the + [Document][google.cloud.discoveryengine.v1beta.Document]s to be + successfully updated. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_import_documents(): + # Create a client + client = discoveryengine_v1beta.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ImportDocumentsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.import_documents(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.ImportDocumentsRequest, dict]): + The request object. Request message for Import methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1beta.types.ImportDocumentsResponse` Response of the + [ImportDocumentsRequest][google.cloud.discoveryengine.v1beta.ImportDocumentsRequest]. + If the long running operation is done, then this + message is returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a import_config.ImportDocumentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, import_config.ImportDocumentsRequest): + request = import_config.ImportDocumentsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_documents] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_config.ImportDocumentsResponse, + metadata_type=import_config.ImportDocumentsMetadata, + ) + + # Done; return the response. + return response + + def purge_documents(self, + request: Optional[Union[purge_config.PurgeDocumentsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Permanently deletes all selected + [Document][google.cloud.discoveryengine.v1beta.Document]s in a + branch. + + This process is asynchronous. Depending on the number of + [Document][google.cloud.discoveryengine.v1beta.Document]s to be + deleted, this operation can take hours to complete. Before the + delete operation completes, some + [Document][google.cloud.discoveryengine.v1beta.Document]s might + still be returned by + [DocumentService.GetDocument][google.cloud.discoveryengine.v1beta.DocumentService.GetDocument] + or + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1beta.DocumentService.ListDocuments]. + + To get a list of the + [Document][google.cloud.discoveryengine.v1beta.Document]s to be + deleted, set + [PurgeDocumentsRequest.force][google.cloud.discoveryengine.v1beta.PurgeDocumentsRequest.force] + to false. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_purge_documents(): + # Create a client + client = discoveryengine_v1beta.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.PurgeDocumentsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_documents(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.PurgeDocumentsRequest, dict]): + The request object. Request message for + [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1beta.DocumentService.PurgeDocuments] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1beta.types.PurgeDocumentsResponse` Response message for + [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1beta.DocumentService.PurgeDocuments] + method. If the long running operation is successfully + done, then this message is returned by the + google.longrunning.Operations.response field. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a purge_config.PurgeDocumentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, purge_config.PurgeDocumentsRequest): + request = purge_config.PurgeDocumentsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.purge_documents] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + purge_config.PurgeDocumentsResponse, + metadata_type=purge_config.PurgeDocumentsMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "DocumentServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "DocumentServiceClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/pagers.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/pagers.py new file mode 100644 index 000000000000..f6dcb0a142ce --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.discoveryengine_v1beta.types import document +from google.cloud.discoveryengine_v1beta.types import document_service + + +class ListDocumentsPager: + """A pager for iterating through ``list_documents`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1beta.types.ListDocumentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``documents`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDocuments`` requests and continue to iterate + through the ``documents`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1beta.types.ListDocumentsResponse` + 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[..., document_service.ListDocumentsResponse], + request: document_service.ListDocumentsRequest, + response: document_service.ListDocumentsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.discoveryengine_v1beta.types.ListDocumentsRequest): + The initial request object. + response (google.cloud.discoveryengine_v1beta.types.ListDocumentsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = document_service.ListDocumentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[document_service.ListDocumentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[document.Document]: + for page in self.pages: + yield from page.documents + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDocumentsAsyncPager: + """A pager for iterating through ``list_documents`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1beta.types.ListDocumentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``documents`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDocuments`` requests and continue to iterate + through the ``documents`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1beta.types.ListDocumentsResponse` + 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[document_service.ListDocumentsResponse]], + request: document_service.ListDocumentsRequest, + response: document_service.ListDocumentsResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.discoveryengine_v1beta.types.ListDocumentsRequest): + The initial request object. + response (google.cloud.discoveryengine_v1beta.types.ListDocumentsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = document_service.ListDocumentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[document_service.ListDocumentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[document.Document]: + async def async_generator(): + async for page in self.pages: + for response in page.documents: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/__init__.py new file mode 100644 index 000000000000..fb08db02f32c --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import DocumentServiceTransport +from .grpc import DocumentServiceGrpcTransport +from .grpc_asyncio import DocumentServiceGrpcAsyncIOTransport +from .rest import DocumentServiceRestTransport +from .rest import DocumentServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[DocumentServiceTransport]] +_transport_registry['grpc'] = DocumentServiceGrpcTransport +_transport_registry['grpc_asyncio'] = DocumentServiceGrpcAsyncIOTransport +_transport_registry['rest'] = DocumentServiceRestTransport + +__all__ = ( + 'DocumentServiceTransport', + 'DocumentServiceGrpcTransport', + 'DocumentServiceGrpcAsyncIOTransport', + 'DocumentServiceRestTransport', + 'DocumentServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/base.py new file mode 100644 index 000000000000..d78ce78eb3cd --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/base.py @@ -0,0 +1,269 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.discoveryengine_v1beta.types import document +from google.cloud.discoveryengine_v1beta.types import document as gcd_document +from google.cloud.discoveryengine_v1beta.types import document_service +from google.cloud.discoveryengine_v1beta.types import import_config +from google.cloud.discoveryengine_v1beta.types import purge_config +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class DocumentServiceTransport(abc.ABC): + """Abstract transport class for DocumentService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'discoveryengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_document: gapic_v1.method.wrap_method( + self.get_document, + default_timeout=None, + client_info=client_info, + ), + self.list_documents: gapic_v1.method.wrap_method( + self.list_documents, + default_timeout=None, + client_info=client_info, + ), + self.create_document: gapic_v1.method.wrap_method( + self.create_document, + default_timeout=None, + client_info=client_info, + ), + self.update_document: gapic_v1.method.wrap_method( + self.update_document, + default_timeout=None, + client_info=client_info, + ), + self.delete_document: gapic_v1.method.wrap_method( + self.delete_document, + default_timeout=None, + client_info=client_info, + ), + self.import_documents: gapic_v1.method.wrap_method( + self.import_documents, + default_retry=retries.Retry( +initial=1.0,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.0, + client_info=client_info, + ), + self.purge_documents: gapic_v1.method.wrap_method( + self.purge_documents, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def get_document(self) -> Callable[ + [document_service.GetDocumentRequest], + Union[ + document.Document, + Awaitable[document.Document] + ]]: + raise NotImplementedError() + + @property + def list_documents(self) -> Callable[ + [document_service.ListDocumentsRequest], + Union[ + document_service.ListDocumentsResponse, + Awaitable[document_service.ListDocumentsResponse] + ]]: + raise NotImplementedError() + + @property + def create_document(self) -> Callable[ + [document_service.CreateDocumentRequest], + Union[ + gcd_document.Document, + Awaitable[gcd_document.Document] + ]]: + raise NotImplementedError() + + @property + def update_document(self) -> Callable[ + [document_service.UpdateDocumentRequest], + Union[ + document.Document, + Awaitable[document.Document] + ]]: + raise NotImplementedError() + + @property + def delete_document(self) -> Callable[ + [document_service.DeleteDocumentRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def import_documents(self) -> Callable[ + [import_config.ImportDocumentsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def purge_documents(self) -> Callable[ + [purge_config.PurgeDocumentsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'DocumentServiceTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/grpc.py new file mode 100644 index 000000000000..9328ff2b0bd4 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/grpc.py @@ -0,0 +1,512 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.discoveryengine_v1beta.types import document +from google.cloud.discoveryengine_v1beta.types import document as gcd_document +from google.cloud.discoveryengine_v1beta.types import document_service +from google.cloud.discoveryengine_v1beta.types import import_config +from google.cloud.discoveryengine_v1beta.types import purge_config +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import DocumentServiceTransport, DEFAULT_CLIENT_INFO + + +class DocumentServiceGrpcTransport(DocumentServiceTransport): + """gRPC backend transport for DocumentService. + + Service for ingesting + [Document][google.cloud.discoveryengine.v1beta.Document] information + of the customer's website. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def get_document(self) -> Callable[ + [document_service.GetDocumentRequest], + document.Document]: + r"""Return a callable for the get document method over gRPC. + + Gets a [Document][google.cloud.discoveryengine.v1beta.Document]. + + Returns: + Callable[[~.GetDocumentRequest], + ~.Document]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_document' not in self._stubs: + self._stubs['get_document'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.DocumentService/GetDocument', + request_serializer=document_service.GetDocumentRequest.serialize, + response_deserializer=document.Document.deserialize, + ) + return self._stubs['get_document'] + + @property + def list_documents(self) -> Callable[ + [document_service.ListDocumentsRequest], + document_service.ListDocumentsResponse]: + r"""Return a callable for the list documents method over gRPC. + + Gets a list of + [Document][google.cloud.discoveryengine.v1beta.Document]s. + + Returns: + Callable[[~.ListDocumentsRequest], + ~.ListDocumentsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_documents' not in self._stubs: + self._stubs['list_documents'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.DocumentService/ListDocuments', + request_serializer=document_service.ListDocumentsRequest.serialize, + response_deserializer=document_service.ListDocumentsResponse.deserialize, + ) + return self._stubs['list_documents'] + + @property + def create_document(self) -> Callable[ + [document_service.CreateDocumentRequest], + gcd_document.Document]: + r"""Return a callable for the create document method over gRPC. + + Creates a + [Document][google.cloud.discoveryengine.v1beta.Document]. + + Returns: + Callable[[~.CreateDocumentRequest], + ~.Document]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_document' not in self._stubs: + self._stubs['create_document'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.DocumentService/CreateDocument', + request_serializer=document_service.CreateDocumentRequest.serialize, + response_deserializer=gcd_document.Document.deserialize, + ) + return self._stubs['create_document'] + + @property + def update_document(self) -> Callable[ + [document_service.UpdateDocumentRequest], + document.Document]: + r"""Return a callable for the update document method over gRPC. + + Updates a + [Document][google.cloud.discoveryengine.v1beta.Document]. + + Returns: + Callable[[~.UpdateDocumentRequest], + ~.Document]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_document' not in self._stubs: + self._stubs['update_document'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.DocumentService/UpdateDocument', + request_serializer=document_service.UpdateDocumentRequest.serialize, + response_deserializer=document.Document.deserialize, + ) + return self._stubs['update_document'] + + @property + def delete_document(self) -> Callable[ + [document_service.DeleteDocumentRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete document method over gRPC. + + Deletes a + [Document][google.cloud.discoveryengine.v1beta.Document]. + + Returns: + Callable[[~.DeleteDocumentRequest], + ~.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_document' not in self._stubs: + self._stubs['delete_document'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.DocumentService/DeleteDocument', + request_serializer=document_service.DeleteDocumentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_document'] + + @property + def import_documents(self) -> Callable[ + [import_config.ImportDocumentsRequest], + operations_pb2.Operation]: + r"""Return a callable for the import documents method over gRPC. + + Bulk import of multiple + [Document][google.cloud.discoveryengine.v1beta.Document]s. + Request processing may be synchronous. Non-existing items will + be created. + + Note: It is possible for a subset of the + [Document][google.cloud.discoveryengine.v1beta.Document]s to be + successfully updated. + + Returns: + Callable[[~.ImportDocumentsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_documents' not in self._stubs: + self._stubs['import_documents'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.DocumentService/ImportDocuments', + request_serializer=import_config.ImportDocumentsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_documents'] + + @property + def purge_documents(self) -> Callable[ + [purge_config.PurgeDocumentsRequest], + operations_pb2.Operation]: + r"""Return a callable for the purge documents method over gRPC. + + Permanently deletes all selected + [Document][google.cloud.discoveryengine.v1beta.Document]s in a + branch. + + This process is asynchronous. Depending on the number of + [Document][google.cloud.discoveryengine.v1beta.Document]s to be + deleted, this operation can take hours to complete. Before the + delete operation completes, some + [Document][google.cloud.discoveryengine.v1beta.Document]s might + still be returned by + [DocumentService.GetDocument][google.cloud.discoveryengine.v1beta.DocumentService.GetDocument] + or + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1beta.DocumentService.ListDocuments]. + + To get a list of the + [Document][google.cloud.discoveryengine.v1beta.Document]s to be + deleted, set + [PurgeDocumentsRequest.force][google.cloud.discoveryengine.v1beta.PurgeDocumentsRequest.force] + to false. + + Returns: + Callable[[~.PurgeDocumentsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'purge_documents' not in self._stubs: + self._stubs['purge_documents'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.DocumentService/PurgeDocuments', + request_serializer=purge_config.PurgeDocumentsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['purge_documents'] + + def close(self): + self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'DocumentServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..3d575402cda1 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/grpc_asyncio.py @@ -0,0 +1,511 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.discoveryengine_v1beta.types import document +from google.cloud.discoveryengine_v1beta.types import document as gcd_document +from google.cloud.discoveryengine_v1beta.types import document_service +from google.cloud.discoveryengine_v1beta.types import import_config +from google.cloud.discoveryengine_v1beta.types import purge_config +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import DocumentServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import DocumentServiceGrpcTransport + + +class DocumentServiceGrpcAsyncIOTransport(DocumentServiceTransport): + """gRPC AsyncIO backend transport for DocumentService. + + Service for ingesting + [Document][google.cloud.discoveryengine.v1beta.Document] information + of the customer's website. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def get_document(self) -> Callable[ + [document_service.GetDocumentRequest], + Awaitable[document.Document]]: + r"""Return a callable for the get document method over gRPC. + + Gets a [Document][google.cloud.discoveryengine.v1beta.Document]. + + Returns: + Callable[[~.GetDocumentRequest], + Awaitable[~.Document]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_document' not in self._stubs: + self._stubs['get_document'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.DocumentService/GetDocument', + request_serializer=document_service.GetDocumentRequest.serialize, + response_deserializer=document.Document.deserialize, + ) + return self._stubs['get_document'] + + @property + def list_documents(self) -> Callable[ + [document_service.ListDocumentsRequest], + Awaitable[document_service.ListDocumentsResponse]]: + r"""Return a callable for the list documents method over gRPC. + + Gets a list of + [Document][google.cloud.discoveryengine.v1beta.Document]s. + + Returns: + Callable[[~.ListDocumentsRequest], + Awaitable[~.ListDocumentsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_documents' not in self._stubs: + self._stubs['list_documents'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.DocumentService/ListDocuments', + request_serializer=document_service.ListDocumentsRequest.serialize, + response_deserializer=document_service.ListDocumentsResponse.deserialize, + ) + return self._stubs['list_documents'] + + @property + def create_document(self) -> Callable[ + [document_service.CreateDocumentRequest], + Awaitable[gcd_document.Document]]: + r"""Return a callable for the create document method over gRPC. + + Creates a + [Document][google.cloud.discoveryengine.v1beta.Document]. + + Returns: + Callable[[~.CreateDocumentRequest], + Awaitable[~.Document]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_document' not in self._stubs: + self._stubs['create_document'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.DocumentService/CreateDocument', + request_serializer=document_service.CreateDocumentRequest.serialize, + response_deserializer=gcd_document.Document.deserialize, + ) + return self._stubs['create_document'] + + @property + def update_document(self) -> Callable[ + [document_service.UpdateDocumentRequest], + Awaitable[document.Document]]: + r"""Return a callable for the update document method over gRPC. + + Updates a + [Document][google.cloud.discoveryengine.v1beta.Document]. + + Returns: + Callable[[~.UpdateDocumentRequest], + Awaitable[~.Document]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_document' not in self._stubs: + self._stubs['update_document'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.DocumentService/UpdateDocument', + request_serializer=document_service.UpdateDocumentRequest.serialize, + response_deserializer=document.Document.deserialize, + ) + return self._stubs['update_document'] + + @property + def delete_document(self) -> Callable[ + [document_service.DeleteDocumentRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete document method over gRPC. + + Deletes a + [Document][google.cloud.discoveryengine.v1beta.Document]. + + Returns: + Callable[[~.DeleteDocumentRequest], + 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_document' not in self._stubs: + self._stubs['delete_document'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.DocumentService/DeleteDocument', + request_serializer=document_service.DeleteDocumentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_document'] + + @property + def import_documents(self) -> Callable[ + [import_config.ImportDocumentsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import documents method over gRPC. + + Bulk import of multiple + [Document][google.cloud.discoveryengine.v1beta.Document]s. + Request processing may be synchronous. Non-existing items will + be created. + + Note: It is possible for a subset of the + [Document][google.cloud.discoveryengine.v1beta.Document]s to be + successfully updated. + + Returns: + Callable[[~.ImportDocumentsRequest], + 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 'import_documents' not in self._stubs: + self._stubs['import_documents'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.DocumentService/ImportDocuments', + request_serializer=import_config.ImportDocumentsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_documents'] + + @property + def purge_documents(self) -> Callable[ + [purge_config.PurgeDocumentsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the purge documents method over gRPC. + + Permanently deletes all selected + [Document][google.cloud.discoveryengine.v1beta.Document]s in a + branch. + + This process is asynchronous. Depending on the number of + [Document][google.cloud.discoveryengine.v1beta.Document]s to be + deleted, this operation can take hours to complete. Before the + delete operation completes, some + [Document][google.cloud.discoveryengine.v1beta.Document]s might + still be returned by + [DocumentService.GetDocument][google.cloud.discoveryengine.v1beta.DocumentService.GetDocument] + or + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1beta.DocumentService.ListDocuments]. + + To get a list of the + [Document][google.cloud.discoveryengine.v1beta.Document]s to be + deleted, set + [PurgeDocumentsRequest.force][google.cloud.discoveryengine.v1beta.PurgeDocumentsRequest.force] + to false. + + Returns: + Callable[[~.PurgeDocumentsRequest], + 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 'purge_documents' not in self._stubs: + self._stubs['purge_documents'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.DocumentService/PurgeDocuments', + request_serializer=purge_config.PurgeDocumentsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['purge_documents'] + + def close(self): + return self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ( + 'DocumentServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/rest.py new file mode 100644 index 000000000000..4d4937514e59 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/rest.py @@ -0,0 +1,1429 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.cloud.location import locations_pb2 # type: ignore +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.discoveryengine_v1beta.types import document +from google.cloud.discoveryengine_v1beta.types import document as gcd_document +from google.cloud.discoveryengine_v1beta.types import document_service +from google.cloud.discoveryengine_v1beta.types import import_config +from google.cloud.discoveryengine_v1beta.types import purge_config +from google.protobuf import empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from .base import DocumentServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class DocumentServiceRestInterceptor: + """Interceptor for DocumentService. + + 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 DocumentServiceRestTransport. + + .. code-block:: python + class MyCustomDocumentServiceInterceptor(DocumentServiceRestInterceptor): + def pre_create_document(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_document(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_document(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_document(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_document(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_import_documents(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_import_documents(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_documents(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_documents(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_purge_documents(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_purge_documents(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_document(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_document(self, response): + logging.log(f"Received response: {response}") + return response + + transport = DocumentServiceRestTransport(interceptor=MyCustomDocumentServiceInterceptor()) + client = DocumentServiceClient(transport=transport) + + + """ + def pre_create_document(self, request: document_service.CreateDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_service.CreateDocumentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_document + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentService server. + """ + return request, metadata + + def post_create_document(self, response: gcd_document.Document) -> gcd_document.Document: + """Post-rpc interceptor for create_document + + Override in a subclass to manipulate the response + after it is returned by the DocumentService server but before + it is returned to user code. + """ + return response + def pre_delete_document(self, request: document_service.DeleteDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_service.DeleteDocumentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_document + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentService server. + """ + return request, metadata + + def pre_get_document(self, request: document_service.GetDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_service.GetDocumentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_document + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentService server. + """ + return request, metadata + + def post_get_document(self, response: document.Document) -> document.Document: + """Post-rpc interceptor for get_document + + Override in a subclass to manipulate the response + after it is returned by the DocumentService server but before + it is returned to user code. + """ + return response + def pre_import_documents(self, request: import_config.ImportDocumentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[import_config.ImportDocumentsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for import_documents + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentService server. + """ + return request, metadata + + def post_import_documents(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for import_documents + + Override in a subclass to manipulate the response + after it is returned by the DocumentService server but before + it is returned to user code. + """ + return response + def pre_list_documents(self, request: document_service.ListDocumentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_service.ListDocumentsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_documents + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentService server. + """ + return request, metadata + + def post_list_documents(self, response: document_service.ListDocumentsResponse) -> document_service.ListDocumentsResponse: + """Post-rpc interceptor for list_documents + + Override in a subclass to manipulate the response + after it is returned by the DocumentService server but before + it is returned to user code. + """ + return response + def pre_purge_documents(self, request: purge_config.PurgeDocumentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[purge_config.PurgeDocumentsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for purge_documents + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentService server. + """ + return request, metadata + + def post_purge_documents(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for purge_documents + + Override in a subclass to manipulate the response + after it is returned by the DocumentService server but before + it is returned to user code. + """ + return response + def pre_update_document(self, request: document_service.UpdateDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_service.UpdateDocumentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_document + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentService server. + """ + return request, metadata + + def post_update_document(self, response: document.Document) -> document.Document: + """Post-rpc interceptor for update_document + + Override in a subclass to manipulate the response + after it is returned by the DocumentService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentService 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 DocumentService server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the DocumentService 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 DocumentService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class DocumentServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: DocumentServiceRestInterceptor + + +class DocumentServiceRestTransport(DocumentServiceTransport): + """REST backend transport for DocumentService. + + Service for ingesting + [Document][google.cloud.discoveryengine.v1beta.Document] information + of the customer's website. + + 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 = 'discoveryengine.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[DocumentServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or DocumentServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1beta") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CreateDocument(DocumentServiceRestStub): + def __hash__(self): + return hash("CreateDocument") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "documentId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_service.CreateDocumentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gcd_document.Document: + r"""Call the create document method over HTTP. + + Args: + request (~.document_service.CreateDocumentRequest): + The request object. Request message for + [DocumentService.CreateDocument][google.cloud.discoveryengine.v1beta.DocumentService.CreateDocument] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcd_document.Document: + Document captures all raw metadata + information of items to be recommended + or searched. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{parent=projects/*/locations/*/dataStores/*/branches/*}/documents', + 'body': 'document', + }, +{ + 'method': 'post', + 'uri': '/v1beta/{parent=projects/*/locations/*/collections/*/dataStores/*/branches/*}/documents', + 'body': 'document', + }, + ] + request, metadata = self._interceptor.pre_create_document(request, metadata) + pb_request = document_service.CreateDocumentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcd_document.Document() + pb_resp = gcd_document.Document.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_document(resp) + return resp + + class _DeleteDocument(DocumentServiceRestStub): + def __hash__(self): + return hash("DeleteDocument") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_service.DeleteDocumentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete document method over HTTP. + + Args: + request (~.document_service.DeleteDocumentRequest): + The request object. Request message for + [DocumentService.DeleteDocument][google.cloud.discoveryengine.v1beta.DocumentService.DeleteDocument] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/documents/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/documents/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_document(request, metadata) + pb_request = document_service.DeleteDocumentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _GetDocument(DocumentServiceRestStub): + def __hash__(self): + return hash("GetDocument") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_service.GetDocumentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> document.Document: + r"""Call the get document method over HTTP. + + Args: + request (~.document_service.GetDocumentRequest): + The request object. Request message for + [DocumentService.GetDocument][google.cloud.discoveryengine.v1beta.DocumentService.GetDocument] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.document.Document: + Document captures all raw metadata + information of items to be recommended + or searched. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/documents/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/documents/*}', + }, + ] + request, metadata = self._interceptor.pre_get_document(request, metadata) + pb_request = document_service.GetDocumentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = document.Document() + pb_resp = document.Document.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_document(resp) + return resp + + class _ImportDocuments(DocumentServiceRestStub): + def __hash__(self): + return hash("ImportDocuments") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: import_config.ImportDocumentsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the import documents method over HTTP. + + Args: + request (~.import_config.ImportDocumentsRequest): + The request object. Request message for Import methods. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{parent=projects/*/locations/*/dataStores/*/branches/*}/documents:import', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1beta/{parent=projects/*/locations/*/collections/*/dataStores/*/branches/*}/documents:import', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_import_documents(request, metadata) + pb_request = import_config.ImportDocumentsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_import_documents(resp) + return resp + + class _ListDocuments(DocumentServiceRestStub): + def __hash__(self): + return hash("ListDocuments") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_service.ListDocumentsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> document_service.ListDocumentsResponse: + r"""Call the list documents method over HTTP. + + Args: + request (~.document_service.ListDocumentsRequest): + The request object. Request message for + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1beta.DocumentService.ListDocuments] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.document_service.ListDocumentsResponse: + Response message for + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1beta.DocumentService.ListDocuments] + method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=projects/*/locations/*/dataStores/*/branches/*}/documents', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{parent=projects/*/locations/*/collections/*/dataStores/*/branches/*}/documents', + }, + ] + request, metadata = self._interceptor.pre_list_documents(request, metadata) + pb_request = document_service.ListDocumentsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = document_service.ListDocumentsResponse() + pb_resp = document_service.ListDocumentsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_documents(resp) + return resp + + class _PurgeDocuments(DocumentServiceRestStub): + def __hash__(self): + return hash("PurgeDocuments") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: purge_config.PurgeDocumentsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the purge documents method over HTTP. + + Args: + request (~.purge_config.PurgeDocumentsRequest): + The request object. Request message for + [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1beta.DocumentService.PurgeDocuments] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{parent=projects/*/locations/*/dataStores/*/branches/*}/documents:purge', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1beta/{parent=projects/*/locations/*/collections/*/dataStores/*/branches/*}/documents:purge', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_purge_documents(request, metadata) + pb_request = purge_config.PurgeDocumentsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_purge_documents(resp) + return resp + + class _UpdateDocument(DocumentServiceRestStub): + def __hash__(self): + return hash("UpdateDocument") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: document_service.UpdateDocumentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> document.Document: + r"""Call the update document method over HTTP. + + Args: + request (~.document_service.UpdateDocumentRequest): + The request object. Request message for + [DocumentService.UpdateDocument][google.cloud.discoveryengine.v1beta.DocumentService.UpdateDocument] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.document.Document: + Document captures all raw metadata + information of items to be recommended + or searched. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1beta/{document.name=projects/*/locations/*/dataStores/*/branches/*/documents/*}', + 'body': 'document', + }, +{ + 'method': 'patch', + 'uri': '/v1beta/{document.name=projects/*/locations/*/collections/*/dataStores/*/branches/*/documents/*}', + 'body': 'document', + }, + ] + request, metadata = self._interceptor.pre_update_document(request, metadata) + pb_request = document_service.UpdateDocumentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = document.Document() + pb_resp = document.Document.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_document(resp) + return resp + + @property + def create_document(self) -> Callable[ + [document_service.CreateDocumentRequest], + gcd_document.Document]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateDocument(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_document(self) -> Callable[ + [document_service.DeleteDocumentRequest], + 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._DeleteDocument(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_document(self) -> Callable[ + [document_service.GetDocumentRequest], + document.Document]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetDocument(self._session, self._host, self._interceptor) # type: ignore + + @property + def import_documents(self) -> Callable[ + [import_config.ImportDocumentsRequest], + 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._ImportDocuments(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_documents(self) -> Callable[ + [document_service.ListDocumentsRequest], + document_service.ListDocumentsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListDocuments(self._session, self._host, self._interceptor) # type: ignore + + @property + def purge_documents(self) -> Callable[ + [purge_config.PurgeDocumentsRequest], + 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._PurgeDocuments(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_document(self) -> Callable[ + [document_service.UpdateDocumentRequest], + document.Document]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateDocument(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(DocumentServiceRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(DocumentServiceRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'DocumentServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/__init__.py new file mode 100644 index 000000000000..ad8f24a9e055 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import RecommendationServiceClient +from .async_client import RecommendationServiceAsyncClient + +__all__ = ( + 'RecommendationServiceClient', + 'RecommendationServiceAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/async_client.py new file mode 100644 index 000000000000..d30e8ef14c51 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/async_client.py @@ -0,0 +1,389 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.discoveryengine_v1beta.types import recommendation_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .transports.base import RecommendationServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import RecommendationServiceGrpcAsyncIOTransport +from .client import RecommendationServiceClient + + +class RecommendationServiceAsyncClient: + """Service for making recommendations.""" + + _client: RecommendationServiceClient + + DEFAULT_ENDPOINT = RecommendationServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = RecommendationServiceClient.DEFAULT_MTLS_ENDPOINT + + document_path = staticmethod(RecommendationServiceClient.document_path) + parse_document_path = staticmethod(RecommendationServiceClient.parse_document_path) + serving_config_path = staticmethod(RecommendationServiceClient.serving_config_path) + parse_serving_config_path = staticmethod(RecommendationServiceClient.parse_serving_config_path) + common_billing_account_path = staticmethod(RecommendationServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(RecommendationServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(RecommendationServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(RecommendationServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(RecommendationServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(RecommendationServiceClient.parse_common_organization_path) + common_project_path = staticmethod(RecommendationServiceClient.common_project_path) + parse_common_project_path = staticmethod(RecommendationServiceClient.parse_common_project_path) + common_location_path = staticmethod(RecommendationServiceClient.common_location_path) + parse_common_location_path = staticmethod(RecommendationServiceClient.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: + RecommendationServiceAsyncClient: The constructed client. + """ + return RecommendationServiceClient.from_service_account_info.__func__(RecommendationServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RecommendationServiceAsyncClient: The constructed client. + """ + return RecommendationServiceClient.from_service_account_file.__func__(RecommendationServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return RecommendationServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> RecommendationServiceTransport: + """Returns the transport used by the client instance. + + Returns: + RecommendationServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(RecommendationServiceClient).get_transport_class, type(RecommendationServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, RecommendationServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the recommendation 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 (Union[str, ~.RecommendationServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = RecommendationServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def recommend(self, + request: Optional[Union[recommendation_service.RecommendRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> recommendation_service.RecommendResponse: + r"""Makes a recommendation, which requires a contextual + user event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_recommend(): + # Create a client + client = discoveryengine_v1beta.RecommendationServiceAsyncClient() + + # Initialize request argument(s) + user_event = discoveryengine_v1beta.UserEvent() + user_event.event_type = "event_type_value" + user_event.user_pseudo_id = "user_pseudo_id_value" + + request = discoveryengine_v1beta.RecommendRequest( + serving_config="serving_config_value", + user_event=user_event, + ) + + # Make the request + response = await client.recommend(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.RecommendRequest, dict]]): + The request object. Request message for Recommend method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.types.RecommendResponse: + Response message for Recommend + method. + + """ + # Create or coerce a protobuf request object. + request = recommendation_service.RecommendRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.recommend, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config", request.serving_config), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "RecommendationServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "RecommendationServiceAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/client.py new file mode 100644 index 000000000000..b532de6a9a8a --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/client.py @@ -0,0 +1,606 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.discoveryengine_v1beta.types import recommendation_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .transports.base import RecommendationServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import RecommendationServiceGrpcTransport +from .transports.grpc_asyncio import RecommendationServiceGrpcAsyncIOTransport +from .transports.rest import RecommendationServiceRestTransport + + +class RecommendationServiceClientMeta(type): + """Metaclass for the RecommendationService 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[RecommendationServiceTransport]] + _transport_registry["grpc"] = RecommendationServiceGrpcTransport + _transport_registry["grpc_asyncio"] = RecommendationServiceGrpcAsyncIOTransport + _transport_registry["rest"] = RecommendationServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[RecommendationServiceTransport]: + """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 RecommendationServiceClient(metaclass=RecommendationServiceClientMeta): + """Service for making recommendations.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RecommendationServiceClient: 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: + RecommendationServiceClient: 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) -> RecommendationServiceTransport: + """Returns the transport used by the client instance. + + Returns: + RecommendationServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def document_path(project: str,location: str,data_store: str,branch: str,document: str,) -> str: + """Returns a fully-qualified document string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) + + @staticmethod + def parse_document_path(path: str) -> Dict[str,str]: + """Parses a document path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)/documents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def serving_config_path(project: str,location: str,data_store: str,serving_config: str,) -> str: + """Returns a fully-qualified serving_config string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/servingConfigs/{serving_config}".format(project=project, location=location, data_store=data_store, serving_config=serving_config, ) + + @staticmethod + def parse_serving_config_path(path: str) -> Dict[str,str]: + """Parses a serving_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/servingConfigs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, RecommendationServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the recommendation 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 (Union[str, RecommendationServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, RecommendationServiceTransport): + # transport is a RecommendationServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def recommend(self, + request: Optional[Union[recommendation_service.RecommendRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> recommendation_service.RecommendResponse: + r"""Makes a recommendation, which requires a contextual + user event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_recommend(): + # Create a client + client = discoveryengine_v1beta.RecommendationServiceClient() + + # Initialize request argument(s) + user_event = discoveryengine_v1beta.UserEvent() + user_event.event_type = "event_type_value" + user_event.user_pseudo_id = "user_pseudo_id_value" + + request = discoveryengine_v1beta.RecommendRequest( + serving_config="serving_config_value", + user_event=user_event, + ) + + # Make the request + response = client.recommend(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.RecommendRequest, dict]): + The request object. Request message for Recommend method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.types.RecommendResponse: + Response message for Recommend + method. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a recommendation_service.RecommendRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, recommendation_service.RecommendRequest): + request = recommendation_service.RecommendRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.recommend] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config", request.serving_config), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "RecommendationServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "RecommendationServiceClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/__init__.py new file mode 100644 index 000000000000..ce9f9edfd346 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import RecommendationServiceTransport +from .grpc import RecommendationServiceGrpcTransport +from .grpc_asyncio import RecommendationServiceGrpcAsyncIOTransport +from .rest import RecommendationServiceRestTransport +from .rest import RecommendationServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[RecommendationServiceTransport]] +_transport_registry['grpc'] = RecommendationServiceGrpcTransport +_transport_registry['grpc_asyncio'] = RecommendationServiceGrpcAsyncIOTransport +_transport_registry['rest'] = RecommendationServiceRestTransport + +__all__ = ( + 'RecommendationServiceTransport', + 'RecommendationServiceGrpcTransport', + 'RecommendationServiceGrpcAsyncIOTransport', + 'RecommendationServiceRestTransport', + 'RecommendationServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/base.py new file mode 100644 index 000000000000..9ec66c3afaac --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/base.py @@ -0,0 +1,168 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.discoveryengine_v1beta.types import recommendation_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class RecommendationServiceTransport(abc.ABC): + """Abstract transport class for RecommendationService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'discoveryengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.recommend: gapic_v1.method.wrap_method( + self.recommend, + 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 recommend(self) -> Callable[ + [recommendation_service.RecommendRequest], + Union[ + recommendation_service.RecommendResponse, + Awaitable[recommendation_service.RecommendResponse] + ]]: + 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 kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'RecommendationServiceTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/grpc.py new file mode 100644 index 000000000000..bef973446851 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/grpc.py @@ -0,0 +1,303 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.discoveryengine_v1beta.types import recommendation_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import RecommendationServiceTransport, DEFAULT_CLIENT_INFO + + +class RecommendationServiceGrpcTransport(RecommendationServiceTransport): + """gRPC backend transport for RecommendationService. + + Service for making recommendations. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def recommend(self) -> Callable[ + [recommendation_service.RecommendRequest], + recommendation_service.RecommendResponse]: + r"""Return a callable for the recommend method over gRPC. + + Makes a recommendation, which requires a contextual + user event. + + Returns: + Callable[[~.RecommendRequest], + ~.RecommendResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'recommend' not in self._stubs: + self._stubs['recommend'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.RecommendationService/Recommend', + request_serializer=recommendation_service.RecommendRequest.serialize, + response_deserializer=recommendation_service.RecommendResponse.deserialize, + ) + return self._stubs['recommend'] + + def close(self): + self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'RecommendationServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..730f83fb04be --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/grpc_asyncio.py @@ -0,0 +1,302 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.discoveryengine_v1beta.types import recommendation_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import RecommendationServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import RecommendationServiceGrpcTransport + + +class RecommendationServiceGrpcAsyncIOTransport(RecommendationServiceTransport): + """gRPC AsyncIO backend transport for RecommendationService. + + Service for making recommendations. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def recommend(self) -> Callable[ + [recommendation_service.RecommendRequest], + Awaitable[recommendation_service.RecommendResponse]]: + r"""Return a callable for the recommend method over gRPC. + + Makes a recommendation, which requires a contextual + user event. + + Returns: + Callable[[~.RecommendRequest], + Awaitable[~.RecommendResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'recommend' not in self._stubs: + self._stubs['recommend'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.RecommendationService/Recommend', + request_serializer=recommendation_service.RecommendRequest.serialize, + response_deserializer=recommendation_service.RecommendResponse.deserialize, + ) + return self._stubs['recommend'] + + def close(self): + return self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ( + 'RecommendationServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/rest.py new file mode 100644 index 000000000000..83d301a7013d --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/rest.py @@ -0,0 +1,573 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.cloud.location import locations_pb2 # type: ignore +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.discoveryengine_v1beta.types import recommendation_service +from google.longrunning import operations_pb2 # type: ignore + +from .base import RecommendationServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class RecommendationServiceRestInterceptor: + """Interceptor for RecommendationService. + + 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 RecommendationServiceRestTransport. + + .. code-block:: python + class MyCustomRecommendationServiceInterceptor(RecommendationServiceRestInterceptor): + def pre_recommend(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_recommend(self, response): + logging.log(f"Received response: {response}") + return response + + transport = RecommendationServiceRestTransport(interceptor=MyCustomRecommendationServiceInterceptor()) + client = RecommendationServiceClient(transport=transport) + + + """ + def pre_recommend(self, request: recommendation_service.RecommendRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[recommendation_service.RecommendRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for recommend + + Override in a subclass to manipulate the request or metadata + before they are sent to the RecommendationService server. + """ + return request, metadata + + def post_recommend(self, response: recommendation_service.RecommendResponse) -> recommendation_service.RecommendResponse: + """Post-rpc interceptor for recommend + + Override in a subclass to manipulate the response + after it is returned by the RecommendationService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the RecommendationService 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 RecommendationService server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the RecommendationService 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 RecommendationService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class RecommendationServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: RecommendationServiceRestInterceptor + + +class RecommendationServiceRestTransport(RecommendationServiceTransport): + """REST backend transport for RecommendationService. + + Service for making recommendations. + + 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 = 'discoveryengine.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[RecommendationServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or RecommendationServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _Recommend(RecommendationServiceRestStub): + def __hash__(self): + return hash("Recommend") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: recommendation_service.RecommendRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> recommendation_service.RecommendResponse: + r"""Call the recommend method over HTTP. + + Args: + request (~.recommendation_service.RecommendRequest): + The request object. Request message for Recommend method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.recommendation_service.RecommendResponse: + Response message for Recommend + method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{serving_config=projects/*/locations/*/dataStores/*/servingConfigs/*}:recommend', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1beta/{serving_config=projects/*/locations/*/collections/*/dataStores/*/servingConfigs/*}:recommend', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_recommend(request, metadata) + pb_request = recommendation_service.RecommendRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = recommendation_service.RecommendResponse() + pb_resp = recommendation_service.RecommendResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_recommend(resp) + return resp + + @property + def recommend(self) -> Callable[ + [recommendation_service.RecommendRequest], + recommendation_service.RecommendResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Recommend(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(RecommendationServiceRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(RecommendationServiceRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'RecommendationServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/__init__.py new file mode 100644 index 000000000000..4e9455a921b6 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import SchemaServiceClient +from .async_client import SchemaServiceAsyncClient + +__all__ = ( + 'SchemaServiceClient', + 'SchemaServiceAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/async_client.py new file mode 100644 index 000000000000..7c4686176c93 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/async_client.py @@ -0,0 +1,902 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.discoveryengine_v1beta.services.schema_service import pagers +from google.cloud.discoveryengine_v1beta.types import schema +from google.cloud.discoveryengine_v1beta.types import schema as gcd_schema +from google.cloud.discoveryengine_v1beta.types import schema_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from .transports.base import SchemaServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SchemaServiceGrpcAsyncIOTransport +from .client import SchemaServiceClient + + +class SchemaServiceAsyncClient: + """Service for managing + [Schema][google.cloud.discoveryengine.v1beta.Schema]s. + """ + + _client: SchemaServiceClient + + DEFAULT_ENDPOINT = SchemaServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SchemaServiceClient.DEFAULT_MTLS_ENDPOINT + + data_store_path = staticmethod(SchemaServiceClient.data_store_path) + parse_data_store_path = staticmethod(SchemaServiceClient.parse_data_store_path) + schema_path = staticmethod(SchemaServiceClient.schema_path) + parse_schema_path = staticmethod(SchemaServiceClient.parse_schema_path) + common_billing_account_path = staticmethod(SchemaServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SchemaServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SchemaServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(SchemaServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(SchemaServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(SchemaServiceClient.parse_common_organization_path) + common_project_path = staticmethod(SchemaServiceClient.common_project_path) + parse_common_project_path = staticmethod(SchemaServiceClient.parse_common_project_path) + common_location_path = staticmethod(SchemaServiceClient.common_location_path) + parse_common_location_path = staticmethod(SchemaServiceClient.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: + SchemaServiceAsyncClient: The constructed client. + """ + return SchemaServiceClient.from_service_account_info.__func__(SchemaServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SchemaServiceAsyncClient: The constructed client. + """ + return SchemaServiceClient.from_service_account_file.__func__(SchemaServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return SchemaServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SchemaServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SchemaServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(SchemaServiceClient).get_transport_class, type(SchemaServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, SchemaServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the schema 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 (Union[str, ~.SchemaServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = SchemaServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def get_schema(self, + request: Optional[Union[schema_service.GetSchemaRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> schema.Schema: + r"""Gets a [Schema][google.cloud.discoveryengine.v1beta.Schema]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_get_schema(): + # Create a client + client = discoveryengine_v1beta.SchemaServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GetSchemaRequest( + name="name_value", + ) + + # Make the request + response = await client.get_schema(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.GetSchemaRequest, dict]]): + The request object. Request message for + [SchemaService.GetSchema][google.cloud.discoveryengine.v1beta.SchemaService.GetSchema] + method. + name (:class:`str`): + Required. The full resource name of the schema, in the + format of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.types.Schema: + Defines the structure and layout of a + type of document data. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = schema_service.GetSchemaRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_schema, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_schemas(self, + request: Optional[Union[schema_service.ListSchemasRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSchemasAsyncPager: + r"""Gets a list of + [Schema][google.cloud.discoveryengine.v1beta.Schema]s. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_list_schemas(): + # Create a client + client = discoveryengine_v1beta.SchemaServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ListSchemasRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_schemas(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.ListSchemasRequest, dict]]): + The request object. Request message for + [SchemaService.ListSchemas][google.cloud.discoveryengine.v1beta.SchemaService.ListSchemas] + method. + parent (:class:`str`): + Required. The parent data store resource name, in the + format of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.services.schema_service.pagers.ListSchemasAsyncPager: + Response message for + [SchemaService.ListSchemas][google.cloud.discoveryengine.v1beta.SchemaService.ListSchemas] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = schema_service.ListSchemasRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_schemas, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSchemasAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_schema(self, + request: Optional[Union[schema_service.CreateSchemaRequest, dict]] = None, + *, + parent: Optional[str] = None, + schema: Optional[gcd_schema.Schema] = None, + schema_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a [Schema][google.cloud.discoveryengine.v1beta.Schema]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_create_schema(): + # Create a client + client = discoveryengine_v1beta.SchemaServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.CreateSchemaRequest( + parent="parent_value", + schema_id="schema_id_value", + ) + + # Make the request + operation = client.create_schema(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.CreateSchemaRequest, dict]]): + The request object. Request message for + [SchemaService.CreateSchema][google.cloud.discoveryengine.v1beta.SchemaService.CreateSchema] + method. + parent (:class:`str`): + Required. The parent data store resource name, in the + format of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + schema (:class:`google.cloud.discoveryengine_v1beta.types.Schema`): + Required. The + [Schema][google.cloud.discoveryengine.v1beta.Schema] to + create. + + This corresponds to the ``schema`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + schema_id (:class:`str`): + Required. The ID to use for the + [Schema][google.cloud.discoveryengine.v1beta.Schema], + which will become the final component of the + [Schema.name][google.cloud.discoveryengine.v1beta.Schema.name]. + + This field should conform to + `RFC-1034 `__ + standard with a length limit of 63 characters. + + This corresponds to the ``schema_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.discoveryengine_v1beta.types.Schema` + Defines the structure and layout of a type of document + data. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, schema, schema_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = schema_service.CreateSchemaRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if schema is not None: + request.schema = schema + if schema_id is not None: + request.schema_id = schema_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_schema, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcd_schema.Schema, + metadata_type=schema_service.CreateSchemaMetadata, + ) + + # Done; return the response. + return response + + async def update_schema(self, + request: Optional[Union[schema_service.UpdateSchemaRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Updates a [Schema][google.cloud.discoveryengine.v1beta.Schema]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_update_schema(): + # Create a client + client = discoveryengine_v1beta.SchemaServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.UpdateSchemaRequest( + ) + + # Make the request + operation = client.update_schema(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.UpdateSchemaRequest, dict]]): + The request object. Request message for + [SchemaService.UpdateSchema][google.cloud.discoveryengine.v1beta.SchemaService.UpdateSchema] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.discoveryengine_v1beta.types.Schema` + Defines the structure and layout of a type of document + data. + + """ + # Create or coerce a protobuf request object. + request = schema_service.UpdateSchemaRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_schema, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("schema.name", request.schema.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + schema.Schema, + metadata_type=schema_service.UpdateSchemaMetadata, + ) + + # Done; return the response. + return response + + async def delete_schema(self, + request: Optional[Union[schema_service.DeleteSchemaRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a [Schema][google.cloud.discoveryengine.v1beta.Schema]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_delete_schema(): + # Create a client + client = discoveryengine_v1beta.SchemaServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.DeleteSchemaRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_schema(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.DeleteSchemaRequest, dict]]): + The request object. Request message for + [SchemaService.DeleteSchema][google.cloud.discoveryengine.v1beta.SchemaService.DeleteSchema] + method. + name (:class:`str`): + Required. The full resource name of the schema, in the + format of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = schema_service.DeleteSchemaRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_schema, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=schema_service.DeleteSchemaMetadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "SchemaServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "SchemaServiceAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/client.py new file mode 100644 index 000000000000..dac2c8a8e5b1 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/client.py @@ -0,0 +1,1119 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.discoveryengine_v1beta.services.schema_service import pagers +from google.cloud.discoveryengine_v1beta.types import schema +from google.cloud.discoveryengine_v1beta.types import schema as gcd_schema +from google.cloud.discoveryengine_v1beta.types import schema_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from .transports.base import SchemaServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SchemaServiceGrpcTransport +from .transports.grpc_asyncio import SchemaServiceGrpcAsyncIOTransport +from .transports.rest import SchemaServiceRestTransport + + +class SchemaServiceClientMeta(type): + """Metaclass for the SchemaService 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[SchemaServiceTransport]] + _transport_registry["grpc"] = SchemaServiceGrpcTransport + _transport_registry["grpc_asyncio"] = SchemaServiceGrpcAsyncIOTransport + _transport_registry["rest"] = SchemaServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[SchemaServiceTransport]: + """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 SchemaServiceClient(metaclass=SchemaServiceClientMeta): + """Service for managing + [Schema][google.cloud.discoveryengine.v1beta.Schema]s. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SchemaServiceClient: 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: + SchemaServiceClient: 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) -> SchemaServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SchemaServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def data_store_path(project: str,location: str,data_store: str,) -> str: + """Returns a fully-qualified data_store string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) + + @staticmethod + def parse_data_store_path(path: str) -> Dict[str,str]: + """Parses a data_store path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def schema_path(project: str,location: str,data_store: str,schema: str,) -> str: + """Returns a fully-qualified schema string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/schemas/{schema}".format(project=project, location=location, data_store=data_store, schema=schema, ) + + @staticmethod + def parse_schema_path(path: str) -> Dict[str,str]: + """Parses a schema path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/schemas/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, SchemaServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the schema 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 (Union[str, SchemaServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, SchemaServiceTransport): + # transport is a SchemaServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def get_schema(self, + request: Optional[Union[schema_service.GetSchemaRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> schema.Schema: + r"""Gets a [Schema][google.cloud.discoveryengine.v1beta.Schema]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_get_schema(): + # Create a client + client = discoveryengine_v1beta.SchemaServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GetSchemaRequest( + name="name_value", + ) + + # Make the request + response = client.get_schema(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.GetSchemaRequest, dict]): + The request object. Request message for + [SchemaService.GetSchema][google.cloud.discoveryengine.v1beta.SchemaService.GetSchema] + method. + name (str): + Required. The full resource name of the schema, in the + format of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.types.Schema: + Defines the structure and layout of a + type of document data. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a schema_service.GetSchemaRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, schema_service.GetSchemaRequest): + request = schema_service.GetSchemaRequest(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_schema] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_schemas(self, + request: Optional[Union[schema_service.ListSchemasRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSchemasPager: + r"""Gets a list of + [Schema][google.cloud.discoveryengine.v1beta.Schema]s. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_list_schemas(): + # Create a client + client = discoveryengine_v1beta.SchemaServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ListSchemasRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_schemas(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.ListSchemasRequest, dict]): + The request object. Request message for + [SchemaService.ListSchemas][google.cloud.discoveryengine.v1beta.SchemaService.ListSchemas] + method. + parent (str): + Required. The parent data store resource name, in the + format of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.services.schema_service.pagers.ListSchemasPager: + Response message for + [SchemaService.ListSchemas][google.cloud.discoveryengine.v1beta.SchemaService.ListSchemas] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a schema_service.ListSchemasRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, schema_service.ListSchemasRequest): + request = schema_service.ListSchemasRequest(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_schemas] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListSchemasPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_schema(self, + request: Optional[Union[schema_service.CreateSchemaRequest, dict]] = None, + *, + parent: Optional[str] = None, + schema: Optional[gcd_schema.Schema] = None, + schema_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a [Schema][google.cloud.discoveryengine.v1beta.Schema]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_create_schema(): + # Create a client + client = discoveryengine_v1beta.SchemaServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.CreateSchemaRequest( + parent="parent_value", + schema_id="schema_id_value", + ) + + # Make the request + operation = client.create_schema(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.CreateSchemaRequest, dict]): + The request object. Request message for + [SchemaService.CreateSchema][google.cloud.discoveryengine.v1beta.SchemaService.CreateSchema] + method. + parent (str): + Required. The parent data store resource name, in the + format of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + schema (google.cloud.discoveryengine_v1beta.types.Schema): + Required. The + [Schema][google.cloud.discoveryengine.v1beta.Schema] to + create. + + This corresponds to the ``schema`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + schema_id (str): + Required. The ID to use for the + [Schema][google.cloud.discoveryengine.v1beta.Schema], + which will become the final component of the + [Schema.name][google.cloud.discoveryengine.v1beta.Schema.name]. + + This field should conform to + `RFC-1034 `__ + standard with a length limit of 63 characters. + + This corresponds to the ``schema_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.discoveryengine_v1beta.types.Schema` + Defines the structure and layout of a type of document + data. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, schema, schema_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a schema_service.CreateSchemaRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, schema_service.CreateSchemaRequest): + request = schema_service.CreateSchemaRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if schema is not None: + request.schema = schema + if schema_id is not None: + request.schema_id = schema_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_schema] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gcd_schema.Schema, + metadata_type=schema_service.CreateSchemaMetadata, + ) + + # Done; return the response. + return response + + def update_schema(self, + request: Optional[Union[schema_service.UpdateSchemaRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Updates a [Schema][google.cloud.discoveryengine.v1beta.Schema]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_update_schema(): + # Create a client + client = discoveryengine_v1beta.SchemaServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.UpdateSchemaRequest( + ) + + # Make the request + operation = client.update_schema(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.UpdateSchemaRequest, dict]): + The request object. Request message for + [SchemaService.UpdateSchema][google.cloud.discoveryengine.v1beta.SchemaService.UpdateSchema] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.discoveryengine_v1beta.types.Schema` + Defines the structure and layout of a type of document + data. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a schema_service.UpdateSchemaRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, schema_service.UpdateSchemaRequest): + request = schema_service.UpdateSchemaRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_schema] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("schema.name", request.schema.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + schema.Schema, + metadata_type=schema_service.UpdateSchemaMetadata, + ) + + # Done; return the response. + return response + + def delete_schema(self, + request: Optional[Union[schema_service.DeleteSchemaRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a [Schema][google.cloud.discoveryengine.v1beta.Schema]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_delete_schema(): + # Create a client + client = discoveryengine_v1beta.SchemaServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.DeleteSchemaRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_schema(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.DeleteSchemaRequest, dict]): + The request object. Request message for + [SchemaService.DeleteSchema][google.cloud.discoveryengine.v1beta.SchemaService.DeleteSchema] + method. + name (str): + Required. The full resource name of the schema, in the + format of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a schema_service.DeleteSchemaRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, schema_service.DeleteSchemaRequest): + request = schema_service.DeleteSchemaRequest(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_schema] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=schema_service.DeleteSchemaMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "SchemaServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "SchemaServiceClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/pagers.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/pagers.py new file mode 100644 index 000000000000..02dc508d2620 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.discoveryengine_v1beta.types import schema +from google.cloud.discoveryengine_v1beta.types import schema_service + + +class ListSchemasPager: + """A pager for iterating through ``list_schemas`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1beta.types.ListSchemasResponse` object, and + provides an ``__iter__`` method to iterate through its + ``schemas`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSchemas`` requests and continue to iterate + through the ``schemas`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1beta.types.ListSchemasResponse` + 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[..., schema_service.ListSchemasResponse], + request: schema_service.ListSchemasRequest, + response: schema_service.ListSchemasResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.discoveryengine_v1beta.types.ListSchemasRequest): + The initial request object. + response (google.cloud.discoveryengine_v1beta.types.ListSchemasResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = schema_service.ListSchemasRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[schema_service.ListSchemasResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[schema.Schema]: + for page in self.pages: + yield from page.schemas + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSchemasAsyncPager: + """A pager for iterating through ``list_schemas`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1beta.types.ListSchemasResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``schemas`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSchemas`` requests and continue to iterate + through the ``schemas`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1beta.types.ListSchemasResponse` + 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[schema_service.ListSchemasResponse]], + request: schema_service.ListSchemasRequest, + response: schema_service.ListSchemasResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.discoveryengine_v1beta.types.ListSchemasRequest): + The initial request object. + response (google.cloud.discoveryengine_v1beta.types.ListSchemasResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = schema_service.ListSchemasRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[schema_service.ListSchemasResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[schema.Schema]: + async def async_generator(): + async for page in self.pages: + for response in page.schemas: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/__init__.py new file mode 100644 index 000000000000..d5ebd14e657b --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import SchemaServiceTransport +from .grpc import SchemaServiceGrpcTransport +from .grpc_asyncio import SchemaServiceGrpcAsyncIOTransport +from .rest import SchemaServiceRestTransport +from .rest import SchemaServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SchemaServiceTransport]] +_transport_registry['grpc'] = SchemaServiceGrpcTransport +_transport_registry['grpc_asyncio'] = SchemaServiceGrpcAsyncIOTransport +_transport_registry['rest'] = SchemaServiceRestTransport + +__all__ = ( + 'SchemaServiceTransport', + 'SchemaServiceGrpcTransport', + 'SchemaServiceGrpcAsyncIOTransport', + 'SchemaServiceRestTransport', + 'SchemaServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/base.py new file mode 100644 index 000000000000..eeb36e9fef51 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/base.py @@ -0,0 +1,231 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.discoveryengine_v1beta.types import schema +from google.cloud.discoveryengine_v1beta.types import schema_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class SchemaServiceTransport(abc.ABC): + """Abstract transport class for SchemaService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'discoveryengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get_schema: gapic_v1.method.wrap_method( + self.get_schema, + default_timeout=None, + client_info=client_info, + ), + self.list_schemas: gapic_v1.method.wrap_method( + self.list_schemas, + default_timeout=None, + client_info=client_info, + ), + self.create_schema: gapic_v1.method.wrap_method( + self.create_schema, + default_timeout=None, + client_info=client_info, + ), + self.update_schema: gapic_v1.method.wrap_method( + self.update_schema, + default_timeout=None, + client_info=client_info, + ), + self.delete_schema: gapic_v1.method.wrap_method( + self.delete_schema, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def get_schema(self) -> Callable[ + [schema_service.GetSchemaRequest], + Union[ + schema.Schema, + Awaitable[schema.Schema] + ]]: + raise NotImplementedError() + + @property + def list_schemas(self) -> Callable[ + [schema_service.ListSchemasRequest], + Union[ + schema_service.ListSchemasResponse, + Awaitable[schema_service.ListSchemasResponse] + ]]: + raise NotImplementedError() + + @property + def create_schema(self) -> Callable[ + [schema_service.CreateSchemaRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_schema(self) -> Callable[ + [schema_service.UpdateSchemaRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_schema(self) -> Callable[ + [schema_service.DeleteSchemaRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'SchemaServiceTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/grpc.py new file mode 100644 index 000000000000..59d88fb350c8 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/grpc.py @@ -0,0 +1,427 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.discoveryengine_v1beta.types import schema +from google.cloud.discoveryengine_v1beta.types import schema_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import SchemaServiceTransport, DEFAULT_CLIENT_INFO + + +class SchemaServiceGrpcTransport(SchemaServiceTransport): + """gRPC backend transport for SchemaService. + + Service for managing + [Schema][google.cloud.discoveryengine.v1beta.Schema]s. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def get_schema(self) -> Callable[ + [schema_service.GetSchemaRequest], + schema.Schema]: + r"""Return a callable for the get schema method over gRPC. + + Gets a [Schema][google.cloud.discoveryengine.v1beta.Schema]. + + Returns: + Callable[[~.GetSchemaRequest], + ~.Schema]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_schema' not in self._stubs: + self._stubs['get_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.SchemaService/GetSchema', + request_serializer=schema_service.GetSchemaRequest.serialize, + response_deserializer=schema.Schema.deserialize, + ) + return self._stubs['get_schema'] + + @property + def list_schemas(self) -> Callable[ + [schema_service.ListSchemasRequest], + schema_service.ListSchemasResponse]: + r"""Return a callable for the list schemas method over gRPC. + + Gets a list of + [Schema][google.cloud.discoveryengine.v1beta.Schema]s. + + Returns: + Callable[[~.ListSchemasRequest], + ~.ListSchemasResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_schemas' not in self._stubs: + self._stubs['list_schemas'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.SchemaService/ListSchemas', + request_serializer=schema_service.ListSchemasRequest.serialize, + response_deserializer=schema_service.ListSchemasResponse.deserialize, + ) + return self._stubs['list_schemas'] + + @property + def create_schema(self) -> Callable[ + [schema_service.CreateSchemaRequest], + operations_pb2.Operation]: + r"""Return a callable for the create schema method over gRPC. + + Creates a [Schema][google.cloud.discoveryengine.v1beta.Schema]. + + Returns: + Callable[[~.CreateSchemaRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_schema' not in self._stubs: + self._stubs['create_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.SchemaService/CreateSchema', + request_serializer=schema_service.CreateSchemaRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_schema'] + + @property + def update_schema(self) -> Callable[ + [schema_service.UpdateSchemaRequest], + operations_pb2.Operation]: + r"""Return a callable for the update schema method over gRPC. + + Updates a [Schema][google.cloud.discoveryengine.v1beta.Schema]. + + Returns: + Callable[[~.UpdateSchemaRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_schema' not in self._stubs: + self._stubs['update_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.SchemaService/UpdateSchema', + request_serializer=schema_service.UpdateSchemaRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_schema'] + + @property + def delete_schema(self) -> Callable[ + [schema_service.DeleteSchemaRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete schema method over gRPC. + + Deletes a [Schema][google.cloud.discoveryengine.v1beta.Schema]. + + Returns: + Callable[[~.DeleteSchemaRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_schema' not in self._stubs: + self._stubs['delete_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.SchemaService/DeleteSchema', + request_serializer=schema_service.DeleteSchemaRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_schema'] + + def close(self): + self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'SchemaServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..c3fac15e2ad3 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/grpc_asyncio.py @@ -0,0 +1,426 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.discoveryengine_v1beta.types import schema +from google.cloud.discoveryengine_v1beta.types import schema_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import SchemaServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import SchemaServiceGrpcTransport + + +class SchemaServiceGrpcAsyncIOTransport(SchemaServiceTransport): + """gRPC AsyncIO backend transport for SchemaService. + + Service for managing + [Schema][google.cloud.discoveryengine.v1beta.Schema]s. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def get_schema(self) -> Callable[ + [schema_service.GetSchemaRequest], + Awaitable[schema.Schema]]: + r"""Return a callable for the get schema method over gRPC. + + Gets a [Schema][google.cloud.discoveryengine.v1beta.Schema]. + + Returns: + Callable[[~.GetSchemaRequest], + Awaitable[~.Schema]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_schema' not in self._stubs: + self._stubs['get_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.SchemaService/GetSchema', + request_serializer=schema_service.GetSchemaRequest.serialize, + response_deserializer=schema.Schema.deserialize, + ) + return self._stubs['get_schema'] + + @property + def list_schemas(self) -> Callable[ + [schema_service.ListSchemasRequest], + Awaitable[schema_service.ListSchemasResponse]]: + r"""Return a callable for the list schemas method over gRPC. + + Gets a list of + [Schema][google.cloud.discoveryengine.v1beta.Schema]s. + + Returns: + Callable[[~.ListSchemasRequest], + Awaitable[~.ListSchemasResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_schemas' not in self._stubs: + self._stubs['list_schemas'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.SchemaService/ListSchemas', + request_serializer=schema_service.ListSchemasRequest.serialize, + response_deserializer=schema_service.ListSchemasResponse.deserialize, + ) + return self._stubs['list_schemas'] + + @property + def create_schema(self) -> Callable[ + [schema_service.CreateSchemaRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create schema method over gRPC. + + Creates a [Schema][google.cloud.discoveryengine.v1beta.Schema]. + + Returns: + Callable[[~.CreateSchemaRequest], + 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_schema' not in self._stubs: + self._stubs['create_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.SchemaService/CreateSchema', + request_serializer=schema_service.CreateSchemaRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_schema'] + + @property + def update_schema(self) -> Callable[ + [schema_service.UpdateSchemaRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update schema method over gRPC. + + Updates a [Schema][google.cloud.discoveryengine.v1beta.Schema]. + + Returns: + Callable[[~.UpdateSchemaRequest], + 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_schema' not in self._stubs: + self._stubs['update_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.SchemaService/UpdateSchema', + request_serializer=schema_service.UpdateSchemaRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_schema'] + + @property + def delete_schema(self) -> Callable[ + [schema_service.DeleteSchemaRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete schema method over gRPC. + + Deletes a [Schema][google.cloud.discoveryengine.v1beta.Schema]. + + Returns: + Callable[[~.DeleteSchemaRequest], + 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_schema' not in self._stubs: + self._stubs['delete_schema'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.SchemaService/DeleteSchema', + request_serializer=schema_service.DeleteSchemaRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_schema'] + + def close(self): + return self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ( + 'SchemaServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/rest.py new file mode 100644 index 000000000000..018217eaa473 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/rest.py @@ -0,0 +1,1192 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.cloud.location import locations_pb2 # type: ignore +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.discoveryengine_v1beta.types import schema +from google.cloud.discoveryengine_v1beta.types import schema_service +from google.longrunning import operations_pb2 # type: ignore + +from .base import SchemaServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class SchemaServiceRestInterceptor: + """Interceptor for SchemaService. + + 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 SchemaServiceRestTransport. + + .. code-block:: python + class MyCustomSchemaServiceInterceptor(SchemaServiceRestInterceptor): + def pre_create_schema(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_schema(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_schema(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_schema(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_schema(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_schema(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_schemas(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_schemas(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_schema(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_schema(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SchemaServiceRestTransport(interceptor=MyCustomSchemaServiceInterceptor()) + client = SchemaServiceClient(transport=transport) + + + """ + def pre_create_schema(self, request: schema_service.CreateSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[schema_service.CreateSchemaRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_schema + + Override in a subclass to manipulate the request or metadata + before they are sent to the SchemaService server. + """ + return request, metadata + + def post_create_schema(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_schema + + Override in a subclass to manipulate the response + after it is returned by the SchemaService server but before + it is returned to user code. + """ + return response + def pre_delete_schema(self, request: schema_service.DeleteSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[schema_service.DeleteSchemaRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_schema + + Override in a subclass to manipulate the request or metadata + before they are sent to the SchemaService server. + """ + return request, metadata + + def post_delete_schema(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_schema + + Override in a subclass to manipulate the response + after it is returned by the SchemaService server but before + it is returned to user code. + """ + return response + def pre_get_schema(self, request: schema_service.GetSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[schema_service.GetSchemaRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_schema + + Override in a subclass to manipulate the request or metadata + before they are sent to the SchemaService server. + """ + return request, metadata + + def post_get_schema(self, response: schema.Schema) -> schema.Schema: + """Post-rpc interceptor for get_schema + + Override in a subclass to manipulate the response + after it is returned by the SchemaService server but before + it is returned to user code. + """ + return response + def pre_list_schemas(self, request: schema_service.ListSchemasRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[schema_service.ListSchemasRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_schemas + + Override in a subclass to manipulate the request or metadata + before they are sent to the SchemaService server. + """ + return request, metadata + + def post_list_schemas(self, response: schema_service.ListSchemasResponse) -> schema_service.ListSchemasResponse: + """Post-rpc interceptor for list_schemas + + Override in a subclass to manipulate the response + after it is returned by the SchemaService server but before + it is returned to user code. + """ + return response + def pre_update_schema(self, request: schema_service.UpdateSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[schema_service.UpdateSchemaRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_schema + + Override in a subclass to manipulate the request or metadata + before they are sent to the SchemaService server. + """ + return request, metadata + + def post_update_schema(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_schema + + Override in a subclass to manipulate the response + after it is returned by the SchemaService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the SchemaService 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 SchemaService server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the SchemaService 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 SchemaService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class SchemaServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: SchemaServiceRestInterceptor + + +class SchemaServiceRestTransport(SchemaServiceTransport): + """REST backend transport for SchemaService. + + Service for managing + [Schema][google.cloud.discoveryengine.v1beta.Schema]s. + + 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 = 'discoveryengine.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[SchemaServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or SchemaServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1beta") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CreateSchema(SchemaServiceRestStub): + def __hash__(self): + return hash("CreateSchema") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "schemaId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: schema_service.CreateSchemaRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create schema method over HTTP. + + Args: + request (~.schema_service.CreateSchemaRequest): + The request object. Request message for + [SchemaService.CreateSchema][google.cloud.discoveryengine.v1beta.SchemaService.CreateSchema] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{parent=projects/*/locations/*/dataStores/*}/schemas', + 'body': 'schema', + }, +{ + 'method': 'post', + 'uri': '/v1beta/{parent=projects/*/locations/*/collections/*/dataStores/*}/schemas', + 'body': 'schema', + }, + ] + request, metadata = self._interceptor.pre_create_schema(request, metadata) + pb_request = schema_service.CreateSchemaRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_schema(resp) + return resp + + class _DeleteSchema(SchemaServiceRestStub): + def __hash__(self): + return hash("DeleteSchema") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: schema_service.DeleteSchemaRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete schema method over HTTP. + + Args: + request (~.schema_service.DeleteSchemaRequest): + The request object. Request message for + [SchemaService.DeleteSchema][google.cloud.discoveryengine.v1beta.SchemaService.DeleteSchema] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/schemas/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_schema(request, metadata) + pb_request = schema_service.DeleteSchemaRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_schema(resp) + return resp + + class _GetSchema(SchemaServiceRestStub): + def __hash__(self): + return hash("GetSchema") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: schema_service.GetSchemaRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> schema.Schema: + r"""Call the get schema method over HTTP. + + Args: + request (~.schema_service.GetSchemaRequest): + The request object. Request message for + [SchemaService.GetSchema][google.cloud.discoveryengine.v1beta.SchemaService.GetSchema] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.schema.Schema: + Defines the structure and layout of a + type of document data. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/schemas/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}', + }, + ] + request, metadata = self._interceptor.pre_get_schema(request, metadata) + pb_request = schema_service.GetSchemaRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = schema.Schema() + pb_resp = schema.Schema.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_schema(resp) + return resp + + class _ListSchemas(SchemaServiceRestStub): + def __hash__(self): + return hash("ListSchemas") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: schema_service.ListSchemasRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> schema_service.ListSchemasResponse: + r"""Call the list schemas method over HTTP. + + Args: + request (~.schema_service.ListSchemasRequest): + The request object. Request message for + [SchemaService.ListSchemas][google.cloud.discoveryengine.v1beta.SchemaService.ListSchemas] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.schema_service.ListSchemasResponse: + Response message for + [SchemaService.ListSchemas][google.cloud.discoveryengine.v1beta.SchemaService.ListSchemas] + method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=projects/*/locations/*/dataStores/*}/schemas', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{parent=projects/*/locations/*/collections/*/dataStores/*}/schemas', + }, + ] + request, metadata = self._interceptor.pre_list_schemas(request, metadata) + pb_request = schema_service.ListSchemasRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = schema_service.ListSchemasResponse() + pb_resp = schema_service.ListSchemasResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_schemas(resp) + return resp + + class _UpdateSchema(SchemaServiceRestStub): + def __hash__(self): + return hash("UpdateSchema") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: schema_service.UpdateSchemaRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the update schema method over HTTP. + + Args: + request (~.schema_service.UpdateSchemaRequest): + The request object. Request message for + [SchemaService.UpdateSchema][google.cloud.discoveryengine.v1beta.SchemaService.UpdateSchema] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1beta/{schema.name=projects/*/locations/*/dataStores/*/schemas/*}', + 'body': 'schema', + }, +{ + 'method': 'patch', + 'uri': '/v1beta/{schema.name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}', + 'body': 'schema', + }, + ] + request, metadata = self._interceptor.pre_update_schema(request, metadata) + pb_request = schema_service.UpdateSchemaRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_schema(resp) + return resp + + @property + def create_schema(self) -> Callable[ + [schema_service.CreateSchemaRequest], + 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._CreateSchema(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_schema(self) -> Callable[ + [schema_service.DeleteSchemaRequest], + 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._DeleteSchema(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_schema(self) -> Callable[ + [schema_service.GetSchemaRequest], + schema.Schema]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSchema(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_schemas(self) -> Callable[ + [schema_service.ListSchemasRequest], + schema_service.ListSchemasResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSchemas(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_schema(self) -> Callable[ + [schema_service.UpdateSchemaRequest], + 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._UpdateSchema(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(SchemaServiceRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(SchemaServiceRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'SchemaServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/__init__.py new file mode 100644 index 000000000000..0355170e3569 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import SearchServiceClient +from .async_client import SearchServiceAsyncClient + +__all__ = ( + 'SearchServiceClient', + 'SearchServiceAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/async_client.py new file mode 100644 index 000000000000..015496bf3c02 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/async_client.py @@ -0,0 +1,402 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.discoveryengine_v1beta.services.search_service import pagers +from google.cloud.discoveryengine_v1beta.types import search_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport +from .client import SearchServiceClient + + +class SearchServiceAsyncClient: + """Service for search.""" + + _client: SearchServiceClient + + DEFAULT_ENDPOINT = SearchServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SearchServiceClient.DEFAULT_MTLS_ENDPOINT + + branch_path = staticmethod(SearchServiceClient.branch_path) + parse_branch_path = staticmethod(SearchServiceClient.parse_branch_path) + document_path = staticmethod(SearchServiceClient.document_path) + parse_document_path = staticmethod(SearchServiceClient.parse_document_path) + serving_config_path = staticmethod(SearchServiceClient.serving_config_path) + parse_serving_config_path = staticmethod(SearchServiceClient.parse_serving_config_path) + common_billing_account_path = staticmethod(SearchServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(SearchServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(SearchServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(SearchServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(SearchServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(SearchServiceClient.parse_common_organization_path) + common_project_path = staticmethod(SearchServiceClient.common_project_path) + parse_common_project_path = staticmethod(SearchServiceClient.parse_common_project_path) + common_location_path = staticmethod(SearchServiceClient.common_location_path) + parse_common_location_path = staticmethod(SearchServiceClient.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: + SearchServiceAsyncClient: The constructed client. + """ + return SearchServiceClient.from_service_account_info.__func__(SearchServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceAsyncClient: The constructed client. + """ + return SearchServiceClient.from_service_account_file.__func__(SearchServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return SearchServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SearchServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SearchServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(SearchServiceClient).get_transport_class, type(SearchServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, SearchServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the search 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 (Union[str, ~.SearchServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = SearchServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def search(self, + request: Optional[Union[search_service.SearchRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAsyncPager: + r"""Performs a search. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_search(): + # Create a client + client = discoveryengine_v1beta.SearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.SearchRequest( + serving_config="serving_config_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.SearchRequest, dict]]): + The request object. Request message for + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.services.search_service.pagers.SearchAsyncPager: + Response message for + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + request = search_service.SearchRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.search, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config", request.serving_config), + )), + ) + + # 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.SearchAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "SearchServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "SearchServiceAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/client.py new file mode 100644 index 000000000000..a4bc64a88839 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/client.py @@ -0,0 +1,628 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.cloud.discoveryengine_v1beta.services.search_service import pagers +from google.cloud.discoveryengine_v1beta.types import search_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import SearchServiceGrpcTransport +from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport +from .transports.rest import SearchServiceRestTransport + + +class SearchServiceClientMeta(type): + """Metaclass for the SearchService 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[SearchServiceTransport]] + _transport_registry["grpc"] = SearchServiceGrpcTransport + _transport_registry["grpc_asyncio"] = SearchServiceGrpcAsyncIOTransport + _transport_registry["rest"] = SearchServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[SearchServiceTransport]: + """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 SearchServiceClient(metaclass=SearchServiceClientMeta): + """Service for search.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SearchServiceClient: 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: + SearchServiceClient: 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) -> SearchServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SearchServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def branch_path(project: str,location: str,data_store: str,branch: str,) -> str: + """Returns a fully-qualified branch string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}".format(project=project, location=location, data_store=data_store, branch=branch, ) + + @staticmethod + def parse_branch_path(path: str) -> Dict[str,str]: + """Parses a branch path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def document_path(project: str,location: str,data_store: str,branch: str,document: str,) -> str: + """Returns a fully-qualified document string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) + + @staticmethod + def parse_document_path(path: str) -> Dict[str,str]: + """Parses a document path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)/documents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def serving_config_path(project: str,location: str,data_store: str,serving_config: str,) -> str: + """Returns a fully-qualified serving_config string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/servingConfigs/{serving_config}".format(project=project, location=location, data_store=data_store, serving_config=serving_config, ) + + @staticmethod + def parse_serving_config_path(path: str) -> Dict[str,str]: + """Parses a serving_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/servingConfigs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, SearchServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the search 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 (Union[str, SearchServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, SearchServiceTransport): + # transport is a SearchServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def search(self, + request: Optional[Union[search_service.SearchRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchPager: + r"""Performs a search. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_search(): + # Create a client + client = discoveryengine_v1beta.SearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.SearchRequest( + serving_config="serving_config_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.SearchRequest, dict]): + The request object. Request message for + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.services.search_service.pagers.SearchPager: + Response message for + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a search_service.SearchRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, search_service.SearchRequest): + request = search_service.SearchRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("serving_config", request.serving_config), + )), + ) + + # 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.SearchPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "SearchServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "SearchServiceClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/pagers.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/pagers.py new file mode 100644 index 000000000000..cb898bf1e1a2 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/pagers.py @@ -0,0 +1,139 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.discoveryengine_v1beta.types import search_service + + +class SearchPager: + """A pager for iterating through ``search`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1beta.types.SearchResponse` object, and + provides an ``__iter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``Search`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1beta.types.SearchResponse` + 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[..., search_service.SearchResponse], + request: search_service.SearchRequest, + response: search_service.SearchResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.discoveryengine_v1beta.types.SearchRequest): + The initial request object. + response (google.cloud.discoveryengine_v1beta.types.SearchResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = search_service.SearchRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[search_service.SearchResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[search_service.SearchResponse.SearchResult]: + for page in self.pages: + yield from page.results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchAsyncPager: + """A pager for iterating through ``search`` requests. + + This class thinly wraps an initial + :class:`google.cloud.discoveryengine_v1beta.types.SearchResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``Search`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.discoveryengine_v1beta.types.SearchResponse` + 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[search_service.SearchResponse]], + request: search_service.SearchRequest, + response: search_service.SearchResponse, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.discoveryengine_v1beta.types.SearchRequest): + The initial request object. + response (google.cloud.discoveryengine_v1beta.types.SearchResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = search_service.SearchRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[search_service.SearchResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[search_service.SearchResponse.SearchResult]: + async def async_generator(): + async for page in self.pages: + for response in page.results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/__init__.py new file mode 100644 index 000000000000..4282aef080e3 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import SearchServiceTransport +from .grpc import SearchServiceGrpcTransport +from .grpc_asyncio import SearchServiceGrpcAsyncIOTransport +from .rest import SearchServiceRestTransport +from .rest import SearchServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] +_transport_registry['grpc'] = SearchServiceGrpcTransport +_transport_registry['grpc_asyncio'] = SearchServiceGrpcAsyncIOTransport +_transport_registry['rest'] = SearchServiceRestTransport + +__all__ = ( + 'SearchServiceTransport', + 'SearchServiceGrpcTransport', + 'SearchServiceGrpcAsyncIOTransport', + 'SearchServiceRestTransport', + 'SearchServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/base.py new file mode 100644 index 000000000000..0017b8de30e8 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/base.py @@ -0,0 +1,168 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.discoveryengine_v1beta.types import search_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class SearchServiceTransport(abc.ABC): + """Abstract transport class for SearchService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'discoveryengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.search: gapic_v1.method.wrap_method( + self.search, + 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 search(self) -> Callable[ + [search_service.SearchRequest], + Union[ + search_service.SearchResponse, + Awaitable[search_service.SearchResponse] + ]]: + 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 kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'SearchServiceTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/grpc.py new file mode 100644 index 000000000000..575f254d79c3 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/grpc.py @@ -0,0 +1,302 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.discoveryengine_v1beta.types import search_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO + + +class SearchServiceGrpcTransport(SearchServiceTransport): + """gRPC backend transport for SearchService. + + Service for search. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def search(self) -> Callable[ + [search_service.SearchRequest], + search_service.SearchResponse]: + r"""Return a callable for the search method over gRPC. + + Performs a search. + + Returns: + Callable[[~.SearchRequest], + ~.SearchResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search' not in self._stubs: + self._stubs['search'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.SearchService/Search', + request_serializer=search_service.SearchRequest.serialize, + response_deserializer=search_service.SearchResponse.deserialize, + ) + return self._stubs['search'] + + def close(self): + self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'SearchServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..3222cb6c4323 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/grpc_asyncio.py @@ -0,0 +1,301 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.discoveryengine_v1beta.types import search_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import SearchServiceGrpcTransport + + +class SearchServiceGrpcAsyncIOTransport(SearchServiceTransport): + """gRPC AsyncIO backend transport for SearchService. + + Service for search. + + 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def search(self) -> Callable[ + [search_service.SearchRequest], + Awaitable[search_service.SearchResponse]]: + r"""Return a callable for the search method over gRPC. + + Performs a search. + + Returns: + Callable[[~.SearchRequest], + Awaitable[~.SearchResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search' not in self._stubs: + self._stubs['search'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.SearchService/Search', + request_serializer=search_service.SearchRequest.serialize, + response_deserializer=search_service.SearchResponse.deserialize, + ) + return self._stubs['search'] + + def close(self): + return self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ( + 'SearchServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/rest.py new file mode 100644 index 000000000000..1fd752a5c08c --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/rest.py @@ -0,0 +1,576 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.cloud.location import locations_pb2 # type: ignore +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.discoveryengine_v1beta.types import search_service +from google.longrunning import operations_pb2 # type: ignore + +from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class SearchServiceRestInterceptor: + """Interceptor for SearchService. + + 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 SearchServiceRestTransport. + + .. code-block:: python + class MyCustomSearchServiceInterceptor(SearchServiceRestInterceptor): + def pre_search(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_search(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SearchServiceRestTransport(interceptor=MyCustomSearchServiceInterceptor()) + client = SearchServiceClient(transport=transport) + + + """ + def pre_search(self, request: search_service.SearchRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[search_service.SearchRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for search + + Override in a subclass to manipulate the request or metadata + before they are sent to the SearchService server. + """ + return request, metadata + + def post_search(self, response: search_service.SearchResponse) -> search_service.SearchResponse: + """Post-rpc interceptor for search + + Override in a subclass to manipulate the response + after it is returned by the SearchService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the SearchService 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 SearchService server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the SearchService 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 SearchService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class SearchServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: SearchServiceRestInterceptor + + +class SearchServiceRestTransport(SearchServiceTransport): + """REST backend transport for SearchService. + + Service for search. + + 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 = 'discoveryengine.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[SearchServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or SearchServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _Search(SearchServiceRestStub): + def __hash__(self): + return hash("Search") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: search_service.SearchRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> search_service.SearchResponse: + r"""Call the search method over HTTP. + + Args: + request (~.search_service.SearchRequest): + The request object. Request message for + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.search_service.SearchResponse: + Response message for + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{serving_config=projects/*/locations/*/dataStores/*/servingConfigs/*}:search', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1beta/{serving_config=projects/*/locations/*/collections/*/dataStores/*/servingConfigs/*}:search', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_search(request, metadata) + pb_request = search_service.SearchRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = search_service.SearchResponse() + pb_resp = search_service.SearchResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_search(resp) + return resp + + @property + def search(self) -> Callable[ + [search_service.SearchRequest], + search_service.SearchResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Search(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(SearchServiceRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(SearchServiceRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'SearchServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/__init__.py new file mode 100644 index 000000000000..387c002d1701 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import UserEventServiceClient +from .async_client import UserEventServiceAsyncClient + +__all__ = ( + 'UserEventServiceClient', + 'UserEventServiceAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/async_client.py new file mode 100644 index 000000000000..03cc92de4659 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/async_client.py @@ -0,0 +1,644 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.discoveryengine_v1beta.types import common +from google.cloud.discoveryengine_v1beta.types import import_config +from google.cloud.discoveryengine_v1beta.types import user_event +from google.cloud.discoveryengine_v1beta.types import user_event_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport +from .client import UserEventServiceClient + + +class UserEventServiceAsyncClient: + """Service for ingesting end user actions on a website to + Discovery Engine API. + """ + + _client: UserEventServiceClient + + DEFAULT_ENDPOINT = UserEventServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = UserEventServiceClient.DEFAULT_MTLS_ENDPOINT + + data_store_path = staticmethod(UserEventServiceClient.data_store_path) + parse_data_store_path = staticmethod(UserEventServiceClient.parse_data_store_path) + document_path = staticmethod(UserEventServiceClient.document_path) + parse_document_path = staticmethod(UserEventServiceClient.parse_document_path) + common_billing_account_path = staticmethod(UserEventServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(UserEventServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(UserEventServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(UserEventServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(UserEventServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(UserEventServiceClient.parse_common_organization_path) + common_project_path = staticmethod(UserEventServiceClient.common_project_path) + parse_common_project_path = staticmethod(UserEventServiceClient.parse_common_project_path) + common_location_path = staticmethod(UserEventServiceClient.common_location_path) + parse_common_location_path = staticmethod(UserEventServiceClient.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: + UserEventServiceAsyncClient: The constructed client. + """ + return UserEventServiceClient.from_service_account_info.__func__(UserEventServiceAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceAsyncClient: The constructed client. + """ + return UserEventServiceClient.from_service_account_file.__func__(UserEventServiceAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return UserEventServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> UserEventServiceTransport: + """Returns the transport used by the client instance. + + Returns: + UserEventServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(UserEventServiceClient).get_transport_class, type(UserEventServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, UserEventServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the user event 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 (Union[str, ~.UserEventServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = UserEventServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def write_user_event(self, + request: Optional[Union[user_event_service.WriteUserEventRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> user_event.UserEvent: + r"""Writes a single user event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_write_user_event(): + # Create a client + client = discoveryengine_v1beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.WriteUserEventRequest( + parent="parent_value", + ) + + # Make the request + response = await client.write_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.WriteUserEventRequest, dict]]): + The request object. Request message for WriteUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.types.UserEvent: + UserEvent captures all metadata + information Discovery Engine API needs + to know about how end users interact + with customers' website. + + """ + # Create or coerce a protobuf request object. + request = user_event_service.WriteUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.write_user_event, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def collect_user_event(self, + request: Optional[Union[user_event_service.CollectUserEventRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> httpbody_pb2.HttpBody: + r"""Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a third-party domain. + + This method is used only by the Discovery Engine API + JavaScript pixel and Google Tag Manager. Users should + not call this method directly. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_collect_user_event(): + # Create a client + client = discoveryengine_v1beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = await client.collect_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.CollectUserEventRequest, dict]]): + The request object. Request message for CollectUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It should only be used for + payload formats that can't be represented as JSON, + such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as + the response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request + fields and also want access to the raw HTTP body. + + Example: + + message GetResourceRequest { + // A unique request id. string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + # Create or coerce a protobuf request object. + request = user_event_service.CollectUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.collect_user_event, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def import_user_events(self, + request: Optional[Union[import_config.ImportUserEventsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + async def sample_import_user_events(): + # Create a client + client = discoveryengine_v1beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + inline_source = discoveryengine_v1beta.InlineSource() + inline_source.user_events.event_type = "event_type_value" + inline_source.user_events.user_pseudo_id = "user_pseudo_id_value" + + request = discoveryengine_v1beta.ImportUserEventsRequest( + inline_source=inline_source, + parent="parent_value", + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1beta.types.ImportUserEventsRequest, dict]]): + The request object. Request message for the + ImportUserEvents request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1beta.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is + returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + request = import_config.ImportUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_user_events, + default_retry=retries.Retry( +initial=1.0,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + import_config.ImportUserEventsResponse, + metadata_type=import_config.ImportUserEventsMetadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "UserEventServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "UserEventServiceAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/client.py new file mode 100644 index 000000000000..298dd873dc24 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/client.py @@ -0,0 +1,857 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.discoveryengine_v1beta.types import common +from google.cloud.discoveryengine_v1beta.types import import_config +from google.cloud.discoveryengine_v1beta.types import user_event +from google.cloud.discoveryengine_v1beta.types import user_event_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import UserEventServiceGrpcTransport +from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport +from .transports.rest import UserEventServiceRestTransport + + +class UserEventServiceClientMeta(type): + """Metaclass for the UserEventService 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[UserEventServiceTransport]] + _transport_registry["grpc"] = UserEventServiceGrpcTransport + _transport_registry["grpc_asyncio"] = UserEventServiceGrpcAsyncIOTransport + _transport_registry["rest"] = UserEventServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[UserEventServiceTransport]: + """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 UserEventServiceClient(metaclass=UserEventServiceClientMeta): + """Service for ingesting end user actions on a website to + Discovery Engine API. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + UserEventServiceClient: 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: + UserEventServiceClient: 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) -> UserEventServiceTransport: + """Returns the transport used by the client instance. + + Returns: + UserEventServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def data_store_path(project: str,location: str,data_store: str,) -> str: + """Returns a fully-qualified data_store string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) + + @staticmethod + def parse_data_store_path(path: str) -> Dict[str,str]: + """Parses a data_store path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def document_path(project: str,location: str,data_store: str,branch: str,document: str,) -> str: + """Returns a fully-qualified document string.""" + return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) + + @staticmethod + def parse_document_path(path: str) -> Dict[str,str]: + """Parses a document path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)/documents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, UserEventServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the user event 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 (Union[str, UserEventServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, UserEventServiceTransport): + # transport is a UserEventServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def write_user_event(self, + request: Optional[Union[user_event_service.WriteUserEventRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> user_event.UserEvent: + r"""Writes a single user event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_write_user_event(): + # Create a client + client = discoveryengine_v1beta.UserEventServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.WriteUserEventRequest( + parent="parent_value", + ) + + # Make the request + response = client.write_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.WriteUserEventRequest, dict]): + The request object. Request message for WriteUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.discoveryengine_v1beta.types.UserEvent: + UserEvent captures all metadata + information Discovery Engine API needs + to know about how end users interact + with customers' website. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.WriteUserEventRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, user_event_service.WriteUserEventRequest): + request = user_event_service.WriteUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.write_user_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def collect_user_event(self, + request: Optional[Union[user_event_service.CollectUserEventRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> httpbody_pb2.HttpBody: + r"""Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a third-party domain. + + This method is used only by the Discovery Engine API + JavaScript pixel and Google Tag Manager. Users should + not call this method directly. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_collect_user_event(): + # Create a client + client = discoveryengine_v1beta.UserEventServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = client.collect_user_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.CollectUserEventRequest, dict]): + The request object. Request message for CollectUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It should only be used for + payload formats that can't be represented as JSON, + such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as + the response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request + fields and also want access to the raw HTTP body. + + Example: + + message GetResourceRequest { + // A unique request id. string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a user_event_service.CollectUserEventRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, user_event_service.CollectUserEventRequest): + request = user_event_service.CollectUserEventRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.collect_user_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def import_user_events(self, + request: Optional[Union[import_config.ImportUserEventsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import discoveryengine_v1beta + + def sample_import_user_events(): + # Create a client + client = discoveryengine_v1beta.UserEventServiceClient() + + # Initialize request argument(s) + inline_source = discoveryengine_v1beta.InlineSource() + inline_source.user_events.event_type = "event_type_value" + inline_source.user_events.user_pseudo_id = "user_pseudo_id_value" + + request = discoveryengine_v1beta.ImportUserEventsRequest( + inline_source=inline_source, + parent="parent_value", + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1beta.types.ImportUserEventsRequest, dict]): + The request object. Request message for the + ImportUserEvents request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.discoveryengine_v1beta.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is + returned by the + google.longrunning.Operations.response field if the + operation was successful. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a import_config.ImportUserEventsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, import_config.ImportUserEventsRequest): + request = import_config.ImportUserEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_user_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + import_config.ImportUserEventsResponse, + metadata_type=import_config.ImportUserEventsMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "UserEventServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "UserEventServiceClient", +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/__init__.py new file mode 100644 index 000000000000..bea95d5a9d94 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import UserEventServiceTransport +from .grpc import UserEventServiceGrpcTransport +from .grpc_asyncio import UserEventServiceGrpcAsyncIOTransport +from .rest import UserEventServiceRestTransport +from .rest import UserEventServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] +_transport_registry['grpc'] = UserEventServiceGrpcTransport +_transport_registry['grpc_asyncio'] = UserEventServiceGrpcAsyncIOTransport +_transport_registry['rest'] = UserEventServiceRestTransport + +__all__ = ( + 'UserEventServiceTransport', + 'UserEventServiceGrpcTransport', + 'UserEventServiceGrpcAsyncIOTransport', + 'UserEventServiceRestTransport', + 'UserEventServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/base.py new file mode 100644 index 000000000000..98e38316fc61 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/base.py @@ -0,0 +1,211 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.discoveryengine_v1beta import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.discoveryengine_v1beta.types import import_config +from google.cloud.discoveryengine_v1beta.types import user_event +from google.cloud.discoveryengine_v1beta.types import user_event_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class UserEventServiceTransport(abc.ABC): + """Abstract transport class for UserEventService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'discoveryengine.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.write_user_event: gapic_v1.method.wrap_method( + self.write_user_event, + default_timeout=None, + client_info=client_info, + ), + self.collect_user_event: gapic_v1.method.wrap_method( + self.collect_user_event, + default_timeout=None, + client_info=client_info, + ), + self.import_user_events: gapic_v1.method.wrap_method( + self.import_user_events, + default_retry=retries.Retry( +initial=1.0,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + Union[ + user_event.UserEvent, + Awaitable[user_event.UserEvent] + ]]: + raise NotImplementedError() + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + Union[ + httpbody_pb2.HttpBody, + Awaitable[httpbody_pb2.HttpBody] + ]]: + raise NotImplementedError() + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'UserEventServiceTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/grpc.py new file mode 100644 index 000000000000..92ec5065ce00 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/grpc.py @@ -0,0 +1,389 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.discoveryengine_v1beta.types import import_config +from google.cloud.discoveryengine_v1beta.types import user_event +from google.cloud.discoveryengine_v1beta.types import user_event_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO + + +class UserEventServiceGrpcTransport(UserEventServiceTransport): + """gRPC backend transport for UserEventService. + + Service for ingesting end user actions on a website to + Discovery Engine 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 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + user_event.UserEvent]: + r"""Return a callable for the write user event method over gRPC. + + Writes a single user event. + + Returns: + Callable[[~.WriteUserEventRequest], + ~.UserEvent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'write_user_event' not in self._stubs: + self._stubs['write_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.UserEventService/WriteUserEvent', + request_serializer=user_event_service.WriteUserEventRequest.serialize, + response_deserializer=user_event.UserEvent.deserialize, + ) + return self._stubs['write_user_event'] + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + httpbody_pb2.HttpBody]: + r"""Return a callable for the collect user event method over gRPC. + + Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a third-party domain. + + This method is used only by the Discovery Engine API + JavaScript pixel and Google Tag Manager. Users should + not call this method directly. + + Returns: + Callable[[~.CollectUserEventRequest], + ~.HttpBody]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'collect_user_event' not in self._stubs: + self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.UserEventService/CollectUserEvent', + request_serializer=user_event_service.CollectUserEventRequest.serialize, + response_deserializer=httpbody_pb2.HttpBody.FromString, + ) + return self._stubs['collect_user_event'] + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + operations_pb2.Operation]: + r"""Return a callable for the import user events method over gRPC. + + Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + Returns: + Callable[[~.ImportUserEventsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_user_events' not in self._stubs: + self._stubs['import_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.UserEventService/ImportUserEvents', + request_serializer=import_config.ImportUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_user_events'] + + def close(self): + self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'UserEventServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..d3d622275528 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/grpc_asyncio.py @@ -0,0 +1,388 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.discoveryengine_v1beta.types import import_config +from google.cloud.discoveryengine_v1beta.types import user_event +from google.cloud.discoveryengine_v1beta.types import user_event_service +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import UserEventServiceGrpcTransport + + +class UserEventServiceGrpcAsyncIOTransport(UserEventServiceTransport): + """gRPC AsyncIO backend transport for UserEventService. + + Service for ingesting end user actions on a website to + Discovery Engine 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 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 = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'discoveryengine.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + Awaitable[user_event.UserEvent]]: + r"""Return a callable for the write user event method over gRPC. + + Writes a single user event. + + Returns: + Callable[[~.WriteUserEventRequest], + Awaitable[~.UserEvent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'write_user_event' not in self._stubs: + self._stubs['write_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.UserEventService/WriteUserEvent', + request_serializer=user_event_service.WriteUserEventRequest.serialize, + response_deserializer=user_event.UserEvent.deserialize, + ) + return self._stubs['write_user_event'] + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + Awaitable[httpbody_pb2.HttpBody]]: + r"""Return a callable for the collect user event method over gRPC. + + Writes a single user event from the browser. This + uses a GET request to due to browser restriction of + POST-ing to a third-party domain. + + This method is used only by the Discovery Engine API + JavaScript pixel and Google Tag Manager. Users should + not call this method directly. + + Returns: + Callable[[~.CollectUserEventRequest], + Awaitable[~.HttpBody]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'collect_user_event' not in self._stubs: + self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.UserEventService/CollectUserEvent', + request_serializer=user_event_service.CollectUserEventRequest.serialize, + response_deserializer=httpbody_pb2.HttpBody.FromString, + ) + return self._stubs['collect_user_event'] + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the import user events method over gRPC. + + Bulk import of User events. Request processing might + be synchronous. Events that already exist are skipped. + Use this method for backfilling historical user events. + + Operation.response is of type ImportResponse. Note that + it is possible for a subset of the items to be + successfully inserted. Operation.metadata is of type + ImportMetadata. + + Returns: + Callable[[~.ImportUserEventsRequest], + 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 'import_user_events' not in self._stubs: + self._stubs['import_user_events'] = self.grpc_channel.unary_unary( + '/google.cloud.discoveryengine.v1beta.UserEventService/ImportUserEvents', + request_serializer=import_config.ImportUserEventsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['import_user_events'] + + def close(self): + return self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: + r"""Return a callable for the list_operations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ( + 'UserEventServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/rest.py new file mode 100644 index 000000000000..4f42389166b8 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/rest.py @@ -0,0 +1,1005 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.cloud.location import locations_pb2 # type: ignore +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.discoveryengine_v1beta.types import import_config +from google.cloud.discoveryengine_v1beta.types import user_event +from google.cloud.discoveryengine_v1beta.types import user_event_service +from google.longrunning import operations_pb2 # type: ignore + +from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class UserEventServiceRestInterceptor: + """Interceptor for UserEventService. + + 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 UserEventServiceRestTransport. + + .. code-block:: python + class MyCustomUserEventServiceInterceptor(UserEventServiceRestInterceptor): + def pre_collect_user_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_collect_user_event(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_import_user_events(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_import_user_events(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_write_user_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_write_user_event(self, response): + logging.log(f"Received response: {response}") + return response + + transport = UserEventServiceRestTransport(interceptor=MyCustomUserEventServiceInterceptor()) + client = UserEventServiceClient(transport=transport) + + + """ + def pre_collect_user_event(self, request: user_event_service.CollectUserEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[user_event_service.CollectUserEventRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for collect_user_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserEventService server. + """ + return request, metadata + + def post_collect_user_event(self, response: httpbody_pb2.HttpBody) -> httpbody_pb2.HttpBody: + """Post-rpc interceptor for collect_user_event + + Override in a subclass to manipulate the response + after it is returned by the UserEventService server but before + it is returned to user code. + """ + return response + def pre_import_user_events(self, request: import_config.ImportUserEventsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[import_config.ImportUserEventsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for import_user_events + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserEventService server. + """ + return request, metadata + + def post_import_user_events(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for import_user_events + + Override in a subclass to manipulate the response + after it is returned by the UserEventService server but before + it is returned to user code. + """ + return response + def pre_write_user_event(self, request: user_event_service.WriteUserEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[user_event_service.WriteUserEventRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for write_user_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserEventService server. + """ + return request, metadata + + def post_write_user_event(self, response: user_event.UserEvent) -> user_event.UserEvent: + """Post-rpc interceptor for write_user_event + + Override in a subclass to manipulate the response + after it is returned by the UserEventService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserEventService 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 UserEventService server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the UserEventService 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 UserEventService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class UserEventServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: UserEventServiceRestInterceptor + + +class UserEventServiceRestTransport(UserEventServiceTransport): + """REST backend transport for UserEventService. + + Service for ingesting end user actions on a website to + Discovery Engine 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 = 'discoveryengine.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[UserEventServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or UserEventServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*}/operations', + }, + { + 'method': 'get', + 'uri': '/v1beta/{name=projects/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1beta") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CollectUserEvent(UserEventServiceRestStub): + def __hash__(self): + return hash("CollectUserEvent") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "userEvent" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: user_event_service.CollectUserEventRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> httpbody_pb2.HttpBody: + r"""Call the collect user event method over HTTP. + + Args: + request (~.user_event_service.CollectUserEventRequest): + The request object. Request message for CollectUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It + should only be used for payload formats that can't be + represented as JSON, such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as the + response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request fields + and also want access to the raw HTTP body. + + Example: + + :: + + message GetResourceRequest { + // A unique request id. + string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + :: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=projects/*/locations/*/dataStores/*}/userEvents:collect', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{parent=projects/*/locations/*/collections/*/dataStores/*}/userEvents:collect', + }, + ] + request, metadata = self._interceptor.pre_collect_user_event(request, metadata) + pb_request = user_event_service.CollectUserEventRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = httpbody_pb2.HttpBody() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_collect_user_event(resp) + return resp + + class _ImportUserEvents(UserEventServiceRestStub): + def __hash__(self): + return hash("ImportUserEvents") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: import_config.ImportUserEventsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the import user events method over HTTP. + + Args: + request (~.import_config.ImportUserEventsRequest): + The request object. Request message for the + ImportUserEvents request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{parent=projects/*/locations/*/dataStores/*}/userEvents:import', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1beta/{parent=projects/*/locations/*/collections/*/dataStores/*}/userEvents:import', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_import_user_events(request, metadata) + pb_request = import_config.ImportUserEventsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_import_user_events(resp) + return resp + + class _WriteUserEvent(UserEventServiceRestStub): + def __hash__(self): + return hash("WriteUserEvent") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: user_event_service.WriteUserEventRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> user_event.UserEvent: + r"""Call the write user event method over HTTP. + + Args: + request (~.user_event_service.WriteUserEventRequest): + The request object. Request message for WriteUserEvent + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.user_event.UserEvent: + UserEvent captures all metadata + information Discovery Engine API needs + to know about how end users interact + with customers' website. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{parent=projects/*/locations/*/dataStores/*}/userEvents:write', + 'body': 'user_event', + }, +{ + 'method': 'post', + 'uri': '/v1beta/{parent=projects/*/locations/*/collections/*/dataStores/*}/userEvents:write', + 'body': 'user_event', + }, + ] + request, metadata = self._interceptor.pre_write_user_event(request, metadata) + pb_request = user_event_service.WriteUserEventRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = user_event.UserEvent() + pb_resp = user_event.UserEvent.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_write_user_event(resp) + return resp + + @property + def collect_user_event(self) -> Callable[ + [user_event_service.CollectUserEventRequest], + httpbody_pb2.HttpBody]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CollectUserEvent(self._session, self._host, self._interceptor) # type: ignore + + @property + def import_user_events(self) -> Callable[ + [import_config.ImportUserEventsRequest], + 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._ImportUserEvents(self._session, self._host, self._interceptor) # type: ignore + + @property + def write_user_event(self) -> Callable[ + [user_event_service.WriteUserEventRequest], + user_event.UserEvent]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._WriteUserEvent(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(UserEventServiceRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(UserEventServiceRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/collections/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*/locations/*}/operations', + }, +{ + 'method': 'get', + 'uri': '/v1beta/{name=projects/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'UserEventServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/__init__.py new file mode 100644 index 000000000000..8b5d1aef0fda --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/__init__.py @@ -0,0 +1,170 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .common import ( + CustomAttribute, + DoubleList, + Interval, + UserInfo, +) +from .completion_service import ( + CompleteQueryRequest, + CompleteQueryResponse, +) +from .conversation import ( + Conversation, + ConversationContext, + ConversationMessage, + Reply, + TextInput, +) +from .conversational_search_service import ( + ConverseConversationRequest, + ConverseConversationResponse, + CreateConversationRequest, + DeleteConversationRequest, + GetConversationRequest, + ListConversationsRequest, + ListConversationsResponse, + UpdateConversationRequest, +) +from .document import ( + Document, +) +from .document_service import ( + CreateDocumentRequest, + DeleteDocumentRequest, + GetDocumentRequest, + ListDocumentsRequest, + ListDocumentsResponse, + UpdateDocumentRequest, +) +from .import_config import ( + BigQuerySource, + GcsSource, + ImportDocumentsMetadata, + ImportDocumentsRequest, + ImportDocumentsResponse, + ImportErrorConfig, + ImportUserEventsMetadata, + ImportUserEventsRequest, + ImportUserEventsResponse, +) +from .purge_config import ( + PurgeDocumentsMetadata, + PurgeDocumentsRequest, + PurgeDocumentsResponse, +) +from .recommendation_service import ( + RecommendRequest, + RecommendResponse, +) +from .schema import ( + Schema, +) +from .schema_service import ( + CreateSchemaMetadata, + CreateSchemaRequest, + DeleteSchemaMetadata, + DeleteSchemaRequest, + GetSchemaRequest, + ListSchemasRequest, + ListSchemasResponse, + UpdateSchemaMetadata, + UpdateSchemaRequest, +) +from .search_service import ( + SearchRequest, + SearchResponse, +) +from .user_event import ( + CompletionInfo, + DocumentInfo, + MediaInfo, + PageInfo, + PanelInfo, + SearchInfo, + TransactionInfo, + UserEvent, +) +from .user_event_service import ( + CollectUserEventRequest, + WriteUserEventRequest, +) + +__all__ = ( + 'CustomAttribute', + 'DoubleList', + 'Interval', + 'UserInfo', + 'CompleteQueryRequest', + 'CompleteQueryResponse', + 'Conversation', + 'ConversationContext', + 'ConversationMessage', + 'Reply', + 'TextInput', + 'ConverseConversationRequest', + 'ConverseConversationResponse', + 'CreateConversationRequest', + 'DeleteConversationRequest', + 'GetConversationRequest', + 'ListConversationsRequest', + 'ListConversationsResponse', + 'UpdateConversationRequest', + 'Document', + 'CreateDocumentRequest', + 'DeleteDocumentRequest', + 'GetDocumentRequest', + 'ListDocumentsRequest', + 'ListDocumentsResponse', + 'UpdateDocumentRequest', + 'BigQuerySource', + 'GcsSource', + 'ImportDocumentsMetadata', + 'ImportDocumentsRequest', + 'ImportDocumentsResponse', + 'ImportErrorConfig', + 'ImportUserEventsMetadata', + 'ImportUserEventsRequest', + 'ImportUserEventsResponse', + 'PurgeDocumentsMetadata', + 'PurgeDocumentsRequest', + 'PurgeDocumentsResponse', + 'RecommendRequest', + 'RecommendResponse', + 'Schema', + 'CreateSchemaMetadata', + 'CreateSchemaRequest', + 'DeleteSchemaMetadata', + 'DeleteSchemaRequest', + 'GetSchemaRequest', + 'ListSchemasRequest', + 'ListSchemasResponse', + 'UpdateSchemaMetadata', + 'UpdateSchemaRequest', + 'SearchRequest', + 'SearchResponse', + 'CompletionInfo', + 'DocumentInfo', + 'MediaInfo', + 'PageInfo', + 'PanelInfo', + 'SearchInfo', + 'TransactionInfo', + 'UserEvent', + 'CollectUserEventRequest', + 'WriteUserEventRequest', +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/common.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/common.py new file mode 100644 index 000000000000..a677438ff182 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/common.py @@ -0,0 +1,182 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.discoveryengine.v1beta', + manifest={ + 'Interval', + 'CustomAttribute', + 'UserInfo', + 'DoubleList', + }, +) + + +class Interval(proto.Message): + r"""A floating point interval. + + 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: + minimum (float): + Inclusive lower bound. + + This field is a member of `oneof`_ ``min``. + exclusive_minimum (float): + Exclusive lower bound. + + This field is a member of `oneof`_ ``min``. + maximum (float): + Inclusive upper bound. + + This field is a member of `oneof`_ ``max``. + exclusive_maximum (float): + Exclusive upper bound. + + This field is a member of `oneof`_ ``max``. + """ + + minimum: float = proto.Field( + proto.DOUBLE, + number=1, + oneof='min', + ) + exclusive_minimum: float = proto.Field( + proto.DOUBLE, + number=2, + oneof='min', + ) + maximum: float = proto.Field( + proto.DOUBLE, + number=3, + oneof='max', + ) + exclusive_maximum: float = proto.Field( + proto.DOUBLE, + number=4, + oneof='max', + ) + + +class CustomAttribute(proto.Message): + r"""A custom attribute that is not explicitly modeled in a resource, + e.g. [UserEvent][google.cloud.discoveryengine.v1beta.UserEvent]. + + Attributes: + text (MutableSequence[str]): + The textual values of this custom attribute. For example, + ``["yellow", "green"]`` when the key is "color". + + Empty string is not allowed. Otherwise, an + ``INVALID_ARGUMENT`` error is returned. + + Exactly one of + [CustomAttribute.text][google.cloud.discoveryengine.v1beta.CustomAttribute.text] + or + [CustomAttribute.numbers][google.cloud.discoveryengine.v1beta.CustomAttribute.numbers] + should be set. Otherwise, an ``INVALID_ARGUMENT`` error is + returned. + numbers (MutableSequence[float]): + The numerical values of this custom attribute. For example, + ``[2.3, 15.4]`` when the key is "lengths_cm". + + Exactly one of + [CustomAttribute.text][google.cloud.discoveryengine.v1beta.CustomAttribute.text] + or + [CustomAttribute.numbers][google.cloud.discoveryengine.v1beta.CustomAttribute.numbers] + should be set. Otherwise, an ``INVALID_ARGUMENT`` error is + returned. + """ + + text: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + numbers: MutableSequence[float] = proto.RepeatedField( + proto.DOUBLE, + number=2, + ) + + +class UserInfo(proto.Message): + r"""Information of an end user. + + Attributes: + user_id (str): + Highly recommended for logged-in users. Unique identifier + for logged-in user, such as a user name. Don't set for + anonymous users. + + Always use a hashed value for this ID. + + Don't set the field to the same fixed ID for different + users. This mixes the event history of those users together, + which results in degraded model quality. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an ``INVALID_ARGUMENT`` error + is returned. + user_agent (str): + User agent as included in the HTTP header. + + The field must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an ``INVALID_ARGUMENT`` + error is returned. + + This should not be set when using the client side event + reporting with GTM or JavaScript tag in + [UserEventService.CollectUserEvent][google.cloud.discoveryengine.v1beta.UserEventService.CollectUserEvent] + or if + [UserEvent.direct_user_request][google.cloud.discoveryengine.v1beta.UserEvent.direct_user_request] + is set. + """ + + user_id: str = proto.Field( + proto.STRING, + number=1, + ) + user_agent: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DoubleList(proto.Message): + r"""Double list. + + Attributes: + values (MutableSequence[float]): + Double values. + """ + + values: MutableSequence[float] = proto.RepeatedField( + proto.DOUBLE, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/completion_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/completion_service.py new file mode 100644 index 000000000000..78d40101d69b --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/completion_service.py @@ -0,0 +1,158 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.discoveryengine.v1beta', + manifest={ + 'CompleteQueryRequest', + 'CompleteQueryResponse', + }, +) + + +class CompleteQueryRequest(proto.Message): + r"""Request message for + [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1beta.CompletionService.CompleteQuery] + method. + + Attributes: + data_store (str): + Required. The parent data store resource name for which the + completion is performed, such as + ``projects/*/locations/global/collections/default_collection/dataStores/default_data_store``. + query (str): + Required. The typeahead input used to fetch + suggestions. Maximum length is 128 characters. + query_model (str): + Selects data model of query suggestions for serving. + Currently supported values: + + - ``document`` - Using suggestions generated from + user-imported documents. + - ``search-history`` - Using suggestions generated from the + past history of + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + API calls. Do not use it when there is no traffic for + Search API. + - ``user-event`` - Using suggestions generated from + user-imported search events. + - ``document-completable`` - Using suggestions taken + directly from user-imported document fields marked as + completable. + + Default values: + + - ``document`` is the default model for regular dataStores. + - ``search-history`` is the default model for + [IndustryVertical.SITE_SEARCH][] dataStores. + user_pseudo_id (str): + A unique identifier for tracking visitors. For example, this + could be implemented with an HTTP cookie, which should be + able to uniquely identify a visitor on a single device. This + unique identifier should not change if the visitor logs in + or out of the website. + + This field should NOT have a fixed value such as + ``unknown_visitor``. + + This should be the same identifier as + [UserEvent.user_pseudo_id][google.cloud.discoveryengine.v1beta.UserEvent.user_pseudo_id] + and + [SearchRequest.user_pseudo_id][google.cloud.discoveryengine.v1beta.SearchRequest.user_pseudo_id]. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an ``INVALID_ARGUMENT`` error + is returned. + include_tail_suggestions (bool): + Indicates if tail suggestions should be + returned if there are no suggestions that match + the full query. Even if set to true, if there + are suggestions that match the full query, those + are returned and no tail suggestions are + returned. + """ + + data_store: str = proto.Field( + proto.STRING, + number=1, + ) + query: str = proto.Field( + proto.STRING, + number=2, + ) + query_model: str = proto.Field( + proto.STRING, + number=3, + ) + user_pseudo_id: str = proto.Field( + proto.STRING, + number=4, + ) + include_tail_suggestions: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class CompleteQueryResponse(proto.Message): + r"""Response message for + [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1beta.CompletionService.CompleteQuery] + method. + + Attributes: + query_suggestions (MutableSequence[google.cloud.discoveryengine_v1beta.types.CompleteQueryResponse.QuerySuggestion]): + Results of the matched query suggestions. The + result list is ordered and the first result is a + top suggestion. + tail_match_triggered (bool): + True if the returned suggestions are all tail suggestions. + + For tail matching to be triggered, include_tail_suggestions + in the request must be true and there must be no suggestions + that match the full query. + """ + + class QuerySuggestion(proto.Message): + r"""Suggestions as search queries. + + Attributes: + suggestion (str): + The suggestion for the query. + """ + + suggestion: str = proto.Field( + proto.STRING, + number=1, + ) + + query_suggestions: MutableSequence[QuerySuggestion] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=QuerySuggestion, + ) + tail_match_triggered: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/conversation.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/conversation.py new file mode 100644 index 000000000000..d82afb7df677 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/conversation.py @@ -0,0 +1,248 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import search_service +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1beta', + manifest={ + 'Conversation', + 'Reply', + 'ConversationContext', + 'TextInput', + 'ConversationMessage', + }, +) + + +class Conversation(proto.Message): + r"""External conversation proto definition. + + Attributes: + name (str): + Immutable. Fully qualified name + ``project/*/locations/global/collections/{collection}/dataStore/*/conversations/*`` + state (google.cloud.discoveryengine_v1beta.types.Conversation.State): + The state of the Conversation. + user_pseudo_id (str): + A unique identifier for tracking users. + messages (MutableSequence[google.cloud.discoveryengine_v1beta.types.ConversationMessage]): + Conversation messages. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the conversation + started. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the conversation + finished. + """ + class State(proto.Enum): + r"""Enumeration of the state of the conversation. + + Values: + STATE_UNSPECIFIED (0): + Unknown. + IN_PROGRESS (1): + Conversation is currently open. + COMPLETED (2): + Conversation has been completed. + """ + STATE_UNSPECIFIED = 0 + IN_PROGRESS = 1 + COMPLETED = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + state: State = proto.Field( + proto.ENUM, + number=2, + enum=State, + ) + user_pseudo_id: str = proto.Field( + proto.STRING, + number=3, + ) + messages: MutableSequence['ConversationMessage'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='ConversationMessage', + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + + +class Reply(proto.Message): + r"""Defines a reply message to user. + + Attributes: + reply (str): + DEPRECATED: use ``summary`` instead. Text reply. + references (MutableSequence[google.cloud.discoveryengine_v1beta.types.Reply.Reference]): + References in the reply. + summary (google.cloud.discoveryengine_v1beta.types.SearchResponse.Summary): + Summary based on search results. + """ + + class Reference(proto.Message): + r"""Defines reference in reply. + + Attributes: + uri (str): + URI link reference. + anchor_text (str): + Anchor text. + start (int): + Anchor text start index. + end (int): + Anchor text end index. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + anchor_text: str = proto.Field( + proto.STRING, + number=2, + ) + start: int = proto.Field( + proto.INT32, + number=3, + ) + end: int = proto.Field( + proto.INT32, + number=4, + ) + + reply: str = proto.Field( + proto.STRING, + number=1, + ) + references: MutableSequence[Reference] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Reference, + ) + summary: search_service.SearchResponse.Summary = proto.Field( + proto.MESSAGE, + number=3, + message=search_service.SearchResponse.Summary, + ) + + +class ConversationContext(proto.Message): + r"""Defines context of the conversation + + Attributes: + context_documents (MutableSequence[str]): + The current list of documents the user is + seeing. It contains the document resource + references. + active_document (str): + The current active document the user opened. + It contains the document resource reference. + """ + + context_documents: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + active_document: str = proto.Field( + proto.STRING, + number=2, + ) + + +class TextInput(proto.Message): + r"""Defines text input. + + Attributes: + input (str): + Text input. + context (google.cloud.discoveryengine_v1beta.types.ConversationContext): + Conversation context of the input. + """ + + input: str = proto.Field( + proto.STRING, + number=1, + ) + context: 'ConversationContext' = proto.Field( + proto.MESSAGE, + number=2, + message='ConversationContext', + ) + + +class ConversationMessage(proto.Message): + r"""Defines a conversation 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: + user_input (google.cloud.discoveryengine_v1beta.types.TextInput): + User text input. + + This field is a member of `oneof`_ ``message``. + reply (google.cloud.discoveryengine_v1beta.types.Reply): + Search reply. + + This field is a member of `oneof`_ ``message``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Message creation timestamp. + """ + + user_input: 'TextInput' = proto.Field( + proto.MESSAGE, + number=1, + oneof='message', + message='TextInput', + ) + reply: 'Reply' = proto.Field( + proto.MESSAGE, + number=2, + oneof='message', + message='Reply', + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/conversational_search_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/conversational_search_service.py new file mode 100644 index 000000000000..8cd4858004e9 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/conversational_search_service.py @@ -0,0 +1,328 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import conversation as gcd_conversation +from google.cloud.discoveryengine_v1beta.types import search_service +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1beta', + manifest={ + 'ConverseConversationRequest', + 'ConverseConversationResponse', + 'CreateConversationRequest', + 'UpdateConversationRequest', + 'DeleteConversationRequest', + 'GetConversationRequest', + 'ListConversationsRequest', + 'ListConversationsResponse', + }, +) + + +class ConverseConversationRequest(proto.Message): + r"""Request message for + [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1beta.ConversationalSearchService.ConverseConversation] + method. + + Attributes: + name (str): + Required. The resource name of the Conversation to get. + Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}``. + Use + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/-`` + to activate auto session mode, which automatically creates a + new conversation inside a ConverseConversation session. + query (google.cloud.discoveryengine_v1beta.types.TextInput): + Required. Current user input. + serving_config (str): + The resource name of the Serving Config to use. Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/servingConfigs/{serving_config_id}`` + If this is not set, the default serving config will be used. + conversation (google.cloud.discoveryengine_v1beta.types.Conversation): + The conversation to be used by auto session + only. The name field will be ignored as we + automatically assign new name for the + conversation in auto session. + safe_search (bool): + Whether to turn on safe search. + user_labels (MutableMapping[str, str]): + The user labels applied to a resource must meet the + following requirements: + + - Each resource can have multiple labels, up to a maximum + of 64. + - Each label must be a key-value pair. + - Keys have a minimum length of 1 character and a maximum + length of 63 characters and cannot be empty. Values can + be empty and have a maximum length of 63 characters. + - Keys and values can contain only lowercase letters, + numeric characters, underscores, and dashes. All + characters must use UTF-8 encoding, and international + characters are allowed. + - The key portion of a label must be unique. However, you + can use the same key with multiple resources. + - Keys must start with a lowercase letter or international + character. + + See `Google Cloud + Document `__ + for more details. + summary_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.ContentSearchSpec.SummarySpec): + A specification for configuring the summary + returned in the response. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + query: gcd_conversation.TextInput = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_conversation.TextInput, + ) + serving_config: str = proto.Field( + proto.STRING, + number=3, + ) + conversation: gcd_conversation.Conversation = proto.Field( + proto.MESSAGE, + number=5, + message=gcd_conversation.Conversation, + ) + safe_search: bool = proto.Field( + proto.BOOL, + number=6, + ) + user_labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + summary_spec: search_service.SearchRequest.ContentSearchSpec.SummarySpec = proto.Field( + proto.MESSAGE, + number=8, + message=search_service.SearchRequest.ContentSearchSpec.SummarySpec, + ) + + +class ConverseConversationResponse(proto.Message): + r"""Response message for + [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1beta.ConversationalSearchService.ConverseConversation] + method. + + Attributes: + reply (google.cloud.discoveryengine_v1beta.types.Reply): + Answer to the current query. + conversation (google.cloud.discoveryengine_v1beta.types.Conversation): + Updated conversation including the answer. + related_questions (MutableSequence[str]): + Suggested related questions. + search_results (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchResponse.SearchResult]): + Search Results. + """ + + reply: gcd_conversation.Reply = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_conversation.Reply, + ) + conversation: gcd_conversation.Conversation = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_conversation.Conversation, + ) + related_questions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + search_results: MutableSequence[search_service.SearchResponse.SearchResult] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=search_service.SearchResponse.SearchResult, + ) + + +class CreateConversationRequest(proto.Message): + r"""Request for CreateConversation method. + + Attributes: + parent (str): + Required. Full resource name of parent data store. Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` + conversation (google.cloud.discoveryengine_v1beta.types.Conversation): + Required. The conversation to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + conversation: gcd_conversation.Conversation = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_conversation.Conversation, + ) + + +class UpdateConversationRequest(proto.Message): + r"""Request for UpdateConversation method. + + Attributes: + conversation (google.cloud.discoveryengine_v1beta.types.Conversation): + Required. The Conversation to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Indicates which fields in the provided + [Conversation][google.cloud.discoveryengine.v1beta.Conversation] + to update. The following are NOT supported: + + - [conversation.name][] + + If not set or empty, all supported fields are updated. + """ + + conversation: gcd_conversation.Conversation = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_conversation.Conversation, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteConversationRequest(proto.Message): + r"""Request for DeleteConversation method. + + Attributes: + name (str): + Required. The resource name of the Conversation to delete. + Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetConversationRequest(proto.Message): + r"""Request for GetConversation method. + + Attributes: + name (str): + Required. The resource name of the Conversation to get. + Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListConversationsRequest(proto.Message): + r"""Request for ListConversations method. + + Attributes: + parent (str): + Required. The data store resource name. Format: + ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` + page_size (int): + Maximum number of results to return. If + unspecified, defaults to 50. Max allowed value + is 1000. + page_token (str): + A page token, received from a previous ``ListConversations`` + call. Provide this to retrieve the subsequent page. + filter (str): + A filter to apply on the list results. The supported + features are: user_pseudo_id, state. + + Example: "user_pseudo_id = some_id". + order_by (str): + A comma-separated list of fields to order by, sorted in + ascending order. Use "desc" after a field name for + descending. Supported fields: + + - ``update_time`` + - ``create_time`` + - ``conversation_name`` + + Example: "update_time desc" "create_time". + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListConversationsResponse(proto.Message): + r"""Response for ListConversations method. + + Attributes: + conversations (MutableSequence[google.cloud.discoveryengine_v1beta.types.Conversation]): + All the Conversations for a given data store. + next_page_token (str): + Pagination token, if not returned indicates + the last page. + """ + + @property + def raw_page(self): + return self + + conversations: MutableSequence[gcd_conversation.Conversation] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_conversation.Conversation, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/document.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/document.py new file mode 100644 index 000000000000..98e34b090864 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/document.py @@ -0,0 +1,189 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1beta', + manifest={ + 'Document', + }, +) + + +class Document(proto.Message): + r"""Document captures all raw metadata information of items to be + recommended or searched. + + 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: + struct_data (google.protobuf.struct_pb2.Struct): + The structured JSON data for the document. It should conform + to the registered + [Schema][google.cloud.discoveryengine.v1beta.Schema] or an + ``INVALID_ARGUMENT`` error is thrown. + + This field is a member of `oneof`_ ``data``. + json_data (str): + The JSON string representation of the document. It should + conform to the registered + [Schema][google.cloud.discoveryengine.v1beta.Schema] or an + ``INVALID_ARGUMENT`` error is thrown. + + This field is a member of `oneof`_ ``data``. + name (str): + Immutable. The full resource name of the document. Format: + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document_id}``. + + This field must be a UTF-8 encoded string with a length + limit of 1024 characters. + id (str): + Immutable. The identifier of the document. + + Id should conform to + `RFC-1034 `__ standard + with a length limit of 63 characters. + schema_id (str): + The identifier of the schema located in the + same data store. + content (google.cloud.discoveryengine_v1beta.types.Document.Content): + The unstructured data linked to this document. Content must + be set if this document is under a ``CONTENT_REQUIRED`` data + store. + parent_document_id (str): + The identifier of the parent document. Currently supports at + most two level document hierarchy. + + Id should conform to + `RFC-1034 `__ standard + with a length limit of 63 characters. + derived_struct_data (google.protobuf.struct_pb2.Struct): + Output only. This field is OUTPUT_ONLY. It contains derived + data that are not in the original input document. + """ + + class Content(proto.Message): + r"""Unstructured data linked to this document. + + 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: + raw_bytes (bytes): + The content represented as a stream of bytes. The maximum + length is 1,000,000 bytes (1 MB / ~0.95 MiB). + + Note: As with all ``bytes`` fields, this field is + represented as pure binary in Protocol Buffers and + base64-encoded string in JSON. For example, + ``abc123!?$*&()'-=@~`` should be represented as + ``YWJjMTIzIT8kKiYoKSctPUB+`` in JSON. See + https://developers.google.com/protocol-buffers/docs/proto3#json. + + This field is a member of `oneof`_ ``content``. + uri (str): + The URI of the content. Only Cloud Storage URIs (e.g. + ``gs://bucket-name/path/to/file``) are supported. The + maximum file size is 100 MB. + + This field is a member of `oneof`_ ``content``. + mime_type (str): + The MIME type of the content. Supported types: + + - ``application/pdf`` (PDF, only native PDFs are supported + for now) + - ``text/html`` (HTML) + - ``application/vnd.openxmlformats-officedocument.wordprocessingml.document`` + (DOCX) + - ``application/vnd.openxmlformats-officedocument.presentationml.presentation`` + (PPTX) + - ``text/plain`` (TXT) + + See + https://www.iana.org/assignments/media-types/media-types.xhtml. + """ + + raw_bytes: bytes = proto.Field( + proto.BYTES, + number=2, + oneof='content', + ) + uri: str = proto.Field( + proto.STRING, + number=3, + oneof='content', + ) + mime_type: str = proto.Field( + proto.STRING, + number=1, + ) + + struct_data: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=4, + oneof='data', + message=struct_pb2.Struct, + ) + json_data: str = proto.Field( + proto.STRING, + number=5, + oneof='data', + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + id: str = proto.Field( + proto.STRING, + number=2, + ) + schema_id: str = proto.Field( + proto.STRING, + number=3, + ) + content: Content = proto.Field( + proto.MESSAGE, + number=10, + message=Content, + ) + parent_document_id: str = proto.Field( + proto.STRING, + number=7, + ) + derived_struct_data: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=6, + message=struct_pb2.Struct, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/document_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/document_service.py new file mode 100644 index 000000000000..8ff69b0d5e86 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/document_service.py @@ -0,0 +1,265 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import document as gcd_document + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1beta', + manifest={ + 'GetDocumentRequest', + 'ListDocumentsRequest', + 'ListDocumentsResponse', + 'CreateDocumentRequest', + 'UpdateDocumentRequest', + 'DeleteDocumentRequest', + }, +) + + +class GetDocumentRequest(proto.Message): + r"""Request message for + [DocumentService.GetDocument][google.cloud.discoveryengine.v1beta.DocumentService.GetDocument] + method. + + Attributes: + name (str): + Required. Full resource name of + [Document][google.cloud.discoveryengine.v1beta.Document], + such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. + + If the caller does not have permission to access the + [Document][google.cloud.discoveryengine.v1beta.Document], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the requested + [Document][google.cloud.discoveryengine.v1beta.Document] + does not exist, a ``NOT_FOUND`` error is returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListDocumentsRequest(proto.Message): + r"""Request message for + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1beta.DocumentService.ListDocuments] + method. + + Attributes: + parent (str): + Required. The parent branch resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. + Use ``default_branch`` as the branch ID, to list documents + under the default branch. + + If the caller does not have permission to list + [Document][google.cloud.discoveryengine.v1beta.Document]s + under this branch, regardless of whether or not this branch + exists, a ``PERMISSION_DENIED`` error is returned. + page_size (int): + Maximum number of + [Document][google.cloud.discoveryengine.v1beta.Document]s to + return. If unspecified, defaults to 100. The maximum allowed + value is 1000. Values above 1000 will be coerced to 1000. + + If this field is negative, an ``INVALID_ARGUMENT`` error is + returned. + page_token (str): + A page token + [ListDocumentsResponse.next_page_token][google.cloud.discoveryengine.v1beta.ListDocumentsResponse.next_page_token], + received from a previous + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1beta.DocumentService.ListDocuments] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1beta.DocumentService.ListDocuments] + must match the call that provided the page token. Otherwise, + an ``INVALID_ARGUMENT`` error is returned. + """ + + 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 ListDocumentsResponse(proto.Message): + r"""Response message for + [DocumentService.ListDocuments][google.cloud.discoveryengine.v1beta.DocumentService.ListDocuments] + method. + + Attributes: + documents (MutableSequence[google.cloud.discoveryengine_v1beta.types.Document]): + The + [Document][google.cloud.discoveryengine.v1beta.Document]s. + next_page_token (str): + A token that can be sent as + [ListDocumentsRequest.page_token][google.cloud.discoveryengine.v1beta.ListDocumentsRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + documents: MutableSequence[gcd_document.Document] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_document.Document, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateDocumentRequest(proto.Message): + r"""Request message for + [DocumentService.CreateDocument][google.cloud.discoveryengine.v1beta.DocumentService.CreateDocument] + method. + + Attributes: + parent (str): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. + document (google.cloud.discoveryengine_v1beta.types.Document): + Required. The + [Document][google.cloud.discoveryengine.v1beta.Document] to + create. + document_id (str): + Required. The ID to use for the + [Document][google.cloud.discoveryengine.v1beta.Document], + which will become the final component of the + [Document.name][google.cloud.discoveryengine.v1beta.Document.name]. + + If the caller does not have permission to create the + [Document][google.cloud.discoveryengine.v1beta.Document], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + This field must be unique among all + [Document][google.cloud.discoveryengine.v1beta.Document]s + with the same + [parent][google.cloud.discoveryengine.v1beta.CreateDocumentRequest.parent]. + Otherwise, an ``ALREADY_EXISTS`` error is returned. + + This field must conform to + `RFC-1034 `__ standard + with a length limit of 63 characters. Otherwise, an + ``INVALID_ARGUMENT`` error is returned. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + document: gcd_document.Document = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_document.Document, + ) + document_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateDocumentRequest(proto.Message): + r"""Request message for + [DocumentService.UpdateDocument][google.cloud.discoveryengine.v1beta.DocumentService.UpdateDocument] + method. + + Attributes: + document (google.cloud.discoveryengine_v1beta.types.Document): + Required. The document to update/create. + + If the caller does not have permission to update the + [Document][google.cloud.discoveryengine.v1beta.Document], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [Document][google.cloud.discoveryengine.v1beta.Document] to + update does not exist and + [allow_missing][google.cloud.discoveryengine.v1beta.UpdateDocumentRequest.allow_missing] + is not set, a ``NOT_FOUND`` error is returned. + allow_missing (bool): + If set to true, and the + [Document][google.cloud.discoveryengine.v1beta.Document] is + not found, a new + [Document][google.cloud.discoveryengine.v1beta.Document] + will be created. + """ + + document: gcd_document.Document = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_document.Document, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class DeleteDocumentRequest(proto.Message): + r"""Request message for + [DocumentService.DeleteDocument][google.cloud.discoveryengine.v1beta.DocumentService.DeleteDocument] + method. + + Attributes: + name (str): + Required. Full resource name of + [Document][google.cloud.discoveryengine.v1beta.Document], + such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. + + If the caller does not have permission to delete the + [Document][google.cloud.discoveryengine.v1beta.Document], + regardless of whether or not it exists, a + ``PERMISSION_DENIED`` error is returned. + + If the + [Document][google.cloud.discoveryengine.v1beta.Document] to + delete does not exist, a ``NOT_FOUND`` error is returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/import_config.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/import_config.py new file mode 100644 index 000000000000..5ba838cc43f8 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/import_config.py @@ -0,0 +1,607 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import document +from google.cloud.discoveryengine_v1beta.types import user_event +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import date_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1beta', + manifest={ + 'GcsSource', + 'BigQuerySource', + 'ImportErrorConfig', + 'ImportUserEventsRequest', + 'ImportUserEventsResponse', + 'ImportUserEventsMetadata', + 'ImportDocumentsMetadata', + 'ImportDocumentsRequest', + 'ImportDocumentsResponse', + }, +) + + +class GcsSource(proto.Message): + r"""Cloud Storage location for input content. + + Attributes: + input_uris (MutableSequence[str]): + Required. Cloud Storage URIs to input files. URI can be up + to 2000 characters long. URIs can match the full object path + (for example, ``gs://bucket/directory/object.json``) or a + pattern matching one or more files, such as + ``gs://bucket/directory/*.json``. + + A request can contain at most 100 files (or 100,000 files if + ``data_schema`` is ``content``). Each file can be up to 2 GB + (or 100 MB if ``data_schema`` is ``content``). + data_schema (str): + The schema to use when parsing the data from the source. + + Supported values for document imports: + + - ``document`` (default): One JSON + [Document][google.cloud.discoveryengine.v1beta.Document] + per line. Each document must have a valid + [Document.id][google.cloud.discoveryengine.v1beta.Document.id]. + - ``content``: Unstructured data (e.g. PDF, HTML). Each + file matched by ``input_uris`` becomes a document, with + the ID set to the first 128 bits of SHA256(URI) encoded + as a hex string. + - ``custom``: One custom data JSON per row in arbitrary + format that conforms to the defined + [Schema][google.cloud.discoveryengine.v1beta.Schema] of + the data store. This can only be used by Gen App Builder. + - ``csv``: A CSV file with header conforming to the defined + [Schema][google.cloud.discoveryengine.v1beta.Schema] of + the data store. Each entry after the header is imported + as a Document. This can only be used by Gen App Builder. + + Supported values for user even imports: + + - ``user_event`` (default): One JSON + [UserEvent][google.cloud.discoveryengine.v1beta.UserEvent] + per line. + """ + + input_uris: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + data_schema: str = proto.Field( + proto.STRING, + number=2, + ) + + +class BigQuerySource(proto.Message): + r"""BigQuery source import data from. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + partition_date (google.type.date_pb2.Date): + BigQuery time partitioned table's \_PARTITIONDATE in + YYYY-MM-DD format. + + This field is a member of `oneof`_ ``partition``. + project_id (str): + The project ID (can be project # or ID) that + the BigQuery source is in with a length limit of + 128 characters. If not specified, inherits the + project ID from the parent request. + dataset_id (str): + Required. The BigQuery data set to copy the + data from with a length limit of 1,024 + characters. + table_id (str): + Required. The BigQuery table to copy the data + from with a length limit of 1,024 characters. + gcs_staging_dir (str): + Intermediate Cloud Storage directory used for + the import with a length limit of 2,000 + characters. Can be specified if one wants to + have the BigQuery export to a specific Cloud + Storage directory. + data_schema (str): + The schema to use when parsing the data from the source. + + Supported values for user event imports: + + - ``user_event`` (default): One + [UserEvent][google.cloud.discoveryengine.v1beta.UserEvent] + per row. + + Supported values for document imports: + + - ``document`` (default): One + [Document][google.cloud.discoveryengine.v1beta.Document] + format per row. Each document must have a valid + [Document.id][google.cloud.discoveryengine.v1beta.Document.id] + and one of + [Document.json_data][google.cloud.discoveryengine.v1beta.Document.json_data] + or + [Document.struct_data][google.cloud.discoveryengine.v1beta.Document.struct_data]. + - ``custom``: One custom data per row in arbitrary format + that conforms to the defined + [Schema][google.cloud.discoveryengine.v1beta.Schema] of + the data store. This can only be used by Gen App Builder. + """ + + partition_date: date_pb2.Date = proto.Field( + proto.MESSAGE, + number=5, + oneof='partition', + message=date_pb2.Date, + ) + project_id: str = proto.Field( + proto.STRING, + number=1, + ) + dataset_id: str = proto.Field( + proto.STRING, + number=2, + ) + table_id: str = proto.Field( + proto.STRING, + number=3, + ) + gcs_staging_dir: str = proto.Field( + proto.STRING, + number=4, + ) + data_schema: str = proto.Field( + proto.STRING, + number=6, + ) + + +class ImportErrorConfig(proto.Message): + r"""Configuration of destination for Import related errors. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_prefix (str): + Cloud Storage prefix for import errors. This must be an + empty, existing Cloud Storage directory. Import errors are + written to sharded files in this directory, one per line, as + a JSON-encoded ``google.rpc.Status`` message. + + This field is a member of `oneof`_ ``destination``. + """ + + gcs_prefix: str = proto.Field( + proto.STRING, + number=1, + oneof='destination', + ) + + +class ImportUserEventsRequest(proto.Message): + r"""Request message for the ImportUserEvents request. + + 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: + inline_source (google.cloud.discoveryengine_v1beta.types.ImportUserEventsRequest.InlineSource): + The Inline source for the input content for + UserEvents. + + This field is a member of `oneof`_ ``source``. + gcs_source (google.cloud.discoveryengine_v1beta.types.GcsSource): + Cloud Storage location for the input content. + + This field is a member of `oneof`_ ``source``. + bigquery_source (google.cloud.discoveryengine_v1beta.types.BigQuerySource): + BigQuery input source. + + This field is a member of `oneof`_ ``source``. + parent (str): + Required. Parent DataStore resource name, of the form + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}`` + error_config (google.cloud.discoveryengine_v1beta.types.ImportErrorConfig): + The desired location of errors incurred + during the Import. Cannot be set for inline user + event imports. + """ + + class InlineSource(proto.Message): + r"""The inline source for the input config for ImportUserEvents + method. + + Attributes: + user_events (MutableSequence[google.cloud.discoveryengine_v1beta.types.UserEvent]): + Required. A list of user events to import. + Recommended max of 10k items. + """ + + user_events: MutableSequence[user_event.UserEvent] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=user_event.UserEvent, + ) + + inline_source: InlineSource = proto.Field( + proto.MESSAGE, + number=2, + oneof='source', + message=InlineSource, + ) + gcs_source: 'GcsSource' = proto.Field( + proto.MESSAGE, + number=3, + oneof='source', + message='GcsSource', + ) + bigquery_source: 'BigQuerySource' = proto.Field( + proto.MESSAGE, + number=4, + oneof='source', + message='BigQuerySource', + ) + parent: str = proto.Field( + proto.STRING, + number=1, + ) + error_config: 'ImportErrorConfig' = proto.Field( + proto.MESSAGE, + number=5, + message='ImportErrorConfig', + ) + + +class ImportUserEventsResponse(proto.Message): + r"""Response of the ImportUserEventsRequest. If the long running + operation was successful, then this message is returned by the + google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (MutableSequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + error_config (google.cloud.discoveryengine_v1beta.types.ImportErrorConfig): + Echoes the destination for the complete + errors if this field was set in the request. + joined_events_count (int): + Count of user events imported with complete + existing Documents. + unjoined_events_count (int): + Count of user events imported, but with + Document information not found in the existing + Branch. + """ + + error_samples: MutableSequence[status_pb2.Status] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + error_config: 'ImportErrorConfig' = proto.Field( + proto.MESSAGE, + number=2, + message='ImportErrorConfig', + ) + joined_events_count: int = proto.Field( + proto.INT64, + number=3, + ) + unjoined_events_count: int = proto.Field( + proto.INT64, + number=4, + ) + + +class ImportUserEventsMetadata(proto.Message): + r"""Metadata related to the progress of the Import operation. + This is returned by the google.longrunning.Operation.metadata + field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + success_count (int): + Count of entries that were processed + successfully. + failure_count (int): + Count of entries that encountered errors + while processing. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + success_count: int = proto.Field( + proto.INT64, + number=3, + ) + failure_count: int = proto.Field( + proto.INT64, + number=4, + ) + + +class ImportDocumentsMetadata(proto.Message): + r"""Metadata related to the progress of the ImportDocuments + operation. This is returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + success_count (int): + Count of entries that were processed + successfully. + failure_count (int): + Count of entries that encountered errors + while processing. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + success_count: int = proto.Field( + proto.INT64, + number=3, + ) + failure_count: int = proto.Field( + proto.INT64, + number=4, + ) + + +class ImportDocumentsRequest(proto.Message): + r"""Request message for Import methods. + + 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: + inline_source (google.cloud.discoveryengine_v1beta.types.ImportDocumentsRequest.InlineSource): + The Inline source for the input content for + documents. + + This field is a member of `oneof`_ ``source``. + gcs_source (google.cloud.discoveryengine_v1beta.types.GcsSource): + Cloud Storage location for the input content. + + This field is a member of `oneof`_ ``source``. + bigquery_source (google.cloud.discoveryengine_v1beta.types.BigQuerySource): + BigQuery input source. + + This field is a member of `oneof`_ ``source``. + parent (str): + Required. The parent branch resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. + Requires create/update permission. + error_config (google.cloud.discoveryengine_v1beta.types.ImportErrorConfig): + The desired location of errors incurred + during the Import. + reconciliation_mode (google.cloud.discoveryengine_v1beta.types.ImportDocumentsRequest.ReconciliationMode): + The mode of reconciliation between existing documents and + the documents to be imported. Defaults to + [ReconciliationMode.INCREMENTAL][google.cloud.discoveryengine.v1beta.ImportDocumentsRequest.ReconciliationMode.INCREMENTAL]. + auto_generate_ids (bool): + Whether to automatically generate IDs for the documents if + absent. + + If set to ``true``, + [Document.id][google.cloud.discoveryengine.v1beta.Document.id]s + are automatically generated based on the hash of the + payload, where IDs may not be consistent during multiple + imports. In which case + [ReconciliationMode.FULL][google.cloud.discoveryengine.v1beta.ImportDocumentsRequest.ReconciliationMode.FULL] + is highly recommended to avoid duplicate contents. If unset + or set to ``false``, + [Document.id][google.cloud.discoveryengine.v1beta.Document.id]s + have to be specified using + [id_field][google.cloud.discoveryengine.v1beta.ImportDocumentsRequest.id_field], + otherwise, documents without IDs fail to be imported. + + Only set this field when using + [GcsSource][google.cloud.discoveryengine.v1beta.GcsSource] + or + [BigQuerySource][google.cloud.discoveryengine.v1beta.BigQuerySource], + and when + [GcsSource.data_schema][google.cloud.discoveryengine.v1beta.GcsSource.data_schema] + or + [BigQuerySource.data_schema][google.cloud.discoveryengine.v1beta.BigQuerySource.data_schema] + is ``custom`` or ``csv``. Otherwise, an INVALID_ARGUMENT + error is thrown. + id_field (str): + The field in the Cloud Storage and BigQuery sources that + indicates the unique IDs of the documents. + + For + [GcsSource][google.cloud.discoveryengine.v1beta.GcsSource] + it is the key of the JSON field. For instance, ``my_id`` for + JSON ``{"my_id": "some_uuid"}``. For + [BigQuerySource][google.cloud.discoveryengine.v1beta.BigQuerySource] + it is the column name of the BigQuery table where the unique + ids are stored. + + The values of the JSON field or the BigQuery column are used + as the + [Document.id][google.cloud.discoveryengine.v1beta.Document.id]s. + The JSON field or the BigQuery column must be of string + type, and the values must be set as valid strings conform to + `RFC-1034 `__ with 1-63 + characters. Otherwise, documents without valid IDs fail to + be imported. + + Only set this field when using + [GcsSource][google.cloud.discoveryengine.v1beta.GcsSource] + or + [BigQuerySource][google.cloud.discoveryengine.v1beta.BigQuerySource], + and when + [GcsSource.data_schema][google.cloud.discoveryengine.v1beta.GcsSource.data_schema] + or + [BigQuerySource.data_schema][google.cloud.discoveryengine.v1beta.BigQuerySource.data_schema] + is ``custom``. And only set this field when + [auto_generate_ids][google.cloud.discoveryengine.v1beta.ImportDocumentsRequest.auto_generate_ids] + is unset or set as ``false``. Otherwise, an INVALID_ARGUMENT + error is thrown. + + If it is unset, a default value ``_id`` is used when + importing from the allowed data sources. + """ + class ReconciliationMode(proto.Enum): + r"""Indicates how imported documents are reconciled with the + existing documents created or imported before. + + Values: + RECONCILIATION_MODE_UNSPECIFIED (0): + Defaults to ``INCREMENTAL``. + INCREMENTAL (1): + Inserts new documents or updates existing + documents. + FULL (2): + Calculates diff and replaces the entire + document dataset. Existing documents may be + deleted if they are not present in the source + location. + """ + RECONCILIATION_MODE_UNSPECIFIED = 0 + INCREMENTAL = 1 + FULL = 2 + + class InlineSource(proto.Message): + r"""The inline source for the input config for ImportDocuments + method. + + Attributes: + documents (MutableSequence[google.cloud.discoveryengine_v1beta.types.Document]): + Required. A list of documents to update/create. Each + document must have a valid + [Document.id][google.cloud.discoveryengine.v1beta.Document.id]. + Recommended max of 100 items. + """ + + documents: MutableSequence[document.Document] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=document.Document, + ) + + inline_source: InlineSource = proto.Field( + proto.MESSAGE, + number=2, + oneof='source', + message=InlineSource, + ) + gcs_source: 'GcsSource' = proto.Field( + proto.MESSAGE, + number=3, + oneof='source', + message='GcsSource', + ) + bigquery_source: 'BigQuerySource' = proto.Field( + proto.MESSAGE, + number=4, + oneof='source', + message='BigQuerySource', + ) + parent: str = proto.Field( + proto.STRING, + number=1, + ) + error_config: 'ImportErrorConfig' = proto.Field( + proto.MESSAGE, + number=5, + message='ImportErrorConfig', + ) + reconciliation_mode: ReconciliationMode = proto.Field( + proto.ENUM, + number=6, + enum=ReconciliationMode, + ) + auto_generate_ids: bool = proto.Field( + proto.BOOL, + number=8, + ) + id_field: str = proto.Field( + proto.STRING, + number=9, + ) + + +class ImportDocumentsResponse(proto.Message): + r"""Response of the + [ImportDocumentsRequest][google.cloud.discoveryengine.v1beta.ImportDocumentsRequest]. + If the long running operation is done, then this message is returned + by the google.longrunning.Operations.response field if the operation + was successful. + + Attributes: + error_samples (MutableSequence[google.rpc.status_pb2.Status]): + A sample of errors encountered while + processing the request. + error_config (google.cloud.discoveryengine_v1beta.types.ImportErrorConfig): + Echoes the destination for the complete + errors in the request if set. + """ + + error_samples: MutableSequence[status_pb2.Status] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + error_config: 'ImportErrorConfig' = proto.Field( + proto.MESSAGE, + number=2, + message='ImportErrorConfig', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/purge_config.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/purge_config.py new file mode 100644 index 000000000000..14d7d3c87642 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/purge_config.py @@ -0,0 +1,133 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1beta', + manifest={ + 'PurgeDocumentsRequest', + 'PurgeDocumentsResponse', + 'PurgeDocumentsMetadata', + }, +) + + +class PurgeDocumentsRequest(proto.Message): + r"""Request message for + [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1beta.DocumentService.PurgeDocuments] + method. + + Attributes: + parent (str): + Required. The parent resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. + filter (str): + Required. Filter matching documents to purge. Only currently + supported value is ``*`` (all items). + force (bool): + Actually performs the purge. If ``force`` is set to false, + return the expected purge count without deleting any + documents. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + force: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class PurgeDocumentsResponse(proto.Message): + r"""Response message for + [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1beta.DocumentService.PurgeDocuments] + method. If the long running operation is successfully done, then + this message is returned by the + google.longrunning.Operations.response field. + + Attributes: + purge_count (int): + The total count of documents purged as a + result of the operation. + purge_sample (MutableSequence[str]): + A sample of document names that will be deleted. Only + populated if ``force`` is set to false. A max of 100 names + will be returned and the names are chosen at random. + """ + + purge_count: int = proto.Field( + proto.INT64, + number=1, + ) + purge_sample: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class PurgeDocumentsMetadata(proto.Message): + r"""Metadata related to the progress of the PurgeDocuments + operation. This will be returned by the + google.longrunning.Operation.metadata field. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + success_count (int): + Count of entries that were deleted + successfully. + failure_count (int): + Count of entries that encountered errors + while processing. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + success_count: int = proto.Field( + proto.INT64, + number=3, + ) + failure_count: int = proto.Field( + proto.INT64, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/recommendation_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/recommendation_service.py new file mode 100644 index 000000000000..d367306d2b22 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/recommendation_service.py @@ -0,0 +1,264 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import document as gcd_document +from google.cloud.discoveryengine_v1beta.types import user_event as gcd_user_event +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1beta', + manifest={ + 'RecommendRequest', + 'RecommendResponse', + }, +) + + +class RecommendRequest(proto.Message): + r"""Request message for Recommend method. + + Attributes: + serving_config (str): + Required. Full resource name of the format: + ``projects/*/locations/global/collections/*/dataStores/*/servingConfigs/*`` + + Before you can request recommendations from your model, you + must create at least one serving config for it. + user_event (google.cloud.discoveryengine_v1beta.types.UserEvent): + Required. Context about the user, what they are looking at + and what action they took to trigger the Recommend request. + Note that this user event detail won't be ingested to + userEvent logs. Thus, a separate userEvent write request is + required for event logging. + + Don't set + [UserEvent.user_pseudo_id][google.cloud.discoveryengine.v1beta.UserEvent.user_pseudo_id] + or + [UserEvent.user_info.user_id][google.cloud.discoveryengine.v1beta.UserInfo.user_id] + to the same fixed ID for different users. If you are trying + to receive non-personalized recommendations (not + recommended; this can negatively impact model performance), + instead set + [UserEvent.user_pseudo_id][google.cloud.discoveryengine.v1beta.UserEvent.user_pseudo_id] + to a random unique ID and leave + [UserEvent.user_info.user_id][google.cloud.discoveryengine.v1beta.UserInfo.user_id] + unset. + page_size (int): + Maximum number of results to return. Set this + property to the number of recommendation results + needed. If zero, the service will choose a + reasonable default. The maximum allowed value is + 100. Values above 100 will be coerced to 100. + filter (str): + Filter for restricting recommendation results with a length + limit of 5,000 characters. Currently, only filter + expressions on the ``filter_tags`` attribute is supported. + + Examples: + + - ``(filter_tags: ANY("Red", "Blue") OR filter_tags: ANY("Hot", "Cold"))`` + - ``(filter_tags: ANY("Red", "Blue")) AND NOT (filter_tags: ANY("Green"))`` + + If your filter blocks all results, the API will return + generic (unfiltered) popular Documents. If you only want + results strictly matching the filters, set + ``strictFiltering`` to True in + [RecommendRequest.params][google.cloud.discoveryengine.v1beta.RecommendRequest.params] + to receive empty results instead. + + Note that the API will never return + [Document][google.cloud.discoveryengine.v1beta.Document]s + with ``storageStatus`` of ``EXPIRED`` or ``DELETED`` + regardless of filter choices. + validate_only (bool): + Use validate only mode for this + recommendation query. If set to true, a fake + model will be used that returns arbitrary + Document IDs. Note that the validate only mode + should only be used for testing the API, or if + the model is not ready. + params (MutableMapping[str, google.protobuf.struct_pb2.Value]): + Additional domain specific parameters for the + recommendations. + + Allowed values: + + - ``returnDocument``: Boolean. If set to true, the + associated Document object will be returned in + [RecommendResponse.RecommendationResult.document][google.cloud.discoveryengine.v1beta.RecommendResponse.RecommendationResult.document]. + - ``returnScore``: Boolean. If set to true, the + recommendation 'score' corresponding to each returned + Document will be set in + [RecommendResponse.RecommendationResult.metadata][google.cloud.discoveryengine.v1beta.RecommendResponse.RecommendationResult.metadata]. + The given 'score' indicates the probability of a Document + conversion given the user's context and history. + - ``strictFiltering``: Boolean. True by default. If set to + false, the service will return generic (unfiltered) + popular Documents instead of empty if your filter blocks + all recommendation results. + - ``diversityLevel``: String. Default empty. If set to be + non-empty, then it needs to be one of: + + - ``no-diversity`` + - ``low-diversity`` + - ``medium-diversity`` + - ``high-diversity`` + - ``auto-diversity`` This gives request-level control + and adjusts recommendation results based on Document + category. + user_labels (MutableMapping[str, str]): + The user labels applied to a resource must meet the + following requirements: + + - Each resource can have multiple labels, up to a maximum + of 64. + - Each label must be a key-value pair. + - Keys have a minimum length of 1 character and a maximum + length of 63 characters and cannot be empty. Values can + be empty and have a maximum length of 63 characters. + - Keys and values can contain only lowercase letters, + numeric characters, underscores, and dashes. All + characters must use UTF-8 encoding, and international + characters are allowed. + - The key portion of a label must be unique. However, you + can use the same key with multiple resources. + - Keys must start with a lowercase letter or international + character. + + See `Requirements for + labels `__ + for more details. + """ + + serving_config: str = proto.Field( + proto.STRING, + number=1, + ) + user_event: gcd_user_event.UserEvent = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_user_event.UserEvent, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=5, + ) + params: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=6, + message=struct_pb2.Value, + ) + user_labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=8, + ) + + +class RecommendResponse(proto.Message): + r"""Response message for Recommend method. + + Attributes: + results (MutableSequence[google.cloud.discoveryengine_v1beta.types.RecommendResponse.RecommendationResult]): + A list of recommended Documents. The order + represents the ranking (from the most relevant + Document to the least). + attribution_token (str): + A unique attribution token. This should be included in the + [UserEvent][google.cloud.discoveryengine.v1beta.UserEvent] + logs resulting from this recommendation, which enables + accurate attribution of recommendation model performance. + missing_ids (MutableSequence[str]): + IDs of documents in the request that were + missing from the default Branch associated with + the requested ServingConfig. + validate_only (bool): + True if + [RecommendRequest.validate_only][google.cloud.discoveryengine.v1beta.RecommendRequest.validate_only] + was set. + """ + + class RecommendationResult(proto.Message): + r"""RecommendationResult represents a generic recommendation + result with associated metadata. + + Attributes: + id (str): + Resource ID of the recommended Document. + document (google.cloud.discoveryengine_v1beta.types.Document): + Set if ``returnDocument`` is set to true in + [RecommendRequest.params][google.cloud.discoveryengine.v1beta.RecommendRequest.params]. + metadata (MutableMapping[str, google.protobuf.struct_pb2.Value]): + Additional Document metadata / annotations. + + Possible values: + + - ``score``: Recommendation score in double value. Is set + if ``returnScore`` is set to true in + [RecommendRequest.params][google.cloud.discoveryengine.v1beta.RecommendRequest.params]. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + document: gcd_document.Document = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_document.Document, + ) + metadata: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=3, + message=struct_pb2.Value, + ) + + results: MutableSequence[RecommendationResult] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=RecommendationResult, + ) + attribution_token: str = proto.Field( + proto.STRING, + number=2, + ) + missing_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/schema.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/schema.py new file mode 100644 index 000000000000..0a7bd7de897b --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/schema.py @@ -0,0 +1,78 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1beta', + manifest={ + 'Schema', + }, +) + + +class Schema(proto.Message): + r"""Defines the structure and layout of a type of document data. + + 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: + struct_schema (google.protobuf.struct_pb2.Struct): + The structured representation of the schema. + + This field is a member of `oneof`_ ``schema``. + json_schema (str): + The JSON representation of the schema. + + This field is a member of `oneof`_ ``schema``. + name (str): + Immutable. The full resource name of the schema, in the + format of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. + + This field must be a UTF-8 encoded string with a length + limit of 1024 characters. + """ + + struct_schema: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=2, + oneof='schema', + message=struct_pb2.Struct, + ) + json_schema: str = proto.Field( + proto.STRING, + number=3, + oneof='schema', + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/schema_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/schema_service.py new file mode 100644 index 000000000000..cf3d210dfce7 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/schema_service.py @@ -0,0 +1,291 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import schema as gcd_schema +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1beta', + manifest={ + 'GetSchemaRequest', + 'ListSchemasRequest', + 'ListSchemasResponse', + 'CreateSchemaRequest', + 'UpdateSchemaRequest', + 'DeleteSchemaRequest', + 'CreateSchemaMetadata', + 'UpdateSchemaMetadata', + 'DeleteSchemaMetadata', + }, +) + + +class GetSchemaRequest(proto.Message): + r"""Request message for + [SchemaService.GetSchema][google.cloud.discoveryengine.v1beta.SchemaService.GetSchema] + method. + + Attributes: + name (str): + Required. The full resource name of the schema, in the + format of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListSchemasRequest(proto.Message): + r"""Request message for + [SchemaService.ListSchemas][google.cloud.discoveryengine.v1beta.SchemaService.ListSchemas] + method. + + Attributes: + parent (str): + Required. The parent data store resource name, in the format + of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. + page_size (int): + The maximum number of + [Schema][google.cloud.discoveryengine.v1beta.Schema]s to + return. The service may return fewer than this value. + + If unspecified, at most 100 + [Schema][google.cloud.discoveryengine.v1beta.Schema]s will + be returned. + + The maximum value is 1000; values above 1000 will be coerced + to 1000. + page_token (str): + A page token, received from a previous + [SchemaService.ListSchemas][google.cloud.discoveryengine.v1beta.SchemaService.ListSchemas] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [SchemaService.ListSchemas][google.cloud.discoveryengine.v1beta.SchemaService.ListSchemas] + 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 ListSchemasResponse(proto.Message): + r"""Response message for + [SchemaService.ListSchemas][google.cloud.discoveryengine.v1beta.SchemaService.ListSchemas] + method. + + Attributes: + schemas (MutableSequence[google.cloud.discoveryengine_v1beta.types.Schema]): + The [Schema][google.cloud.discoveryengine.v1beta.Schema]s. + next_page_token (str): + A token that can be sent as + [ListSchemasRequest.page_token][google.cloud.discoveryengine.v1beta.ListSchemasRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + schemas: MutableSequence[gcd_schema.Schema] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_schema.Schema, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateSchemaRequest(proto.Message): + r"""Request message for + [SchemaService.CreateSchema][google.cloud.discoveryengine.v1beta.SchemaService.CreateSchema] + method. + + Attributes: + parent (str): + Required. The parent data store resource name, in the format + of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. + schema (google.cloud.discoveryengine_v1beta.types.Schema): + Required. The + [Schema][google.cloud.discoveryengine.v1beta.Schema] to + create. + schema_id (str): + Required. The ID to use for the + [Schema][google.cloud.discoveryengine.v1beta.Schema], which + will become the final component of the + [Schema.name][google.cloud.discoveryengine.v1beta.Schema.name]. + + This field should conform to + `RFC-1034 `__ standard + with a length limit of 63 characters. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + schema: gcd_schema.Schema = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_schema.Schema, + ) + schema_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateSchemaRequest(proto.Message): + r"""Request message for + [SchemaService.UpdateSchema][google.cloud.discoveryengine.v1beta.SchemaService.UpdateSchema] + method. + + Attributes: + schema (google.cloud.discoveryengine_v1beta.types.Schema): + Required. The + [Schema][google.cloud.discoveryengine.v1beta.Schema] to + update. + allow_missing (bool): + If set to true, and the + [Schema][google.cloud.discoveryengine.v1beta.Schema] is not + found, a new + [Schema][google.cloud.discoveryengine.v1beta.Schema] will be + created. In this situation, ``update_mask`` is ignored. + """ + + schema: gcd_schema.Schema = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_schema.Schema, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class DeleteSchemaRequest(proto.Message): + r"""Request message for + [SchemaService.DeleteSchema][google.cloud.discoveryengine.v1beta.SchemaService.DeleteSchema] + method. + + Attributes: + name (str): + Required. The full resource name of the schema, in the + format of + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateSchemaMetadata(proto.Message): + r"""Metadata for Create Schema LRO. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class UpdateSchemaMetadata(proto.Message): + r"""Metadata for UpdateSchema LRO. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class DeleteSchemaMetadata(proto.Message): + r"""Metadata for DeleteSchema LRO. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Operation create time. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Operation last update time. If the operation + is done, this is also the finish time. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/search_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/search_service.py new file mode 100644 index 000000000000..daaae5214b66 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/search_service.py @@ -0,0 +1,1312 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import common +from google.cloud.discoveryengine_v1beta.types import document as gcd_document +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1beta', + manifest={ + 'SearchRequest', + 'SearchResponse', + }, +) + + +class SearchRequest(proto.Message): + r"""Request message for + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + method. + + Attributes: + serving_config (str): + Required. The resource name of the Search serving config, + such as + ``projects/*/locations/global/collections/default_collection/dataStores/default_data_store/servingConfigs/default_serving_config``. + This field is used to identify the serving configuration + name, set of models used to make the search. + branch (str): + The branch resource name, such as + ``projects/*/locations/global/collections/default_collection/dataStores/default_data_store/branches/0``. + + Use ``default_branch`` as the branch ID or leave this field + empty, to search documents under the default branch. + query (str): + Raw search query. + image_query (google.cloud.discoveryengine_v1beta.types.SearchRequest.ImageQuery): + Raw image query. + page_size (int): + Maximum number of + [Document][google.cloud.discoveryengine.v1beta.Document]s to + return. If unspecified, defaults to a reasonable value. The + maximum allowed value is 100. Values above 100 are coerced + to 100. + + If this field is negative, an ``INVALID_ARGUMENT`` is + returned. + page_token (str): + A page token received from a previous + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + must match the call that provided the page token. Otherwise, + an ``INVALID_ARGUMENT`` error is returned. + offset (int): + A 0-indexed integer that specifies the current offset (that + is, starting result location, amongst the + [Document][google.cloud.discoveryengine.v1beta.Document]s + deemed by the API as relevant) in search results. This field + is only considered if + [page_token][google.cloud.discoveryengine.v1beta.SearchRequest.page_token] + is unset. + + If this field is negative, an ``INVALID_ARGUMENT`` is + returned. + filter (str): + The filter syntax consists of an expression language for + constructing a predicate from one or more fields of the + documents being filtered. Filter expression is + case-sensitive. + + If this field is unrecognizable, an ``INVALID_ARGUMENT`` is + returned. + order_by (str): + The order in which documents are returned. Documents can be + ordered by a field in an + [Document][google.cloud.discoveryengine.v1beta.Document] + object. Leave it unset if ordered by relevance. ``order_by`` + expression is case-sensitive. + + If this field is unrecognizable, an ``INVALID_ARGUMENT`` is + returned. + user_info (google.cloud.discoveryengine_v1beta.types.UserInfo): + Information about the end user. Highly recommended for + analytics. + [UserInfo.user_agent][google.cloud.discoveryengine.v1beta.UserInfo.user_agent] + is used to deduce ``device_type`` for analytics. + facet_specs (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchRequest.FacetSpec]): + Facet specifications for faceted search. If empty, no facets + are returned. + + A maximum of 100 values are allowed. Otherwise, an + ``INVALID_ARGUMENT`` error is returned. + boost_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.BoostSpec): + Boost specification to boost certain + documents. + params (MutableMapping[str, google.protobuf.struct_pb2.Value]): + Additional search parameters. + + For public website search only, supported values are: + + - ``user_country_code``: string. Default empty. If set to + non-empty, results are restricted or boosted based on the + location provided. + - ``search_type``: double. Default empty. Enables + non-webpage searching depending on the value. The only + valid non-default value is 1, which enables image + searching. + query_expansion_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.QueryExpansionSpec): + The query expansion specification that + specifies the conditions under which query + expansion occurs. + spell_correction_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.SpellCorrectionSpec): + The spell correction specification that + specifies the mode under which spell correction + takes effect. + user_pseudo_id (str): + A unique identifier for tracking visitors. For example, this + could be implemented with an HTTP cookie, which should be + able to uniquely identify a visitor on a single device. This + unique identifier should not change if the visitor logs in + or out of the website. + + This field should NOT have a fixed value such as + ``unknown_visitor``. + + This should be the same identifier as + [UserEvent.user_pseudo_id][google.cloud.discoveryengine.v1beta.UserEvent.user_pseudo_id] + and + [CompleteQueryRequest.user_pseudo_id][google.cloud.discoveryengine.v1beta.CompleteQueryRequest.user_pseudo_id] + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an ``INVALID_ARGUMENT`` error + is returned. + content_search_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.ContentSearchSpec): + A specification for configuring the behavior + of content search. + embedding_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.EmbeddingSpec): + Uses the provided embedding to do additional semantic + document retrieval. The retrieval is based on the dot + product of + [SearchRequest.embedding_spec.embedding_vectors.vector][] + and the document embedding that is provided in + [SearchRequest.embedding_spec.embedding_vectors.field_path][]. + + If + [SearchRequest.embedding_spec.embedding_vectors.field_path][] + is not provided, it will use + [ServingConfig.embedding_config.field_paths][]. + ranking_expression (str): + The ranking expression controls the customized ranking on + retrieval documents. This overrides + [ServingConfig.ranking_expression][]. The ranking expression + is a single function or multiple functions that are joint by + "+". + + - ranking_expression = function, { " + ", function }; + Supported functions: + - double \* relevance_score + - double \* dotProduct(embedding_field_path) Function + variables: ``relevance_score``: pre-defined keywords, + used for measure relevance between query and document. + ``embedding_field_path``: the document embedding field + used with query embedding vector. ``dotProduct``: + embedding function between embedding_field_path and query + embedding vector. + + Example ranking expression: If document has an embedding + field doc_embedding, the ranking expression could be + ``0.5 * relevance_score + 0.3 * dotProduct(doc_embedding)``. + safe_search (bool): + Whether to turn on safe search. This is only + supported for website search. + user_labels (MutableMapping[str, str]): + The user labels applied to a resource must meet the + following requirements: + + - Each resource can have multiple labels, up to a maximum + of 64. + - Each label must be a key-value pair. + - Keys have a minimum length of 1 character and a maximum + length of 63 characters and cannot be empty. Values can + be empty and have a maximum length of 63 characters. + - Keys and values can contain only lowercase letters, + numeric characters, underscores, and dashes. All + characters must use UTF-8 encoding, and international + characters are allowed. + - The key portion of a label must be unique. However, you + can use the same key with multiple resources. + - Keys must start with a lowercase letter or international + character. + + See `Google Cloud + Document `__ + for more details. + """ + + class ImageQuery(proto.Message): + r"""Specifies the image query input. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + image_bytes (str): + Base64 encoded image bytes. Supported image + formats: JPEG, PNG, and BMP. + + This field is a member of `oneof`_ ``image``. + """ + + image_bytes: str = proto.Field( + proto.STRING, + number=1, + oneof='image', + ) + + class FacetSpec(proto.Message): + r"""A facet specification to perform faceted search. + + Attributes: + facet_key (google.cloud.discoveryengine_v1beta.types.SearchRequest.FacetSpec.FacetKey): + Required. The facet key specification. + limit (int): + Maximum of facet values that should be returned for this + facet. If unspecified, defaults to 20. The maximum allowed + value is 300. Values above 300 are coerced to 300. + + If this field is negative, an ``INVALID_ARGUMENT`` is + returned. + excluded_filter_keys (MutableSequence[str]): + List of keys to exclude when faceting. + + By default, + [FacetKey.key][google.cloud.discoveryengine.v1beta.SearchRequest.FacetSpec.FacetKey.key] + is not excluded from the filter unless it is listed in this + field. + + Listing a facet key in this field allows its values to + appear as facet results, even when they are filtered out of + search results. Using this field does not affect what search + results are returned. + + For example, suppose there are 100 documents with the color + facet "Red" and 200 documents with the color facet "Blue". A + query containing the filter "color:ANY("Red")" and having + "color" as + [FacetKey.key][google.cloud.discoveryengine.v1beta.SearchRequest.FacetSpec.FacetKey.key] + would by default return only "Red" documents in the search + results, and also return "Red" with count 100 as the only + color facet. Although there are also blue documents + available, "Blue" would not be shown as an available facet + value. + + If "color" is listed in "excludedFilterKeys", then the query + returns the facet values "Red" with count 100 and "Blue" + with count 200, because the "color" key is now excluded from + the filter. Because this field doesn't affect search + results, the search results are still correctly filtered to + return only "Red" documents. + + A maximum of 100 values are allowed. Otherwise, an + ``INVALID_ARGUMENT`` error is returned. + enable_dynamic_position (bool): + Enables dynamic position for this facet. If set to true, the + position of this facet among all facets in the response is + determined automatically. If dynamic facets are enabled, it + is ordered together. If set to false, the position of this + facet in the response is the same as in the request, and it + is ranked before the facets with dynamic position enable and + all dynamic facets. + + For example, you may always want to have rating facet + returned in the response, but it's not necessarily to always + display the rating facet at the top. In that case, you can + set enable_dynamic_position to true so that the position of + rating facet in response is determined automatically. + + Another example, assuming you have the following facets in + the request: + + - "rating", enable_dynamic_position = true + + - "price", enable_dynamic_position = false + + - "brands", enable_dynamic_position = false + + And also you have a dynamic facets enabled, which generates + a facet ``gender``. Then the final order of the facets in + the response can be ("price", "brands", "rating", "gender") + or ("price", "brands", "gender", "rating") depends on how + API orders "gender" and "rating" facets. However, notice + that "price" and "brands" are always ranked at first and + second position because their enable_dynamic_position is + false. + """ + + class FacetKey(proto.Message): + r"""Specifies how a facet is computed. + + Attributes: + key (str): + Required. Supported textual and numerical facet keys in + [Document][google.cloud.discoveryengine.v1beta.Document] + object, over which the facet values are computed. Facet key + is case-sensitive. + intervals (MutableSequence[google.cloud.discoveryengine_v1beta.types.Interval]): + Set only if values should be bucketed into + intervals. Must be set for facets with numerical + values. Must not be set for facet with text + values. Maximum number of intervals is 30. + restricted_values (MutableSequence[str]): + Only get facet for the given restricted values. Only + supported on textual fields. For example, suppose "category" + has three values "Action > 2022", "Action > 2021" and + "Sci-Fi > 2022". If set "restricted_values" to "Action > + 2022", the "category" facet only contains "Action > 2022". + Only supported on textual fields. Maximum is 10. + prefixes (MutableSequence[str]): + Only get facet values that start with the + given string prefix. For example, suppose + "category" has three values "Action > 2022", + "Action > 2021" and "Sci-Fi > 2022". If set + "prefixes" to "Action", the "category" facet + only contains "Action > 2022" and "Action > + 2021". Only supported on textual fields. Maximum + is 10. + contains (MutableSequence[str]): + Only get facet values that contains the given + strings. For example, suppose "category" has + three values "Action > 2022", "Action > 2021" + and "Sci-Fi > 2022". If set "contains" to + "2022", the "category" facet only contains + "Action > 2022" and "Sci-Fi > 2022". Only + supported on textual fields. Maximum is 10. + case_insensitive (bool): + True to make facet keys case insensitive when + getting faceting values with prefixes or + contains; false otherwise. + order_by (str): + The order in which documents are returned. + + Allowed values are: + + - "count desc", which means order by + [SearchResponse.Facet.values.count][google.cloud.discoveryengine.v1beta.SearchResponse.Facet.FacetValue.count] + descending. + + - "value desc", which means order by + [SearchResponse.Facet.values.value][google.cloud.discoveryengine.v1beta.SearchResponse.Facet.FacetValue.value] + descending. Only applies to textual facets. + + If not set, textual values are sorted in `natural + order `__; + numerical intervals are sorted in the order given by + [FacetSpec.FacetKey.intervals][google.cloud.discoveryengine.v1beta.SearchRequest.FacetSpec.FacetKey.intervals]. + """ + + key: str = proto.Field( + proto.STRING, + number=1, + ) + intervals: MutableSequence[common.Interval] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=common.Interval, + ) + restricted_values: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + prefixes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + contains: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + case_insensitive: bool = proto.Field( + proto.BOOL, + number=6, + ) + order_by: str = proto.Field( + proto.STRING, + number=7, + ) + + facet_key: 'SearchRequest.FacetSpec.FacetKey' = proto.Field( + proto.MESSAGE, + number=1, + message='SearchRequest.FacetSpec.FacetKey', + ) + limit: int = proto.Field( + proto.INT32, + number=2, + ) + excluded_filter_keys: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + enable_dynamic_position: bool = proto.Field( + proto.BOOL, + number=4, + ) + + class BoostSpec(proto.Message): + r"""Boost specification to boost certain documents. + + Attributes: + condition_boost_specs (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchRequest.BoostSpec.ConditionBoostSpec]): + Condition boost specifications. If a document + matches multiple conditions in the + specifictions, boost scores from these + specifications are all applied and combined in a + non-linear way. Maximum number of specifications + is 20. + """ + + class ConditionBoostSpec(proto.Message): + r"""Boost applies to documents which match a condition. + + Attributes: + condition (str): + An expression which specifies a boost condition. The syntax + and supported fields are the same as a filter expression. + See + [SearchRequest.filter][google.cloud.discoveryengine.v1beta.SearchRequest.filter] + for detail syntax and limitations. + + Examples: + + - To boost documents with document ID "doc_1" or "doc_2", + and color "Red" or "Blue": + + - (id: ANY("doc_1", "doc_2")) AND (color: + ANY("Red","Blue")) + boost (float): + Strength of the condition boost, which should be in [-1, 1]. + Negative boost means demotion. Default is 0.0. + + Setting to 1.0 gives the document a big promotion. However, + it does not necessarily mean that the boosted document will + be the top result at all times, nor that other documents + will be excluded. Results could still be shown even when + none of them matches the condition. And results that are + significantly more relevant to the search query can still + trump your heavily favored but irrelevant documents. + + Setting to -1.0 gives the document a big demotion. However, + results that are deeply relevant might still be shown. The + document will have an upstream battle to get a fairly high + ranking, but it is not blocked out completely. + + Setting to 0.0 means no boost applied. The boosting + condition is ignored. + """ + + condition: str = proto.Field( + proto.STRING, + number=1, + ) + boost: float = proto.Field( + proto.FLOAT, + number=2, + ) + + condition_boost_specs: MutableSequence['SearchRequest.BoostSpec.ConditionBoostSpec'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SearchRequest.BoostSpec.ConditionBoostSpec', + ) + + class QueryExpansionSpec(proto.Message): + r"""Specification to determine under which conditions query + expansion should occur. + + Attributes: + condition (google.cloud.discoveryengine_v1beta.types.SearchRequest.QueryExpansionSpec.Condition): + The condition under which query expansion should occur. + Default to + [Condition.DISABLED][google.cloud.discoveryengine.v1beta.SearchRequest.QueryExpansionSpec.Condition.DISABLED]. + pin_unexpanded_results (bool): + Whether to pin unexpanded results. If this + field is set to true, unexpanded products are + always at the top of the search results, + followed by the expanded results. + """ + class Condition(proto.Enum): + r"""Enum describing under which condition query expansion should + occur. + + Values: + CONDITION_UNSPECIFIED (0): + Unspecified query expansion condition. In this case, server + behavior defaults to + [Condition.DISABLED][google.cloud.discoveryengine.v1beta.SearchRequest.QueryExpansionSpec.Condition.DISABLED]. + DISABLED (1): + Disabled query expansion. Only the exact search query is + used, even if + [SearchResponse.total_size][google.cloud.discoveryengine.v1beta.SearchResponse.total_size] + is zero. + AUTO (2): + Automatic query expansion built by the Search + API. + """ + CONDITION_UNSPECIFIED = 0 + DISABLED = 1 + AUTO = 2 + + condition: 'SearchRequest.QueryExpansionSpec.Condition' = proto.Field( + proto.ENUM, + number=1, + enum='SearchRequest.QueryExpansionSpec.Condition', + ) + pin_unexpanded_results: bool = proto.Field( + proto.BOOL, + number=2, + ) + + class SpellCorrectionSpec(proto.Message): + r"""The specification for query spell correction. + + Attributes: + mode (google.cloud.discoveryengine_v1beta.types.SearchRequest.SpellCorrectionSpec.Mode): + The mode under which spell correction should take effect to + replace the original search query. Default to + [Mode.AUTO][google.cloud.discoveryengine.v1beta.SearchRequest.SpellCorrectionSpec.Mode.AUTO]. + """ + class Mode(proto.Enum): + r"""Enum describing under which mode spell correction should + occur. + + Values: + MODE_UNSPECIFIED (0): + Unspecified spell correction mode. In this case, server + behavior defaults to + [Mode.AUTO][google.cloud.discoveryengine.v1beta.SearchRequest.SpellCorrectionSpec.Mode.AUTO]. + SUGGESTION_ONLY (1): + Search API will try to find a spell suggestion if there is + any and put in the + [SearchResponse.corrected_query][google.cloud.discoveryengine.v1beta.SearchResponse.corrected_query]. + The spell suggestion will not be used as the search query. + AUTO (2): + Automatic spell correction built by the + Search API. Search will be based on the + corrected query if found. + """ + MODE_UNSPECIFIED = 0 + SUGGESTION_ONLY = 1 + AUTO = 2 + + mode: 'SearchRequest.SpellCorrectionSpec.Mode' = proto.Field( + proto.ENUM, + number=1, + enum='SearchRequest.SpellCorrectionSpec.Mode', + ) + + class ContentSearchSpec(proto.Message): + r"""A specification for configuring the behavior of content + search. + + Attributes: + snippet_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.ContentSearchSpec.SnippetSpec): + If ``snippetSpec`` is not specified, snippets are not + included in the search response. + summary_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.ContentSearchSpec.SummarySpec): + If ``summarySpec`` is not specified, summaries are not + included in the search response. + extractive_content_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.ContentSearchSpec.ExtractiveContentSpec): + If there is no extractive_content_spec provided, there will + be no extractive answer in the search response. + """ + + class SnippetSpec(proto.Message): + r"""A specification for configuring snippets in a search + response. + + Attributes: + max_snippet_count (int): + [DEPRECATED] This field is deprecated. To control snippet + return, use ``return_snippet`` field. For backwards + compatibility, we will return snippet if max_snippet_count > + 0. + reference_only (bool): + [DEPRECATED] This field is deprecated and will have no + affect on the snippet. + return_snippet (bool): + If ``true``, then return snippet. If no snippet can be + generated, we return "No snippet is available for this + page." A ``snippet_status`` with ``SUCCESS`` or + ``NO_SNIPPET_AVAILABLE`` will also be returned. + """ + + max_snippet_count: int = proto.Field( + proto.INT32, + number=1, + ) + reference_only: bool = proto.Field( + proto.BOOL, + number=2, + ) + return_snippet: bool = proto.Field( + proto.BOOL, + number=3, + ) + + class SummarySpec(proto.Message): + r"""A specification for configuring a summary returned in a + search response. + + Attributes: + summary_result_count (int): + The number of top results to generate the summary from. If + the number of results returned is less than + ``summaryResultCount``, the summary is generated from all of + the results. + + At most five results can be used to generate a summary. + include_citations (bool): + Specifies whether to include citations in the summary. The + default value is ``false``. + + When this field is set to ``true``, summaries include + in-line citation numbers. + + Example summary including citations: + + BigQuery is Google Cloud's fully managed and completely + serverless enterprise data warehouse [1]. BigQuery supports + all data types, works across clouds, and has built-in + machine learning and business intelligence, all within a + unified platform [2, 3]. + + The citation numbers refer to the returned search results + and are 1-indexed. For example, [1] means that the sentence + is attributed to the first search result. [2, 3] means that + the sentence is attributed to both the second and third + search results. + ignore_adversarial_query (bool): + Specifies whether to filter out adversarial queries. The + default value is ``false``. + + Google employs search-query classification to detect + adversarial queries. No summary is returned if the search + query is classified as an adversarial query. For example, a + user might ask a question regarding negative comments about + the company or submit a query designed to generate unsafe, + policy-violating output. If this field is set to ``true``, + we skip generating summaries for adversarial queries and + return fallback messages instead. + ignore_non_summary_seeking_query (bool): + Specifies whether to filter out queries that are not + summary-seeking. The default value is ``false``. + + Google employs search-query classification to detect + summary-seeking queries. No summary is returned if the + search query is classified as a non-summary seeking query. + For example, ``why is the sky blue`` and + ``Who is the best soccer player in the world?`` are + summary-seeking queries, but ``SFO airport`` and + ``world cup 2026`` are not. They are most likely + navigational queries. If this field is set to ``true``, we + skip generating summaries for non-summary seeking queries + and return fallback messages instead. + language_code (str): + Language code for Summary. Use language tags defined by + [BCP47][https://www.rfc-editor.org/rfc/bcp/bcp47.txt]. + """ + + summary_result_count: int = proto.Field( + proto.INT32, + number=1, + ) + include_citations: bool = proto.Field( + proto.BOOL, + number=2, + ) + ignore_adversarial_query: bool = proto.Field( + proto.BOOL, + number=3, + ) + ignore_non_summary_seeking_query: bool = proto.Field( + proto.BOOL, + number=4, + ) + language_code: str = proto.Field( + proto.STRING, + number=6, + ) + + class ExtractiveContentSpec(proto.Message): + r"""A specification for configuring the extractive content in a + search response. + + Attributes: + max_extractive_answer_count (int): + The maximum number of extractive answers returned in each + search result. + + An extractive answer is a verbatim answer extracted from the + original document, which provides a precise and contextually + relevant answer to the search query. + + If the number of matching answers is less than the + ``max_extractive_answer_count``, return all of the answers. + Otherwise, return the ``max_extractive_answer_count``. + + At most one answer is returned for each + [SearchResult][google.cloud.discoveryengine.v1beta.SearchResponse.SearchResult]. + max_extractive_segment_count (int): + The max number of extractive segments returned in each + search result. Only applied if the + [DataStore][google.cloud.discoveryengine.v1beta.DataStore] + is set to + [DataStore.ContentConfig.CONTENT_REQUIRED][google.cloud.discoveryengine.v1beta.DataStore.ContentConfig.CONTENT_REQUIRED] + or + [DataStore.solution_types][google.cloud.discoveryengine.v1beta.DataStore.solution_types] + is + [SOLUTION_TYPE_CHAT][google.cloud.discoveryengine.v1beta.SolutionType.SOLUTION_TYPE_CHAT]. + + An extractive segment is a text segment extracted from the + original document that is relevant to the search query, and, + in general, more verbose than an extractive answer. The + segment could then be used as input for LLMs to generate + summaries and answers. + + If the number of matching segments is less than + ``max_extractive_segment_count``, return all of the + segments. Otherwise, return the + ``max_extractive_segment_count``. + return_extractive_segment_score (bool): + Specifies whether to return the confidence score from the + extractive segments in each search result. The default value + is ``false``. + num_previous_segments (int): + Specifies whether to also include the adjacent from each + selected segments. Return at most ``num_previous_segments`` + segments before each selected segments. + num_next_segments (int): + Return at most ``num_next_segments`` segments after each + selected segments. + """ + + max_extractive_answer_count: int = proto.Field( + proto.INT32, + number=1, + ) + max_extractive_segment_count: int = proto.Field( + proto.INT32, + number=2, + ) + return_extractive_segment_score: bool = proto.Field( + proto.BOOL, + number=3, + ) + num_previous_segments: int = proto.Field( + proto.INT32, + number=4, + ) + num_next_segments: int = proto.Field( + proto.INT32, + number=5, + ) + + snippet_spec: 'SearchRequest.ContentSearchSpec.SnippetSpec' = proto.Field( + proto.MESSAGE, + number=1, + message='SearchRequest.ContentSearchSpec.SnippetSpec', + ) + summary_spec: 'SearchRequest.ContentSearchSpec.SummarySpec' = proto.Field( + proto.MESSAGE, + number=2, + message='SearchRequest.ContentSearchSpec.SummarySpec', + ) + extractive_content_spec: 'SearchRequest.ContentSearchSpec.ExtractiveContentSpec' = proto.Field( + proto.MESSAGE, + number=3, + message='SearchRequest.ContentSearchSpec.ExtractiveContentSpec', + ) + + class EmbeddingSpec(proto.Message): + r"""The specification that uses customized query embedding vector + to do semantic document retrieval. + + Attributes: + embedding_vectors (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchRequest.EmbeddingSpec.EmbeddingVector]): + The embedding vector used for retrieval. + Limit to 1. + """ + + class EmbeddingVector(proto.Message): + r"""Embedding vector. + + Attributes: + field_path (str): + Embedding field path in schema. + vector (MutableSequence[float]): + Query embedding vector. + """ + + field_path: str = proto.Field( + proto.STRING, + number=1, + ) + vector: MutableSequence[float] = proto.RepeatedField( + proto.FLOAT, + number=2, + ) + + embedding_vectors: MutableSequence['SearchRequest.EmbeddingSpec.EmbeddingVector'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SearchRequest.EmbeddingSpec.EmbeddingVector', + ) + + serving_config: str = proto.Field( + proto.STRING, + number=1, + ) + branch: str = proto.Field( + proto.STRING, + number=2, + ) + query: str = proto.Field( + proto.STRING, + number=3, + ) + image_query: ImageQuery = proto.Field( + proto.MESSAGE, + number=19, + message=ImageQuery, + ) + page_size: int = proto.Field( + proto.INT32, + number=4, + ) + page_token: str = proto.Field( + proto.STRING, + number=5, + ) + offset: int = proto.Field( + proto.INT32, + number=6, + ) + filter: str = proto.Field( + proto.STRING, + number=7, + ) + order_by: str = proto.Field( + proto.STRING, + number=8, + ) + user_info: common.UserInfo = proto.Field( + proto.MESSAGE, + number=21, + message=common.UserInfo, + ) + facet_specs: MutableSequence[FacetSpec] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message=FacetSpec, + ) + boost_spec: BoostSpec = proto.Field( + proto.MESSAGE, + number=10, + message=BoostSpec, + ) + params: MutableMapping[str, struct_pb2.Value] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=11, + message=struct_pb2.Value, + ) + query_expansion_spec: QueryExpansionSpec = proto.Field( + proto.MESSAGE, + number=13, + message=QueryExpansionSpec, + ) + spell_correction_spec: SpellCorrectionSpec = proto.Field( + proto.MESSAGE, + number=14, + message=SpellCorrectionSpec, + ) + user_pseudo_id: str = proto.Field( + proto.STRING, + number=15, + ) + content_search_spec: ContentSearchSpec = proto.Field( + proto.MESSAGE, + number=24, + message=ContentSearchSpec, + ) + embedding_spec: EmbeddingSpec = proto.Field( + proto.MESSAGE, + number=23, + message=EmbeddingSpec, + ) + ranking_expression: str = proto.Field( + proto.STRING, + number=26, + ) + safe_search: bool = proto.Field( + proto.BOOL, + number=20, + ) + user_labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=22, + ) + + +class SearchResponse(proto.Message): + r"""Response message for + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + method. + + Attributes: + results (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchResponse.SearchResult]): + A list of matched documents. The order + represents the ranking. + facets (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchResponse.Facet]): + Results of facets requested by user. + guided_search_result (google.cloud.discoveryengine_v1beta.types.SearchResponse.GuidedSearchResult): + Guided search result. + total_size (int): + The estimated total count of matched items irrespective of + pagination. The count of + [results][google.cloud.discoveryengine.v1beta.SearchResponse.results] + returned by pagination may be less than the + [total_size][google.cloud.discoveryengine.v1beta.SearchResponse.total_size] + that matches. + attribution_token (str): + A unique search token. This should be included in the + [UserEvent][google.cloud.discoveryengine.v1beta.UserEvent] + logs resulting from this search, which enables accurate + attribution of search model performance. + redirect_uri (str): + The URI of a customer-defined redirect page. If redirect + action is triggered, no search is performed, and only + [redirect_uri][google.cloud.discoveryengine.v1beta.SearchResponse.redirect_uri] + and + [attribution_token][google.cloud.discoveryengine.v1beta.SearchResponse.attribution_token] + are set in the response. + next_page_token (str): + A token that can be sent as + [SearchRequest.page_token][google.cloud.discoveryengine.v1beta.SearchRequest.page_token] + to retrieve the next page. If this field is omitted, there + are no subsequent pages. + corrected_query (str): + Contains the spell corrected query, if found. If the spell + correction type is AUTOMATIC, then the search results are + based on corrected_query. Otherwise the original query is + used for search. + summary (google.cloud.discoveryengine_v1beta.types.SearchResponse.Summary): + A summary as part of the search results. This field is only + returned if + [SearchRequest.ContentSearchSpec.summary_spec][google.cloud.discoveryengine.v1beta.SearchRequest.ContentSearchSpec.summary_spec] + is set. + applied_controls (MutableSequence[str]): + Controls applied as part of the Control + service. + query_expansion_info (google.cloud.discoveryengine_v1beta.types.SearchResponse.QueryExpansionInfo): + Query expansion information for the returned + results. + """ + + class SearchResult(proto.Message): + r"""Represents the search results. + + Attributes: + id (str): + [Document.id][google.cloud.discoveryengine.v1beta.Document.id] + of the searched + [Document][google.cloud.discoveryengine.v1beta.Document]. + document (google.cloud.discoveryengine_v1beta.types.Document): + The document data snippet in the search + response. Only fields that are marked as + retrievable are populated. + model_scores (MutableMapping[str, google.cloud.discoveryengine_v1beta.types.DoubleList]): + Google provided available scores. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + document: gcd_document.Document = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_document.Document, + ) + model_scores: MutableMapping[str, common.DoubleList] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=4, + message=common.DoubleList, + ) + + class Facet(proto.Message): + r"""A facet result. + + Attributes: + key (str): + The key for this facet. E.g., "colors" or "price". It + matches + [SearchRequest.FacetSpec.FacetKey.key][google.cloud.discoveryengine.v1beta.SearchRequest.FacetSpec.FacetKey.key]. + values (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchResponse.Facet.FacetValue]): + The facet values for this field. + dynamic_facet (bool): + Whether the facet is dynamically generated. + """ + + class FacetValue(proto.Message): + r"""A facet value which contains value names and their count. + + 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: + value (str): + Text value of a facet, such as "Black" for + facet "colors". + + This field is a member of `oneof`_ ``facet_value``. + interval (google.cloud.discoveryengine_v1beta.types.Interval): + Interval value for a facet, such as [10, 20) for facet + "price". It matches + [SearchRequest.FacetSpec.FacetKey.intervals][google.cloud.discoveryengine.v1beta.SearchRequest.FacetSpec.FacetKey.intervals]. + + This field is a member of `oneof`_ ``facet_value``. + count (int): + Number of items that have this facet value. + """ + + value: str = proto.Field( + proto.STRING, + number=1, + oneof='facet_value', + ) + interval: common.Interval = proto.Field( + proto.MESSAGE, + number=2, + oneof='facet_value', + message=common.Interval, + ) + count: int = proto.Field( + proto.INT64, + number=3, + ) + + key: str = proto.Field( + proto.STRING, + number=1, + ) + values: MutableSequence['SearchResponse.Facet.FacetValue'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='SearchResponse.Facet.FacetValue', + ) + dynamic_facet: bool = proto.Field( + proto.BOOL, + number=3, + ) + + class GuidedSearchResult(proto.Message): + r"""Guided search result. The guided search helps user to refine + the search results and narrow down to the real needs from a + broaded search results. + + Attributes: + refinement_attributes (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchResponse.GuidedSearchResult.RefinementAttribute]): + A list of ranked refinement attributes. + follow_up_questions (MutableSequence[str]): + Suggested follow-up questions. + """ + + class RefinementAttribute(proto.Message): + r"""Useful attribute for search result refinements. + + Attributes: + attribute_key (str): + Attribute key used to refine the results e.g. 'movie_type'. + attribute_value (str): + Attribute value used to refine the results + e.g. 'drama'. + """ + + attribute_key: str = proto.Field( + proto.STRING, + number=1, + ) + attribute_value: str = proto.Field( + proto.STRING, + number=2, + ) + + refinement_attributes: MutableSequence['SearchResponse.GuidedSearchResult.RefinementAttribute'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SearchResponse.GuidedSearchResult.RefinementAttribute', + ) + follow_up_questions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + class Summary(proto.Message): + r"""Summary of the top N search result specified by the summary + spec. + + Attributes: + summary_text (str): + The summary content. + summary_skipped_reasons (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchResponse.Summary.SummarySkippedReason]): + Additional summary-skipped reasons. This + provides the reason for ignored cases. If + nothing is skipped, this field is not set. + safety_attributes (google.cloud.discoveryengine_v1beta.types.SearchResponse.Summary.SafetyAttributes): + A collection of Safety Attribute categories + and their associated confidence scores. + """ + class SummarySkippedReason(proto.Enum): + r"""An Enum for summary-skipped reasons. + + Values: + SUMMARY_SKIPPED_REASON_UNSPECIFIED (0): + Default value. The summary skipped reason is + not specified. + ADVERSARIAL_QUERY_IGNORED (1): + The adversarial query ignored case. + + Only populated when + [SummarySpec.ignore_adversarial_query][google.cloud.discoveryengine.v1beta.SearchRequest.ContentSearchSpec.SummarySpec.ignore_adversarial_query] + is set to ``true``. + NON_SUMMARY_SEEKING_QUERY_IGNORED (2): + The non-summary seeking query ignored case. + + Only populated when + [SummarySpec.ignore_non_summary_seeking_query][google.cloud.discoveryengine.v1beta.SearchRequest.ContentSearchSpec.SummarySpec.ignore_non_summary_seeking_query] + is set to ``true``. + OUT_OF_DOMAIN_QUERY_IGNORED (3): + The out-of-domain query ignored case. + + Google skips the summary if there are no + high-relevance search results. For example, the + data store contains facts about company A but + the user query is asking questions about company + B. + POTENTIAL_POLICY_VIOLATION (4): + The potential policy violation case. + + Google skips the summary if there is a potential + policy violation detected. This includes content + that may be violent or toxic. + LLM_ADDON_NOT_ENABLED (5): + The LLM addon not enabled case. + + Google skips the summary if the LLM addon is not + enabled. + """ + SUMMARY_SKIPPED_REASON_UNSPECIFIED = 0 + ADVERSARIAL_QUERY_IGNORED = 1 + NON_SUMMARY_SEEKING_QUERY_IGNORED = 2 + OUT_OF_DOMAIN_QUERY_IGNORED = 3 + POTENTIAL_POLICY_VIOLATION = 4 + LLM_ADDON_NOT_ENABLED = 5 + + class SafetyAttributes(proto.Message): + r"""Safety Attribute categories and their associated confidence + scores. + + Attributes: + categories (MutableSequence[str]): + The display names of Safety Attribute + categories associated with the generated + content. Order matches the Scores. + scores (MutableSequence[float]): + The confidence scores of the each category, + higher value means higher confidence. Order + matches the Categories. + """ + + categories: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + scores: MutableSequence[float] = proto.RepeatedField( + proto.FLOAT, + number=2, + ) + + summary_text: str = proto.Field( + proto.STRING, + number=1, + ) + summary_skipped_reasons: MutableSequence['SearchResponse.Summary.SummarySkippedReason'] = proto.RepeatedField( + proto.ENUM, + number=2, + enum='SearchResponse.Summary.SummarySkippedReason', + ) + safety_attributes: 'SearchResponse.Summary.SafetyAttributes' = proto.Field( + proto.MESSAGE, + number=3, + message='SearchResponse.Summary.SafetyAttributes', + ) + + class QueryExpansionInfo(proto.Message): + r"""Information describing query expansion including whether + expansion has occurred. + + Attributes: + expanded_query (bool): + Bool describing whether query expansion has + occurred. + pinned_result_count (int): + Number of pinned results. This field will only be set when + expansion happens and + [SearchRequest.QueryExpansionSpec.pin_unexpanded_results][google.cloud.discoveryengine.v1beta.SearchRequest.QueryExpansionSpec.pin_unexpanded_results] + is set to true. + """ + + expanded_query: bool = proto.Field( + proto.BOOL, + number=1, + ) + pinned_result_count: int = proto.Field( + proto.INT64, + number=2, + ) + + @property + def raw_page(self): + return self + + results: MutableSequence[SearchResult] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=SearchResult, + ) + facets: MutableSequence[Facet] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Facet, + ) + guided_search_result: GuidedSearchResult = proto.Field( + proto.MESSAGE, + number=8, + message=GuidedSearchResult, + ) + total_size: int = proto.Field( + proto.INT32, + number=3, + ) + attribution_token: str = proto.Field( + proto.STRING, + number=4, + ) + redirect_uri: str = proto.Field( + proto.STRING, + number=12, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=5, + ) + corrected_query: str = proto.Field( + proto.STRING, + number=7, + ) + summary: Summary = proto.Field( + proto.MESSAGE, + number=9, + message=Summary, + ) + applied_controls: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=10, + ) + query_expansion_info: QueryExpansionInfo = proto.Field( + proto.MESSAGE, + number=14, + message=QueryExpansionInfo, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/user_event.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/user_event.py new file mode 100644 index 000000000000..26f29fcf13c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/user_event.py @@ -0,0 +1,758 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import common +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1beta', + manifest={ + 'UserEvent', + 'PageInfo', + 'SearchInfo', + 'CompletionInfo', + 'TransactionInfo', + 'DocumentInfo', + 'PanelInfo', + 'MediaInfo', + }, +) + + +class UserEvent(proto.Message): + r"""UserEvent captures all metadata information Discovery Engine + API needs to know about how end users interact with customers' + website. + + Attributes: + event_type (str): + Required. User event type. Allowed values are: + + Generic values: + + - ``search``: Search for Documents. + - ``view-item``: Detailed page view of a Document. + - ``view-item-list``: View of a panel or ordered list of + Documents. + - ``view-home-page``: View of the home page. + - ``view-category-page``: View of a category page, e.g. + Home > Men > Jeans + + Retail-related values: + + - ``add-to-cart``: Add an item(s) to cart, e.g. in Retail + online shopping + - ``purchase``: Purchase an item(s) + + Media-related values: + + - ``media-play``: Start/resume watching a video, playing a + song, etc. + - ``media-complete``: Finished or stopped midway through a + video, song, etc. + user_pseudo_id (str): + Required. A unique identifier for tracking visitors. + + For example, this could be implemented with an HTTP cookie, + which should be able to uniquely identify a visitor on a + single device. This unique identifier should not change if + the visitor log in/out of the website. + + Do not set the field to the same fixed ID for different + users. This mixes the event history of those users together, + which results in degraded model quality. + + The field must be a UTF-8 encoded string with a length limit + of 128 characters. Otherwise, an ``INVALID_ARGUMENT`` error + is returned. + + The field should not contain PII or user-data. We recommend + to use Google Analytics `Client + ID `__ + for this field. + event_time (google.protobuf.timestamp_pb2.Timestamp): + Only required for + [UserEventService.ImportUserEvents][google.cloud.discoveryengine.v1beta.UserEventService.ImportUserEvents] + method. Timestamp of when the user event happened. + user_info (google.cloud.discoveryengine_v1beta.types.UserInfo): + Information about the end user. + direct_user_request (bool): + Should set to true if the request is made directly from the + end user, in which case the + [UserEvent.user_info.user_agent][google.cloud.discoveryengine.v1beta.UserInfo.user_agent] + can be populated from the HTTP request. + + This flag should be set only if the API request is made + directly from the end user such as a mobile app (and not if + a gateway or a server is processing and pushing the user + events). + + This should not be set when using the JavaScript tag in + [UserEventService.CollectUserEvent][google.cloud.discoveryengine.v1beta.UserEventService.CollectUserEvent]. + session_id (str): + A unique identifier for tracking a visitor session with a + length limit of 128 bytes. A session is an aggregation of an + end user behavior in a time span. + + A general guideline to populate the session_id: + + 1. If user has no activity for 30 min, a new session_id + should be assigned. + 2. The session_id should be unique across users, suggest use + uuid or add + [UserEvent.user_pseudo_id][google.cloud.discoveryengine.v1beta.UserEvent.user_pseudo_id] + as prefix. + page_info (google.cloud.discoveryengine_v1beta.types.PageInfo): + Page metadata such as categories and other critical + information for certain event types such as + ``view-category-page``. + attribution_token (str): + Token to attribute an API response to user action(s) to + trigger the event. + + Highly recommended for user events that are the result of + [RecommendationService.Recommend][google.cloud.discoveryengine.v1beta.RecommendationService.Recommend]. + This field enables accurate attribution of recommendation + model performance. + + The value must be one of: + + - [RecommendResponse.attribution_token][google.cloud.discoveryengine.v1beta.RecommendResponse.attribution_token] + for events that are the result of + [RecommendationService.Recommend][google.cloud.discoveryengine.v1beta.RecommendationService.Recommend]. + - [SearchResponse.attribution_token][google.cloud.discoveryengine.v1beta.SearchResponse.attribution_token] + for events that are the result of + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search]. + + This token enables us to accurately attribute page view or + conversion completion back to the event and the particular + predict response containing this clicked/purchased product. + If user clicks on product K in the recommendation results, + pass + [RecommendResponse.attribution_token][google.cloud.discoveryengine.v1beta.RecommendResponse.attribution_token] + as a URL parameter to product K's page. When recording + events on product K's page, log the + [RecommendResponse.attribution_token][google.cloud.discoveryengine.v1beta.RecommendResponse.attribution_token] + to this field. + filter (str): + The filter syntax consists of an expression language for + constructing a predicate from one or more fields of the + documents being filtered. + + One example is for ``search`` events, the associated + [SearchRequest][google.cloud.discoveryengine.v1beta.SearchRequest] + may contain a filter expression in + [SearchRequest.filter][google.cloud.discoveryengine.v1beta.SearchRequest.filter] + conforming to https://google.aip.dev/160#filtering. + + Similarly, for ``view-item-list`` events that are generated + from a [RecommendationService.RecommendRequest][], this + field may be populated directly from + [RecommendationService.RecommendRequest.filter][] conforming + to https://google.aip.dev/160#filtering. + + The value must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an ``INVALID_ARGUMENT`` + error is returned. + documents (MutableSequence[google.cloud.discoveryengine_v1beta.types.DocumentInfo]): + List of + [Document][google.cloud.discoveryengine.v1beta.Document]s + associated with this user event. + + This field is optional except for the following event types: + + - ``view-item`` + - ``add-to-cart`` + - ``purchase`` + - ``media-play`` + - ``media-complete`` + + In a ``search`` event, this field represents the documents + returned to the end user on the current page (the end user + may have not finished browsing the whole page yet). When a + new page is returned to the end user, after + pagination/filtering/ordering even for the same query, a new + ``search`` event with different + [UserEvent.documents][google.cloud.discoveryengine.v1beta.UserEvent.documents] + is desired. + panel (google.cloud.discoveryengine_v1beta.types.PanelInfo): + Panel metadata associated with this user + event. + search_info (google.cloud.discoveryengine_v1beta.types.SearchInfo): + [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] + details related to the event. + + This field should be set for ``search`` event. + completion_info (google.cloud.discoveryengine_v1beta.types.CompletionInfo): + [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1beta.CompletionService.CompleteQuery] + details related to the event. + + This field should be set for ``search`` event when + autocomplete function is enabled and the user clicks a + suggestion for search. + transaction_info (google.cloud.discoveryengine_v1beta.types.TransactionInfo): + The transaction metadata (if any) associated + with this user event. + tag_ids (MutableSequence[str]): + A list of identifiers for the independent + experiment groups this user event belongs to. + This is used to distinguish between user events + associated with different experiment setups on + the customer end. + promotion_ids (MutableSequence[str]): + The promotion IDs if this is an event + associated with promotions. Currently, this + field is restricted to at most one ID. + attributes (MutableMapping[str, google.cloud.discoveryengine_v1beta.types.CustomAttribute]): + Extra user event features to include in the recommendation + model. These attributes must NOT contain data that needs to + be parsed or processed further, e.g. JSON or other + encodings. + + If you provide custom attributes for ingested user events, + also include them in the user events that you associate with + prediction requests. Custom attribute formatting must be + consistent between imported events and events provided with + prediction requests. This lets the Discovery Engine API use + those custom attributes when training models and serving + predictions, which helps improve recommendation quality. + + This field needs to pass all below criteria, otherwise an + ``INVALID_ARGUMENT`` error is returned: + + - The key must be a UTF-8 encoded string with a length + limit of 5,000 characters. + - For text attributes, at most 400 values are allowed. + Empty values are not allowed. Each value must be a UTF-8 + encoded string with a length limit of 256 characters. + - For number attributes, at most 400 values are allowed. + + For product recommendations, an example of extra user + information is ``traffic_channel``, which is how a user + arrives at the site. Users can arrive at the site by coming + to the site directly, coming through Google search, or in + other ways. + media_info (google.cloud.discoveryengine_v1beta.types.MediaInfo): + Media-specific info. + """ + + event_type: str = proto.Field( + proto.STRING, + number=1, + ) + user_pseudo_id: str = proto.Field( + proto.STRING, + number=2, + ) + event_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + user_info: common.UserInfo = proto.Field( + proto.MESSAGE, + number=4, + message=common.UserInfo, + ) + direct_user_request: bool = proto.Field( + proto.BOOL, + number=5, + ) + session_id: str = proto.Field( + proto.STRING, + number=6, + ) + page_info: 'PageInfo' = proto.Field( + proto.MESSAGE, + number=7, + message='PageInfo', + ) + attribution_token: str = proto.Field( + proto.STRING, + number=8, + ) + filter: str = proto.Field( + proto.STRING, + number=9, + ) + documents: MutableSequence['DocumentInfo'] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message='DocumentInfo', + ) + panel: 'PanelInfo' = proto.Field( + proto.MESSAGE, + number=11, + message='PanelInfo', + ) + search_info: 'SearchInfo' = proto.Field( + proto.MESSAGE, + number=12, + message='SearchInfo', + ) + completion_info: 'CompletionInfo' = proto.Field( + proto.MESSAGE, + number=13, + message='CompletionInfo', + ) + transaction_info: 'TransactionInfo' = proto.Field( + proto.MESSAGE, + number=14, + message='TransactionInfo', + ) + tag_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=15, + ) + promotion_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=16, + ) + attributes: MutableMapping[str, common.CustomAttribute] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=17, + message=common.CustomAttribute, + ) + media_info: 'MediaInfo' = proto.Field( + proto.MESSAGE, + number=18, + message='MediaInfo', + ) + + +class PageInfo(proto.Message): + r"""Detailed page information. + + Attributes: + pageview_id (str): + A unique ID of a web page view. + + This should be kept the same for all user events triggered + from the same pageview. For example, an item detail page + view could trigger multiple events as the user is browsing + the page. The ``pageview_id`` property should be kept the + same for all these events so that they can be grouped + together properly. + + When using the client side event reporting with JavaScript + pixel and Google Tag Manager, this value is filled in + automatically. + page_category (str): + The most specific category associated with a category page. + + To represent full path of category, use '>' sign to separate + different hierarchies. If '>' is part of the category name, + please replace it with other character(s). + + Category pages include special pages such as sales or + promotions. For instance, a special sale page may have the + category hierarchy: + ``"pageCategory" : "Sales > 2017 Black Friday Deals"``. + + Required for ``view-category-page`` events. Other event + types should not set this field. Otherwise, an + ``INVALID_ARGUMENT`` error is returned. + uri (str): + Complete URL (window.location.href) of the + user's current page. + When using the client side event reporting with + JavaScript pixel and Google Tag Manager, this + value is filled in automatically. Maximum length + 5,000 characters. + referrer_uri (str): + The referrer URL of the current page. + + When using the client side event reporting with + JavaScript pixel and Google Tag Manager, this + value is filled in automatically. However, some + browser privacy restrictions may cause this + field to be empty. + """ + + pageview_id: str = proto.Field( + proto.STRING, + number=1, + ) + page_category: str = proto.Field( + proto.STRING, + number=2, + ) + uri: str = proto.Field( + proto.STRING, + number=3, + ) + referrer_uri: str = proto.Field( + proto.STRING, + number=4, + ) + + +class SearchInfo(proto.Message): + r"""Detailed search information. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + search_query (str): + The user's search query. + + See + [SearchRequest.query][google.cloud.discoveryengine.v1beta.SearchRequest.query] + for definition. + + The value must be a UTF-8 encoded string with a length limit + of 5,000 characters. Otherwise, an ``INVALID_ARGUMENT`` + error is returned. + + At least one of + [search_query][google.cloud.discoveryengine.v1beta.SearchInfo.search_query] + or + [PageInfo.page_category][google.cloud.discoveryengine.v1beta.PageInfo.page_category] + is required for ``search`` events. Other event types should + not set this field. Otherwise, an ``INVALID_ARGUMENT`` error + is returned. + order_by (str): + The order in which products are returned, if applicable. + + See + [SearchRequest.order_by][google.cloud.discoveryengine.v1beta.SearchRequest.order_by] + for definition and syntax. + + The value must be a UTF-8 encoded string with a length limit + of 1,000 characters. Otherwise, an ``INVALID_ARGUMENT`` + error is returned. + + This can only be set for ``search`` events. Other event + types should not set this field. Otherwise, an + ``INVALID_ARGUMENT`` error is returned. + offset (int): + An integer that specifies the current offset for pagination + (the 0-indexed starting location, amongst the products + deemed by the API as relevant). + + See + [SearchRequest.offset][google.cloud.discoveryengine.v1beta.SearchRequest.offset] + for definition. + + If this field is negative, an ``INVALID_ARGUMENT`` is + returned. + + This can only be set for ``search`` events. Other event + types should not set this field. Otherwise, an + ``INVALID_ARGUMENT`` error is returned. + + This field is a member of `oneof`_ ``_offset``. + """ + + search_query: str = proto.Field( + proto.STRING, + number=1, + ) + order_by: str = proto.Field( + proto.STRING, + number=2, + ) + offset: int = proto.Field( + proto.INT32, + number=3, + optional=True, + ) + + +class CompletionInfo(proto.Message): + r"""Detailed completion information including completion + attribution token and clicked completion info. + + Attributes: + selected_suggestion (str): + End user selected + [CompleteQueryResponse.QuerySuggestion.suggestion][google.cloud.discoveryengine.v1beta.CompleteQueryResponse.QuerySuggestion.suggestion]. + selected_position (int): + End user selected + [CompleteQueryResponse.QuerySuggestion.suggestion][google.cloud.discoveryengine.v1beta.CompleteQueryResponse.QuerySuggestion.suggestion] + position, starting from 0. + """ + + selected_suggestion: str = proto.Field( + proto.STRING, + number=1, + ) + selected_position: int = proto.Field( + proto.INT32, + number=2, + ) + + +class TransactionInfo(proto.Message): + r"""A transaction represents the entire purchase transaction. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + value (float): + Required. Total non-zero value associated + with the transaction. This value may include + shipping, tax, or other adjustments to the total + value that you want to include. + + This field is a member of `oneof`_ ``_value``. + currency (str): + Required. Currency code. Use three-character + ISO-4217 code. + transaction_id (str): + The transaction ID with a length limit of 128 + characters. + tax (float): + All the taxes associated with the + transaction. + + This field is a member of `oneof`_ ``_tax``. + cost (float): + All the costs associated with the products. These can be + manufacturing costs, shipping expenses not borne by the end + user, or any other costs, such that: + + - Profit = + [value][google.cloud.discoveryengine.v1beta.TransactionInfo.value] + - + [tax][google.cloud.discoveryengine.v1beta.TransactionInfo.tax] + - + [cost][google.cloud.discoveryengine.v1beta.TransactionInfo.cost] + + This field is a member of `oneof`_ ``_cost``. + discount_value (float): + The total discount(s) value applied to this transaction. + This figure should be excluded from + [TransactionInfo.value][google.cloud.discoveryengine.v1beta.TransactionInfo.value] + + For example, if a user paid + [TransactionInfo.value][google.cloud.discoveryengine.v1beta.TransactionInfo.value] + amount, then nominal (pre-discount) value of the transaction + is the sum of + [TransactionInfo.value][google.cloud.discoveryengine.v1beta.TransactionInfo.value] + and + [TransactionInfo.discount_value][google.cloud.discoveryengine.v1beta.TransactionInfo.discount_value] + + This means that profit is calculated the same way, + regardless of the discount value, and that + [TransactionInfo.discount_value][google.cloud.discoveryengine.v1beta.TransactionInfo.discount_value] + can be larger than + [TransactionInfo.value][google.cloud.discoveryengine.v1beta.TransactionInfo.value]: + + - Profit = + [value][google.cloud.discoveryengine.v1beta.TransactionInfo.value] + - + [tax][google.cloud.discoveryengine.v1beta.TransactionInfo.tax] + - + [cost][google.cloud.discoveryengine.v1beta.TransactionInfo.cost] + + This field is a member of `oneof`_ ``_discount_value``. + """ + + value: float = proto.Field( + proto.FLOAT, + number=1, + optional=True, + ) + currency: str = proto.Field( + proto.STRING, + number=2, + ) + transaction_id: str = proto.Field( + proto.STRING, + number=3, + ) + tax: float = proto.Field( + proto.FLOAT, + number=4, + optional=True, + ) + cost: float = proto.Field( + proto.FLOAT, + number=5, + optional=True, + ) + discount_value: float = proto.Field( + proto.FLOAT, + number=6, + optional=True, + ) + + +class DocumentInfo(proto.Message): + r"""Detailed document information associated with a user event. + + 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: + id (str): + The [Document][google.cloud.discoveryengine.v1beta.Document] + resource ID. + + This field is a member of `oneof`_ ``document_descriptor``. + name (str): + The [Document][google.cloud.discoveryengine.v1beta.Document] + resource full name, of the form: + ``projects/{project_id}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}/branches/{branch_id}/documents/{document_id}`` + + This field is a member of `oneof`_ ``document_descriptor``. + uri (str): + The [Document][google.cloud.discoveryengine.v1beta.Document] + URI - only allowed for website data stores. + + This field is a member of `oneof`_ ``document_descriptor``. + quantity (int): + Quantity of the Document associated with the user event. + Defaults to 1. + + For example, this field will be 2 if two quantities of the + same Document are involved in a ``add-to-cart`` event. + + Required for events of the following event types: + + - ``add-to-cart`` + - ``purchase`` + + This field is a member of `oneof`_ ``_quantity``. + promotion_ids (MutableSequence[str]): + The promotion IDs associated with this + Document. Currently, this field is restricted to + at most one ID. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + oneof='document_descriptor', + ) + name: str = proto.Field( + proto.STRING, + number=2, + oneof='document_descriptor', + ) + uri: str = proto.Field( + proto.STRING, + number=6, + oneof='document_descriptor', + ) + quantity: int = proto.Field( + proto.INT32, + number=3, + optional=True, + ) + promotion_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + + +class PanelInfo(proto.Message): + r"""Detailed panel information associated with a user event. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + panel_id (str): + Required. The panel ID. + display_name (str): + The display name of the panel. + panel_position (int): + The ordered position of the panel, if shown to the user with + other panels. If set, then + [total_panels][google.cloud.discoveryengine.v1beta.PanelInfo.total_panels] + must also be set. + + This field is a member of `oneof`_ ``_panel_position``. + total_panels (int): + The total number of panels, including this one, shown to the + user. Must be set if + [panel_position][google.cloud.discoveryengine.v1beta.PanelInfo.panel_position] + is set. + + This field is a member of `oneof`_ ``_total_panels``. + """ + + panel_id: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + panel_position: int = proto.Field( + proto.INT32, + number=4, + optional=True, + ) + total_panels: int = proto.Field( + proto.INT32, + number=5, + optional=True, + ) + + +class MediaInfo(proto.Message): + r"""Media-specific user event information. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + media_progress_duration (google.protobuf.duration_pb2.Duration): + The media progress time in seconds, if applicable. For + example, if the end user has finished 90 seconds of a + playback video, then + [MediaInfo.media_progress_duration.seconds][google.protobuf.Duration.seconds] + should be set to 90. + media_progress_percentage (float): + Media progress should be computed using only the + [media_progress_duration][google.cloud.discoveryengine.v1beta.MediaInfo.media_progress_duration] + relative to the media total length. + + This value must be between ``[0, 1.0]`` inclusive. + + If this is not a playback or the progress cannot be computed + (e.g. ongoing livestream), this field should be unset. + + This field is a member of `oneof`_ ``_media_progress_percentage``. + """ + + media_progress_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + media_progress_percentage: float = proto.Field( + proto.FLOAT, + number=2, + optional=True, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/user_event_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/user_event_service.py new file mode 100644 index 000000000000..ae2bafcd2b09 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/user_event_service.py @@ -0,0 +1,110 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.discoveryengine_v1beta.types import user_event as gcd_user_event + + +__protobuf__ = proto.module( + package='google.cloud.discoveryengine.v1beta', + manifest={ + 'WriteUserEventRequest', + 'CollectUserEventRequest', + }, +) + + +class WriteUserEventRequest(proto.Message): + r"""Request message for WriteUserEvent method. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. The parent DataStore resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. + user_event (google.cloud.discoveryengine_v1beta.types.UserEvent): + Required. User event to write. + + This field is a member of `oneof`_ ``_user_event``. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + user_event: gcd_user_event.UserEvent = proto.Field( + proto.MESSAGE, + number=2, + optional=True, + message=gcd_user_event.UserEvent, + ) + + +class CollectUserEventRequest(proto.Message): + r"""Request message for CollectUserEvent method. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. The parent DataStore resource name, such as + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. + user_event (str): + Required. URL encoded UserEvent proto with a + length limit of 2,000,000 characters. + uri (str): + The URL including cgi-parameters but + excluding the hash fragment with a length limit + of 5,000 characters. This is often more useful + than the referer URL, because many browsers only + send the domain for third-party requests. + + This field is a member of `oneof`_ ``_uri``. + ets (int): + The event timestamp in milliseconds. This + prevents browser caching of otherwise identical + get requests. The name is abbreviated to reduce + the payload bytes. + + This field is a member of `oneof`_ ``_ets``. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + user_event: str = proto.Field( + proto.STRING, + number=2, + ) + uri: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + ets: int = proto.Field( + proto.INT64, + number=4, + optional=True, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/mypy.ini b/owl-bot-staging/google-cloud-discoveryengine/v1beta/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/noxfile.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/noxfile.py new file mode 100644 index 000000000000..292cf3ef4497 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/noxfile.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.11" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/discoveryengine_v1beta/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + 'mypy', + 'types-requests', + 'types-protobuf' + ) + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==7.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_completion_service_complete_query_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_completion_service_complete_query_async.py new file mode 100644 index 000000000000..c3292d2432b8 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_completion_service_complete_query_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CompleteQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_CompletionService_CompleteQuery_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +async def sample_complete_query(): + # Create a client + client = discoveryengine_v1beta.CompletionServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.CompleteQueryRequest( + data_store="data_store_value", + query="query_value", + ) + + # Make the request + response = await client.complete_query(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_CompletionService_CompleteQuery_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_completion_service_complete_query_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_completion_service_complete_query_sync.py new file mode 100644 index 000000000000..dc9950fc9b3a --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_completion_service_complete_query_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CompleteQuery +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_CompletionService_CompleteQuery_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +def sample_complete_query(): + # Create a client + client = discoveryengine_v1beta.CompletionServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.CompleteQueryRequest( + data_store="data_store_value", + query="query_value", + ) + + # Make the request + response = client.complete_query(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_CompletionService_CompleteQuery_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_converse_conversation_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_converse_conversation_async.py new file mode 100644 index 000000000000..f9c364caab7a --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_converse_conversation_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ConverseConversation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_ConversationalSearchService_ConverseConversation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +async def sample_converse_conversation(): + # Create a client + client = discoveryengine_v1beta.ConversationalSearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ConverseConversationRequest( + name="name_value", + ) + + # Make the request + response = await client.converse_conversation(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_ConversationalSearchService_ConverseConversation_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_converse_conversation_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_converse_conversation_sync.py new file mode 100644 index 000000000000..0ca10055d668 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_converse_conversation_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ConverseConversation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_ConversationalSearchService_ConverseConversation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +def sample_converse_conversation(): + # Create a client + client = discoveryengine_v1beta.ConversationalSearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ConverseConversationRequest( + name="name_value", + ) + + # Make the request + response = client.converse_conversation(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_ConversationalSearchService_ConverseConversation_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_create_conversation_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_create_conversation_async.py new file mode 100644 index 000000000000..71813f019c97 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_create_conversation_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateConversation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_ConversationalSearchService_CreateConversation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +async def sample_create_conversation(): + # Create a client + client = discoveryengine_v1beta.ConversationalSearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.CreateConversationRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_conversation(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_ConversationalSearchService_CreateConversation_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_create_conversation_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_create_conversation_sync.py new file mode 100644 index 000000000000..1eda69c9ace4 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_create_conversation_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateConversation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_ConversationalSearchService_CreateConversation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +def sample_create_conversation(): + # Create a client + client = discoveryengine_v1beta.ConversationalSearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.CreateConversationRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_conversation(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_ConversationalSearchService_CreateConversation_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_delete_conversation_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_delete_conversation_async.py new file mode 100644 index 000000000000..b4a32a25bc03 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_delete_conversation_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteConversation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_ConversationalSearchService_DeleteConversation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +async def sample_delete_conversation(): + # Create a client + client = discoveryengine_v1beta.ConversationalSearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.DeleteConversationRequest( + name="name_value", + ) + + # Make the request + await client.delete_conversation(request=request) + + +# [END discoveryengine_v1beta_generated_ConversationalSearchService_DeleteConversation_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_delete_conversation_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_delete_conversation_sync.py new file mode 100644 index 000000000000..81456ccabed9 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_delete_conversation_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteConversation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_ConversationalSearchService_DeleteConversation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +def sample_delete_conversation(): + # Create a client + client = discoveryengine_v1beta.ConversationalSearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.DeleteConversationRequest( + name="name_value", + ) + + # Make the request + client.delete_conversation(request=request) + + +# [END discoveryengine_v1beta_generated_ConversationalSearchService_DeleteConversation_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_get_conversation_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_get_conversation_async.py new file mode 100644 index 000000000000..584182019e79 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_get_conversation_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetConversation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_ConversationalSearchService_GetConversation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +async def sample_get_conversation(): + # Create a client + client = discoveryengine_v1beta.ConversationalSearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GetConversationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_conversation(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_ConversationalSearchService_GetConversation_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_get_conversation_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_get_conversation_sync.py new file mode 100644 index 000000000000..ba1560fdc73f --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_get_conversation_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetConversation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_ConversationalSearchService_GetConversation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +def sample_get_conversation(): + # Create a client + client = discoveryengine_v1beta.ConversationalSearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GetConversationRequest( + name="name_value", + ) + + # Make the request + response = client.get_conversation(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_ConversationalSearchService_GetConversation_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_list_conversations_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_list_conversations_async.py new file mode 100644 index 000000000000..8a66f51f457e --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_list_conversations_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListConversations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_ConversationalSearchService_ListConversations_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +async def sample_list_conversations(): + # Create a client + client = discoveryengine_v1beta.ConversationalSearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ListConversationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_conversations(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END discoveryengine_v1beta_generated_ConversationalSearchService_ListConversations_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_list_conversations_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_list_conversations_sync.py new file mode 100644 index 000000000000..bd74d5aac498 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_list_conversations_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListConversations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_ConversationalSearchService_ListConversations_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +def sample_list_conversations(): + # Create a client + client = discoveryengine_v1beta.ConversationalSearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ListConversationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_conversations(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END discoveryengine_v1beta_generated_ConversationalSearchService_ListConversations_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_update_conversation_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_update_conversation_async.py new file mode 100644 index 000000000000..6a2315f983e4 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_update_conversation_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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-discoveryengine + + +# [START discoveryengine_v1beta_generated_ConversationalSearchService_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 discoveryengine_v1beta + + +async def sample_update_conversation(): + # Create a client + client = discoveryengine_v1beta.ConversationalSearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.UpdateConversationRequest( + ) + + # Make the request + response = await client.update_conversation(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_ConversationalSearchService_UpdateConversation_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_update_conversation_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_update_conversation_sync.py new file mode 100644 index 000000000000..9d7655198a12 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_update_conversation_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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-discoveryengine + + +# [START discoveryengine_v1beta_generated_ConversationalSearchService_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 discoveryengine_v1beta + + +def sample_update_conversation(): + # Create a client + client = discoveryengine_v1beta.ConversationalSearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.UpdateConversationRequest( + ) + + # Make the request + response = client.update_conversation(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_ConversationalSearchService_UpdateConversation_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_create_document_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_create_document_async.py new file mode 100644 index 000000000000..c5ad5307b7dc --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_create_document_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateDocument +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_DocumentService_CreateDocument_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +async def sample_create_document(): + # Create a client + client = discoveryengine_v1beta.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.CreateDocumentRequest( + parent="parent_value", + document_id="document_id_value", + ) + + # Make the request + response = await client.create_document(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_DocumentService_CreateDocument_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_create_document_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_create_document_sync.py new file mode 100644 index 000000000000..581b4de727d3 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_create_document_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateDocument +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_DocumentService_CreateDocument_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +def sample_create_document(): + # Create a client + client = discoveryengine_v1beta.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.CreateDocumentRequest( + parent="parent_value", + document_id="document_id_value", + ) + + # Make the request + response = client.create_document(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_DocumentService_CreateDocument_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_delete_document_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_delete_document_async.py new file mode 100644 index 000000000000..10de40428e12 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_delete_document_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteDocument +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_DocumentService_DeleteDocument_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +async def sample_delete_document(): + # Create a client + client = discoveryengine_v1beta.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.DeleteDocumentRequest( + name="name_value", + ) + + # Make the request + await client.delete_document(request=request) + + +# [END discoveryengine_v1beta_generated_DocumentService_DeleteDocument_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_delete_document_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_delete_document_sync.py new file mode 100644 index 000000000000..3c93fc37d1f0 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_delete_document_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteDocument +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_DocumentService_DeleteDocument_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +def sample_delete_document(): + # Create a client + client = discoveryengine_v1beta.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.DeleteDocumentRequest( + name="name_value", + ) + + # Make the request + client.delete_document(request=request) + + +# [END discoveryengine_v1beta_generated_DocumentService_DeleteDocument_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_get_document_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_get_document_async.py new file mode 100644 index 000000000000..5f4c88f34930 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_get_document_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDocument +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_DocumentService_GetDocument_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +async def sample_get_document(): + # Create a client + client = discoveryengine_v1beta.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GetDocumentRequest( + name="name_value", + ) + + # Make the request + response = await client.get_document(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_DocumentService_GetDocument_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_get_document_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_get_document_sync.py new file mode 100644 index 000000000000..f86f8f96daaa --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_get_document_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDocument +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_DocumentService_GetDocument_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +def sample_get_document(): + # Create a client + client = discoveryengine_v1beta.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GetDocumentRequest( + name="name_value", + ) + + # Make the request + response = client.get_document(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_DocumentService_GetDocument_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_import_documents_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_import_documents_async.py new file mode 100644 index 000000000000..948a10a23148 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_import_documents_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportDocuments +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_DocumentService_ImportDocuments_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +async def sample_import_documents(): + # Create a client + client = discoveryengine_v1beta.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ImportDocumentsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.import_documents(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_DocumentService_ImportDocuments_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_import_documents_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_import_documents_sync.py new file mode 100644 index 000000000000..2637559cffe6 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_import_documents_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportDocuments +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_DocumentService_ImportDocuments_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +def sample_import_documents(): + # Create a client + client = discoveryengine_v1beta.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ImportDocumentsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.import_documents(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_DocumentService_ImportDocuments_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_list_documents_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_list_documents_async.py new file mode 100644 index 000000000000..e90d8a1e53f9 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_list_documents_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDocuments +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_DocumentService_ListDocuments_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +async def sample_list_documents(): + # Create a client + client = discoveryengine_v1beta.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ListDocumentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_documents(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END discoveryengine_v1beta_generated_DocumentService_ListDocuments_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_list_documents_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_list_documents_sync.py new file mode 100644 index 000000000000..dca286461a3f --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_list_documents_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDocuments +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_DocumentService_ListDocuments_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +def sample_list_documents(): + # Create a client + client = discoveryengine_v1beta.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ListDocumentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_documents(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END discoveryengine_v1beta_generated_DocumentService_ListDocuments_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_purge_documents_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_purge_documents_async.py new file mode 100644 index 000000000000..7733ae956e3e --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_purge_documents_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PurgeDocuments +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_DocumentService_PurgeDocuments_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +async def sample_purge_documents(): + # Create a client + client = discoveryengine_v1beta.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.PurgeDocumentsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_documents(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_DocumentService_PurgeDocuments_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_purge_documents_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_purge_documents_sync.py new file mode 100644 index 000000000000..2ef4b0163400 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_purge_documents_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for PurgeDocuments +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_DocumentService_PurgeDocuments_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +def sample_purge_documents(): + # Create a client + client = discoveryengine_v1beta.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.PurgeDocumentsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Make the request + operation = client.purge_documents(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_DocumentService_PurgeDocuments_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_update_document_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_update_document_async.py new file mode 100644 index 000000000000..553079df811e --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_update_document_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateDocument +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_DocumentService_UpdateDocument_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +async def sample_update_document(): + # Create a client + client = discoveryengine_v1beta.DocumentServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.UpdateDocumentRequest( + ) + + # Make the request + response = await client.update_document(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_DocumentService_UpdateDocument_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_update_document_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_update_document_sync.py new file mode 100644 index 000000000000..47e00ab8eabe --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_update_document_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateDocument +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_DocumentService_UpdateDocument_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +def sample_update_document(): + # Create a client + client = discoveryengine_v1beta.DocumentServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.UpdateDocumentRequest( + ) + + # Make the request + response = client.update_document(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_DocumentService_UpdateDocument_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_recommendation_service_recommend_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_recommendation_service_recommend_async.py new file mode 100644 index 000000000000..818b8ead4440 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_recommendation_service_recommend_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Recommend +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_RecommendationService_Recommend_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +async def sample_recommend(): + # Create a client + client = discoveryengine_v1beta.RecommendationServiceAsyncClient() + + # Initialize request argument(s) + user_event = discoveryengine_v1beta.UserEvent() + user_event.event_type = "event_type_value" + user_event.user_pseudo_id = "user_pseudo_id_value" + + request = discoveryengine_v1beta.RecommendRequest( + serving_config="serving_config_value", + user_event=user_event, + ) + + # Make the request + response = await client.recommend(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_RecommendationService_Recommend_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_recommendation_service_recommend_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_recommendation_service_recommend_sync.py new file mode 100644 index 000000000000..36bcd43f7ad6 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_recommendation_service_recommend_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Recommend +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_RecommendationService_Recommend_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +def sample_recommend(): + # Create a client + client = discoveryengine_v1beta.RecommendationServiceClient() + + # Initialize request argument(s) + user_event = discoveryengine_v1beta.UserEvent() + user_event.event_type = "event_type_value" + user_event.user_pseudo_id = "user_pseudo_id_value" + + request = discoveryengine_v1beta.RecommendRequest( + serving_config="serving_config_value", + user_event=user_event, + ) + + # Make the request + response = client.recommend(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_RecommendationService_Recommend_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_create_schema_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_create_schema_async.py new file mode 100644 index 000000000000..1e44a6c60abd --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_create_schema_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_SchemaService_CreateSchema_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +async def sample_create_schema(): + # Create a client + client = discoveryengine_v1beta.SchemaServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.CreateSchemaRequest( + parent="parent_value", + schema_id="schema_id_value", + ) + + # Make the request + operation = client.create_schema(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_SchemaService_CreateSchema_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_create_schema_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_create_schema_sync.py new file mode 100644 index 000000000000..0652ba5ecc49 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_create_schema_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_SchemaService_CreateSchema_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +def sample_create_schema(): + # Create a client + client = discoveryengine_v1beta.SchemaServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.CreateSchemaRequest( + parent="parent_value", + schema_id="schema_id_value", + ) + + # Make the request + operation = client.create_schema(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_SchemaService_CreateSchema_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_delete_schema_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_delete_schema_async.py new file mode 100644 index 000000000000..a4ad35ded987 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_delete_schema_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_SchemaService_DeleteSchema_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +async def sample_delete_schema(): + # Create a client + client = discoveryengine_v1beta.SchemaServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.DeleteSchemaRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_schema(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_SchemaService_DeleteSchema_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_delete_schema_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_delete_schema_sync.py new file mode 100644 index 000000000000..8981de597436 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_delete_schema_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_SchemaService_DeleteSchema_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +def sample_delete_schema(): + # Create a client + client = discoveryengine_v1beta.SchemaServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.DeleteSchemaRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_schema(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_SchemaService_DeleteSchema_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_get_schema_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_get_schema_async.py new file mode 100644 index 000000000000..f4a57057f3fe --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_get_schema_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_SchemaService_GetSchema_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +async def sample_get_schema(): + # Create a client + client = discoveryengine_v1beta.SchemaServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GetSchemaRequest( + name="name_value", + ) + + # Make the request + response = await client.get_schema(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_SchemaService_GetSchema_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_get_schema_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_get_schema_sync.py new file mode 100644 index 000000000000..0aad48195870 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_get_schema_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_SchemaService_GetSchema_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +def sample_get_schema(): + # Create a client + client = discoveryengine_v1beta.SchemaServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.GetSchemaRequest( + name="name_value", + ) + + # Make the request + response = client.get_schema(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_SchemaService_GetSchema_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_list_schemas_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_list_schemas_async.py new file mode 100644 index 000000000000..80cd936b534c --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_list_schemas_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSchemas +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_SchemaService_ListSchemas_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +async def sample_list_schemas(): + # Create a client + client = discoveryengine_v1beta.SchemaServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ListSchemasRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_schemas(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END discoveryengine_v1beta_generated_SchemaService_ListSchemas_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_list_schemas_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_list_schemas_sync.py new file mode 100644 index 000000000000..8188c22dc744 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_list_schemas_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSchemas +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_SchemaService_ListSchemas_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +def sample_list_schemas(): + # Create a client + client = discoveryengine_v1beta.SchemaServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.ListSchemasRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_schemas(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END discoveryengine_v1beta_generated_SchemaService_ListSchemas_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_update_schema_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_update_schema_async.py new file mode 100644 index 000000000000..f525193651c9 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_update_schema_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_SchemaService_UpdateSchema_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +async def sample_update_schema(): + # Create a client + client = discoveryengine_v1beta.SchemaServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.UpdateSchemaRequest( + ) + + # Make the request + operation = client.update_schema(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_SchemaService_UpdateSchema_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_update_schema_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_update_schema_sync.py new file mode 100644 index 000000000000..e411a1f88c0e --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_update_schema_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_SchemaService_UpdateSchema_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +def sample_update_schema(): + # Create a client + client = discoveryengine_v1beta.SchemaServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.UpdateSchemaRequest( + ) + + # Make the request + operation = client.update_schema(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_SchemaService_UpdateSchema_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_search_service_search_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_search_service_search_async.py new file mode 100644 index 000000000000..acf0a5f6ee77 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_search_service_search_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Search +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_SearchService_Search_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +async def sample_search(): + # Create a client + client = discoveryengine_v1beta.SearchServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.SearchRequest( + serving_config="serving_config_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END discoveryengine_v1beta_generated_SearchService_Search_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_search_service_search_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_search_service_search_sync.py new file mode 100644 index 000000000000..d2bf3cd00472 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_search_service_search_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Search +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_SearchService_Search_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +def sample_search(): + # Create a client + client = discoveryengine_v1beta.SearchServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.SearchRequest( + serving_config="serving_config_value", + ) + + # Make the request + page_result = client.search(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END discoveryengine_v1beta_generated_SearchService_Search_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_collect_user_event_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_collect_user_event_async.py new file mode 100644 index 000000000000..eff216b60ec9 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_collect_user_event_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CollectUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_UserEventService_CollectUserEvent_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +async def sample_collect_user_event(): + # Create a client + client = discoveryengine_v1beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = await client.collect_user_event(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_UserEventService_CollectUserEvent_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_collect_user_event_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_collect_user_event_sync.py new file mode 100644 index 000000000000..ce0fa980ede5 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_collect_user_event_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CollectUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_UserEventService_CollectUserEvent_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +def sample_collect_user_event(): + # Create a client + client = discoveryengine_v1beta.UserEventServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.CollectUserEventRequest( + parent="parent_value", + user_event="user_event_value", + ) + + # Make the request + response = client.collect_user_event(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_UserEventService_CollectUserEvent_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_import_user_events_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_import_user_events_async.py new file mode 100644 index 000000000000..267845582b52 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_import_user_events_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_UserEventService_ImportUserEvents_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +async def sample_import_user_events(): + # Create a client + client = discoveryengine_v1beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + inline_source = discoveryengine_v1beta.InlineSource() + inline_source.user_events.event_type = "event_type_value" + inline_source.user_events.user_pseudo_id = "user_pseudo_id_value" + + request = discoveryengine_v1beta.ImportUserEventsRequest( + inline_source=inline_source, + parent="parent_value", + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_UserEventService_ImportUserEvents_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_import_user_events_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_import_user_events_sync.py new file mode 100644 index 000000000000..f00b3a4f695d --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_import_user_events_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportUserEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_UserEventService_ImportUserEvents_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +def sample_import_user_events(): + # Create a client + client = discoveryengine_v1beta.UserEventServiceClient() + + # Initialize request argument(s) + inline_source = discoveryengine_v1beta.InlineSource() + inline_source.user_events.event_type = "event_type_value" + inline_source.user_events.user_pseudo_id = "user_pseudo_id_value" + + request = discoveryengine_v1beta.ImportUserEventsRequest( + inline_source=inline_source, + parent="parent_value", + ) + + # Make the request + operation = client.import_user_events(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_UserEventService_ImportUserEvents_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_write_user_event_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_write_user_event_async.py new file mode 100644 index 000000000000..e3c1279f13c8 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_write_user_event_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for WriteUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_UserEventService_WriteUserEvent_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +async def sample_write_user_event(): + # Create a client + client = discoveryengine_v1beta.UserEventServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.WriteUserEventRequest( + parent="parent_value", + ) + + # Make the request + response = await client.write_user_event(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_UserEventService_WriteUserEvent_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_write_user_event_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_write_user_event_sync.py new file mode 100644 index 000000000000..0559a9f48518 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_write_user_event_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for WriteUserEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-discoveryengine + + +# [START discoveryengine_v1beta_generated_UserEventService_WriteUserEvent_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import discoveryengine_v1beta + + +def sample_write_user_event(): + # Create a client + client = discoveryengine_v1beta.UserEventServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1beta.WriteUserEventRequest( + parent="parent_value", + ) + + # Make the request + response = client.write_user_event(request=request) + + # Handle the response + print(response) + +# [END discoveryengine_v1beta_generated_UserEventService_WriteUserEvent_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1beta.json b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1beta.json new file mode 100644 index 000000000000..5ef34e5b313b --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1beta.json @@ -0,0 +1,3843 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.discoveryengine.v1beta", + "version": "v1beta" + } + ], + "language": "PYTHON", + "name": "google-cloud-discoveryengine", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.CompletionServiceAsyncClient", + "shortName": "CompletionServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.CompletionServiceAsyncClient.complete_query", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.CompletionService.CompleteQuery", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "CompleteQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.CompleteQueryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.types.CompleteQueryResponse", + "shortName": "complete_query" + }, + "description": "Sample for CompleteQuery", + "file": "discoveryengine_v1beta_generated_completion_service_complete_query_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_CompletionService_CompleteQuery_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": "discoveryengine_v1beta_generated_completion_service_complete_query_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.CompletionServiceClient", + "shortName": "CompletionServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.CompletionServiceClient.complete_query", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.CompletionService.CompleteQuery", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.CompletionService", + "shortName": "CompletionService" + }, + "shortName": "CompleteQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.CompleteQueryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.types.CompleteQueryResponse", + "shortName": "complete_query" + }, + "description": "Sample for CompleteQuery", + "file": "discoveryengine_v1beta_generated_completion_service_complete_query_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_CompletionService_CompleteQuery_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": "discoveryengine_v1beta_generated_completion_service_complete_query_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceAsyncClient", + "shortName": "ConversationalSearchServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceAsyncClient.converse_conversation", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService.ConverseConversation", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService", + "shortName": "ConversationalSearchService" + }, + "shortName": "ConverseConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.ConverseConversationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "query", + "type": "google.cloud.discoveryengine_v1beta.types.TextInput" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.types.ConverseConversationResponse", + "shortName": "converse_conversation" + }, + "description": "Sample for ConverseConversation", + "file": "discoveryengine_v1beta_generated_conversational_search_service_converse_conversation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_ConversationalSearchService_ConverseConversation_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": "discoveryengine_v1beta_generated_conversational_search_service_converse_conversation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceClient", + "shortName": "ConversationalSearchServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceClient.converse_conversation", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService.ConverseConversation", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService", + "shortName": "ConversationalSearchService" + }, + "shortName": "ConverseConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.ConverseConversationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "query", + "type": "google.cloud.discoveryengine_v1beta.types.TextInput" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.types.ConverseConversationResponse", + "shortName": "converse_conversation" + }, + "description": "Sample for ConverseConversation", + "file": "discoveryengine_v1beta_generated_conversational_search_service_converse_conversation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_ConversationalSearchService_ConverseConversation_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": "discoveryengine_v1beta_generated_conversational_search_service_converse_conversation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceAsyncClient", + "shortName": "ConversationalSearchServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceAsyncClient.create_conversation", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService.CreateConversation", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService", + "shortName": "ConversationalSearchService" + }, + "shortName": "CreateConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.CreateConversationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "conversation", + "type": "google.cloud.discoveryengine_v1beta.types.Conversation" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.types.Conversation", + "shortName": "create_conversation" + }, + "description": "Sample for CreateConversation", + "file": "discoveryengine_v1beta_generated_conversational_search_service_create_conversation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_ConversationalSearchService_CreateConversation_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": "discoveryengine_v1beta_generated_conversational_search_service_create_conversation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceClient", + "shortName": "ConversationalSearchServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceClient.create_conversation", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService.CreateConversation", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService", + "shortName": "ConversationalSearchService" + }, + "shortName": "CreateConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.CreateConversationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "conversation", + "type": "google.cloud.discoveryengine_v1beta.types.Conversation" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.types.Conversation", + "shortName": "create_conversation" + }, + "description": "Sample for CreateConversation", + "file": "discoveryengine_v1beta_generated_conversational_search_service_create_conversation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_ConversationalSearchService_CreateConversation_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": "discoveryengine_v1beta_generated_conversational_search_service_create_conversation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceAsyncClient", + "shortName": "ConversationalSearchServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceAsyncClient.delete_conversation", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService.DeleteConversation", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService", + "shortName": "ConversationalSearchService" + }, + "shortName": "DeleteConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.DeleteConversationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_conversation" + }, + "description": "Sample for DeleteConversation", + "file": "discoveryengine_v1beta_generated_conversational_search_service_delete_conversation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_ConversationalSearchService_DeleteConversation_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": "discoveryengine_v1beta_generated_conversational_search_service_delete_conversation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceClient", + "shortName": "ConversationalSearchServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceClient.delete_conversation", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService.DeleteConversation", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService", + "shortName": "ConversationalSearchService" + }, + "shortName": "DeleteConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.DeleteConversationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_conversation" + }, + "description": "Sample for DeleteConversation", + "file": "discoveryengine_v1beta_generated_conversational_search_service_delete_conversation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_ConversationalSearchService_DeleteConversation_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": "discoveryengine_v1beta_generated_conversational_search_service_delete_conversation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceAsyncClient", + "shortName": "ConversationalSearchServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceAsyncClient.get_conversation", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService.GetConversation", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService", + "shortName": "ConversationalSearchService" + }, + "shortName": "GetConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.GetConversationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.types.Conversation", + "shortName": "get_conversation" + }, + "description": "Sample for GetConversation", + "file": "discoveryengine_v1beta_generated_conversational_search_service_get_conversation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_ConversationalSearchService_GetConversation_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": "discoveryengine_v1beta_generated_conversational_search_service_get_conversation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceClient", + "shortName": "ConversationalSearchServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceClient.get_conversation", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService.GetConversation", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService", + "shortName": "ConversationalSearchService" + }, + "shortName": "GetConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.GetConversationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.types.Conversation", + "shortName": "get_conversation" + }, + "description": "Sample for GetConversation", + "file": "discoveryengine_v1beta_generated_conversational_search_service_get_conversation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_ConversationalSearchService_GetConversation_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": "discoveryengine_v1beta_generated_conversational_search_service_get_conversation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceAsyncClient", + "shortName": "ConversationalSearchServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceAsyncClient.list_conversations", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService.ListConversations", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService", + "shortName": "ConversationalSearchService" + }, + "shortName": "ListConversations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.ListConversationsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.services.conversational_search_service.pagers.ListConversationsAsyncPager", + "shortName": "list_conversations" + }, + "description": "Sample for ListConversations", + "file": "discoveryengine_v1beta_generated_conversational_search_service_list_conversations_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_ConversationalSearchService_ListConversations_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": "discoveryengine_v1beta_generated_conversational_search_service_list_conversations_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceClient", + "shortName": "ConversationalSearchServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceClient.list_conversations", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService.ListConversations", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService", + "shortName": "ConversationalSearchService" + }, + "shortName": "ListConversations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.ListConversationsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.services.conversational_search_service.pagers.ListConversationsPager", + "shortName": "list_conversations" + }, + "description": "Sample for ListConversations", + "file": "discoveryengine_v1beta_generated_conversational_search_service_list_conversations_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_ConversationalSearchService_ListConversations_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": "discoveryengine_v1beta_generated_conversational_search_service_list_conversations_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceAsyncClient", + "shortName": "ConversationalSearchServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceAsyncClient.update_conversation", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService.UpdateConversation", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService", + "shortName": "ConversationalSearchService" + }, + "shortName": "UpdateConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.UpdateConversationRequest" + }, + { + "name": "conversation", + "type": "google.cloud.discoveryengine_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, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.types.Conversation", + "shortName": "update_conversation" + }, + "description": "Sample for UpdateConversation", + "file": "discoveryengine_v1beta_generated_conversational_search_service_update_conversation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_ConversationalSearchService_UpdateConversation_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": "discoveryengine_v1beta_generated_conversational_search_service_update_conversation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceClient", + "shortName": "ConversationalSearchServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceClient.update_conversation", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService.UpdateConversation", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService", + "shortName": "ConversationalSearchService" + }, + "shortName": "UpdateConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.UpdateConversationRequest" + }, + { + "name": "conversation", + "type": "google.cloud.discoveryengine_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, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.types.Conversation", + "shortName": "update_conversation" + }, + "description": "Sample for UpdateConversation", + "file": "discoveryengine_v1beta_generated_conversational_search_service_update_conversation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_ConversationalSearchService_UpdateConversation_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": "discoveryengine_v1beta_generated_conversational_search_service_update_conversation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceAsyncClient", + "shortName": "DocumentServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceAsyncClient.create_document", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.DocumentService.CreateDocument", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "CreateDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.CreateDocumentRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "document", + "type": "google.cloud.discoveryengine_v1beta.types.Document" + }, + { + "name": "document_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.types.Document", + "shortName": "create_document" + }, + "description": "Sample for CreateDocument", + "file": "discoveryengine_v1beta_generated_document_service_create_document_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_DocumentService_CreateDocument_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": "discoveryengine_v1beta_generated_document_service_create_document_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceClient", + "shortName": "DocumentServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceClient.create_document", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.DocumentService.CreateDocument", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "CreateDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.CreateDocumentRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "document", + "type": "google.cloud.discoveryengine_v1beta.types.Document" + }, + { + "name": "document_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.types.Document", + "shortName": "create_document" + }, + "description": "Sample for CreateDocument", + "file": "discoveryengine_v1beta_generated_document_service_create_document_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_DocumentService_CreateDocument_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": "discoveryengine_v1beta_generated_document_service_create_document_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceAsyncClient", + "shortName": "DocumentServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceAsyncClient.delete_document", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.DocumentService.DeleteDocument", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "DeleteDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.DeleteDocumentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_document" + }, + "description": "Sample for DeleteDocument", + "file": "discoveryengine_v1beta_generated_document_service_delete_document_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_DocumentService_DeleteDocument_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": "discoveryengine_v1beta_generated_document_service_delete_document_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceClient", + "shortName": "DocumentServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceClient.delete_document", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.DocumentService.DeleteDocument", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "DeleteDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.DeleteDocumentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_document" + }, + "description": "Sample for DeleteDocument", + "file": "discoveryengine_v1beta_generated_document_service_delete_document_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_DocumentService_DeleteDocument_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": "discoveryengine_v1beta_generated_document_service_delete_document_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceAsyncClient", + "shortName": "DocumentServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceAsyncClient.get_document", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.DocumentService.GetDocument", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "GetDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.GetDocumentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.types.Document", + "shortName": "get_document" + }, + "description": "Sample for GetDocument", + "file": "discoveryengine_v1beta_generated_document_service_get_document_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_DocumentService_GetDocument_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": "discoveryengine_v1beta_generated_document_service_get_document_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceClient", + "shortName": "DocumentServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceClient.get_document", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.DocumentService.GetDocument", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "GetDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.GetDocumentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.types.Document", + "shortName": "get_document" + }, + "description": "Sample for GetDocument", + "file": "discoveryengine_v1beta_generated_document_service_get_document_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_DocumentService_GetDocument_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": "discoveryengine_v1beta_generated_document_service_get_document_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceAsyncClient", + "shortName": "DocumentServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceAsyncClient.import_documents", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.DocumentService.ImportDocuments", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "ImportDocuments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.ImportDocumentsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "import_documents" + }, + "description": "Sample for ImportDocuments", + "file": "discoveryengine_v1beta_generated_document_service_import_documents_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_DocumentService_ImportDocuments_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": "discoveryengine_v1beta_generated_document_service_import_documents_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceClient", + "shortName": "DocumentServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceClient.import_documents", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.DocumentService.ImportDocuments", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "ImportDocuments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.ImportDocumentsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "import_documents" + }, + "description": "Sample for ImportDocuments", + "file": "discoveryengine_v1beta_generated_document_service_import_documents_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_DocumentService_ImportDocuments_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": "discoveryengine_v1beta_generated_document_service_import_documents_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceAsyncClient", + "shortName": "DocumentServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceAsyncClient.list_documents", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.DocumentService.ListDocuments", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "ListDocuments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.ListDocumentsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.services.document_service.pagers.ListDocumentsAsyncPager", + "shortName": "list_documents" + }, + "description": "Sample for ListDocuments", + "file": "discoveryengine_v1beta_generated_document_service_list_documents_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_DocumentService_ListDocuments_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": "discoveryengine_v1beta_generated_document_service_list_documents_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceClient", + "shortName": "DocumentServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceClient.list_documents", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.DocumentService.ListDocuments", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "ListDocuments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.ListDocumentsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.services.document_service.pagers.ListDocumentsPager", + "shortName": "list_documents" + }, + "description": "Sample for ListDocuments", + "file": "discoveryengine_v1beta_generated_document_service_list_documents_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_DocumentService_ListDocuments_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": "discoveryengine_v1beta_generated_document_service_list_documents_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceAsyncClient", + "shortName": "DocumentServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceAsyncClient.purge_documents", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.DocumentService.PurgeDocuments", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "PurgeDocuments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.PurgeDocumentsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "purge_documents" + }, + "description": "Sample for PurgeDocuments", + "file": "discoveryengine_v1beta_generated_document_service_purge_documents_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_DocumentService_PurgeDocuments_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": "discoveryengine_v1beta_generated_document_service_purge_documents_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceClient", + "shortName": "DocumentServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceClient.purge_documents", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.DocumentService.PurgeDocuments", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "PurgeDocuments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.PurgeDocumentsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "purge_documents" + }, + "description": "Sample for PurgeDocuments", + "file": "discoveryengine_v1beta_generated_document_service_purge_documents_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_DocumentService_PurgeDocuments_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": "discoveryengine_v1beta_generated_document_service_purge_documents_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceAsyncClient", + "shortName": "DocumentServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceAsyncClient.update_document", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.DocumentService.UpdateDocument", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "UpdateDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.UpdateDocumentRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.types.Document", + "shortName": "update_document" + }, + "description": "Sample for UpdateDocument", + "file": "discoveryengine_v1beta_generated_document_service_update_document_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_DocumentService_UpdateDocument_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": "discoveryengine_v1beta_generated_document_service_update_document_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceClient", + "shortName": "DocumentServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceClient.update_document", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.DocumentService.UpdateDocument", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "UpdateDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.UpdateDocumentRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.types.Document", + "shortName": "update_document" + }, + "description": "Sample for UpdateDocument", + "file": "discoveryengine_v1beta_generated_document_service_update_document_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_DocumentService_UpdateDocument_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": "discoveryengine_v1beta_generated_document_service_update_document_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.RecommendationServiceAsyncClient", + "shortName": "RecommendationServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.RecommendationServiceAsyncClient.recommend", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.RecommendationService.Recommend", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.RecommendationService", + "shortName": "RecommendationService" + }, + "shortName": "Recommend" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.RecommendRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.types.RecommendResponse", + "shortName": "recommend" + }, + "description": "Sample for Recommend", + "file": "discoveryengine_v1beta_generated_recommendation_service_recommend_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_RecommendationService_Recommend_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1beta_generated_recommendation_service_recommend_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.RecommendationServiceClient", + "shortName": "RecommendationServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.RecommendationServiceClient.recommend", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.RecommendationService.Recommend", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.RecommendationService", + "shortName": "RecommendationService" + }, + "shortName": "Recommend" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.RecommendRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.types.RecommendResponse", + "shortName": "recommend" + }, + "description": "Sample for Recommend", + "file": "discoveryengine_v1beta_generated_recommendation_service_recommend_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_RecommendationService_Recommend_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1beta_generated_recommendation_service_recommend_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient", + "shortName": "SchemaServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient.create_schema", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.CreateSchema", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.SchemaService", + "shortName": "SchemaService" + }, + "shortName": "CreateSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.CreateSchemaRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "schema", + "type": "google.cloud.discoveryengine_v1beta.types.Schema" + }, + { + "name": "schema_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_schema" + }, + "description": "Sample for CreateSchema", + "file": "discoveryengine_v1beta_generated_schema_service_create_schema_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_SchemaService_CreateSchema_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": "discoveryengine_v1beta_generated_schema_service_create_schema_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient", + "shortName": "SchemaServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient.create_schema", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.CreateSchema", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.SchemaService", + "shortName": "SchemaService" + }, + "shortName": "CreateSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.CreateSchemaRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "schema", + "type": "google.cloud.discoveryengine_v1beta.types.Schema" + }, + { + "name": "schema_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_schema" + }, + "description": "Sample for CreateSchema", + "file": "discoveryengine_v1beta_generated_schema_service_create_schema_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_SchemaService_CreateSchema_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": "discoveryengine_v1beta_generated_schema_service_create_schema_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient", + "shortName": "SchemaServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient.delete_schema", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.DeleteSchema", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.SchemaService", + "shortName": "SchemaService" + }, + "shortName": "DeleteSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.DeleteSchemaRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_schema" + }, + "description": "Sample for DeleteSchema", + "file": "discoveryengine_v1beta_generated_schema_service_delete_schema_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_SchemaService_DeleteSchema_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": "discoveryengine_v1beta_generated_schema_service_delete_schema_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient", + "shortName": "SchemaServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient.delete_schema", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.DeleteSchema", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.SchemaService", + "shortName": "SchemaService" + }, + "shortName": "DeleteSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.DeleteSchemaRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_schema" + }, + "description": "Sample for DeleteSchema", + "file": "discoveryengine_v1beta_generated_schema_service_delete_schema_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_SchemaService_DeleteSchema_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": "discoveryengine_v1beta_generated_schema_service_delete_schema_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient", + "shortName": "SchemaServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient.get_schema", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.GetSchema", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.SchemaService", + "shortName": "SchemaService" + }, + "shortName": "GetSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.GetSchemaRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.types.Schema", + "shortName": "get_schema" + }, + "description": "Sample for GetSchema", + "file": "discoveryengine_v1beta_generated_schema_service_get_schema_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_SchemaService_GetSchema_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": "discoveryengine_v1beta_generated_schema_service_get_schema_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient", + "shortName": "SchemaServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient.get_schema", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.GetSchema", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.SchemaService", + "shortName": "SchemaService" + }, + "shortName": "GetSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.GetSchemaRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.types.Schema", + "shortName": "get_schema" + }, + "description": "Sample for GetSchema", + "file": "discoveryengine_v1beta_generated_schema_service_get_schema_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_SchemaService_GetSchema_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": "discoveryengine_v1beta_generated_schema_service_get_schema_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient", + "shortName": "SchemaServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient.list_schemas", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.ListSchemas", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.SchemaService", + "shortName": "SchemaService" + }, + "shortName": "ListSchemas" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.ListSchemasRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.services.schema_service.pagers.ListSchemasAsyncPager", + "shortName": "list_schemas" + }, + "description": "Sample for ListSchemas", + "file": "discoveryengine_v1beta_generated_schema_service_list_schemas_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_SchemaService_ListSchemas_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": "discoveryengine_v1beta_generated_schema_service_list_schemas_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient", + "shortName": "SchemaServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient.list_schemas", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.ListSchemas", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.SchemaService", + "shortName": "SchemaService" + }, + "shortName": "ListSchemas" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.ListSchemasRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.services.schema_service.pagers.ListSchemasPager", + "shortName": "list_schemas" + }, + "description": "Sample for ListSchemas", + "file": "discoveryengine_v1beta_generated_schema_service_list_schemas_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_SchemaService_ListSchemas_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": "discoveryengine_v1beta_generated_schema_service_list_schemas_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient", + "shortName": "SchemaServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient.update_schema", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.UpdateSchema", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.SchemaService", + "shortName": "SchemaService" + }, + "shortName": "UpdateSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.UpdateSchemaRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "update_schema" + }, + "description": "Sample for UpdateSchema", + "file": "discoveryengine_v1beta_generated_schema_service_update_schema_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_SchemaService_UpdateSchema_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1beta_generated_schema_service_update_schema_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient", + "shortName": "SchemaServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient.update_schema", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.UpdateSchema", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.SchemaService", + "shortName": "SchemaService" + }, + "shortName": "UpdateSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.UpdateSchemaRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "update_schema" + }, + "description": "Sample for UpdateSchema", + "file": "discoveryengine_v1beta_generated_schema_service_update_schema_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_SchemaService_UpdateSchema_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1beta_generated_schema_service_update_schema_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.SearchServiceAsyncClient", + "shortName": "SearchServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.SearchServiceAsyncClient.search", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.SearchService.Search", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.SearchService", + "shortName": "SearchService" + }, + "shortName": "Search" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.SearchRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.services.search_service.pagers.SearchAsyncPager", + "shortName": "search" + }, + "description": "Sample for Search", + "file": "discoveryengine_v1beta_generated_search_service_search_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_SearchService_Search_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": "discoveryengine_v1beta_generated_search_service_search_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.SearchServiceClient", + "shortName": "SearchServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.SearchServiceClient.search", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.SearchService.Search", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.SearchService", + "shortName": "SearchService" + }, + "shortName": "Search" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.SearchRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.services.search_service.pagers.SearchPager", + "shortName": "search" + }, + "description": "Sample for Search", + "file": "discoveryengine_v1beta_generated_search_service_search_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_SearchService_Search_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": "discoveryengine_v1beta_generated_search_service_search_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.UserEventServiceAsyncClient.collect_user_event", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.UserEventService.CollectUserEvent", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "CollectUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.CollectUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api.httpbody_pb2.HttpBody", + "shortName": "collect_user_event" + }, + "description": "Sample for CollectUserEvent", + "file": "discoveryengine_v1beta_generated_user_event_service_collect_user_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_UserEventService_CollectUserEvent_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": "discoveryengine_v1beta_generated_user_event_service_collect_user_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.UserEventServiceClient.collect_user_event", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.UserEventService.CollectUserEvent", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "CollectUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.CollectUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api.httpbody_pb2.HttpBody", + "shortName": "collect_user_event" + }, + "description": "Sample for CollectUserEvent", + "file": "discoveryengine_v1beta_generated_user_event_service_collect_user_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_UserEventService_CollectUserEvent_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": "discoveryengine_v1beta_generated_user_event_service_collect_user_event_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.UserEventServiceAsyncClient.import_user_events", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.UserEventService.ImportUserEvents", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "ImportUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.ImportUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "import_user_events" + }, + "description": "Sample for ImportUserEvents", + "file": "discoveryengine_v1beta_generated_user_event_service_import_user_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_UserEventService_ImportUserEvents_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": "discoveryengine_v1beta_generated_user_event_service_import_user_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.UserEventServiceClient.import_user_events", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.UserEventService.ImportUserEvents", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "ImportUserEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.ImportUserEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "import_user_events" + }, + "description": "Sample for ImportUserEvents", + "file": "discoveryengine_v1beta_generated_user_event_service_import_user_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_UserEventService_ImportUserEvents_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": "discoveryengine_v1beta_generated_user_event_service_import_user_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.UserEventServiceAsyncClient", + "shortName": "UserEventServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.UserEventServiceAsyncClient.write_user_event", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.UserEventService.WriteUserEvent", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "WriteUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.WriteUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.types.UserEvent", + "shortName": "write_user_event" + }, + "description": "Sample for WriteUserEvent", + "file": "discoveryengine_v1beta_generated_user_event_service_write_user_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_UserEventService_WriteUserEvent_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": "discoveryengine_v1beta_generated_user_event_service_write_user_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1beta.UserEventServiceClient", + "shortName": "UserEventServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1beta.UserEventServiceClient.write_user_event", + "method": { + "fullName": "google.cloud.discoveryengine.v1beta.UserEventService.WriteUserEvent", + "service": { + "fullName": "google.cloud.discoveryengine.v1beta.UserEventService", + "shortName": "UserEventService" + }, + "shortName": "WriteUserEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1beta.types.WriteUserEventRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1beta.types.UserEvent", + "shortName": "write_user_event" + }, + "description": "Sample for WriteUserEvent", + "file": "discoveryengine_v1beta_generated_user_event_service_write_user_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1beta_generated_UserEventService_WriteUserEvent_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": "discoveryengine_v1beta_generated_user_event_service_write_user_event_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/scripts/fixup_discoveryengine_v1beta_keywords.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/scripts/fixup_discoveryengine_v1beta_keywords.py new file mode 100644 index 000000000000..713ab2895836 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/scripts/fixup_discoveryengine_v1beta_keywords.py @@ -0,0 +1,199 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class discoveryengineCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'collect_user_event': ('parent', 'user_event', 'uri', 'ets', ), + 'complete_query': ('data_store', 'query', 'query_model', 'user_pseudo_id', 'include_tail_suggestions', ), + 'converse_conversation': ('name', 'query', 'serving_config', 'conversation', 'safe_search', 'user_labels', 'summary_spec', ), + 'create_conversation': ('parent', 'conversation', ), + 'create_document': ('parent', 'document', 'document_id', ), + 'create_schema': ('parent', 'schema', 'schema_id', ), + 'delete_conversation': ('name', ), + 'delete_document': ('name', ), + 'delete_schema': ('name', ), + 'get_conversation': ('name', ), + 'get_document': ('name', ), + 'get_schema': ('name', ), + 'import_documents': ('parent', 'inline_source', 'gcs_source', 'bigquery_source', 'error_config', 'reconciliation_mode', 'auto_generate_ids', 'id_field', ), + 'import_user_events': ('parent', 'inline_source', 'gcs_source', 'bigquery_source', 'error_config', ), + 'list_conversations': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_documents': ('parent', 'page_size', 'page_token', ), + 'list_schemas': ('parent', 'page_size', 'page_token', ), + 'purge_documents': ('parent', 'filter', 'force', ), + 'recommend': ('serving_config', 'user_event', 'page_size', 'filter', 'validate_only', 'params', 'user_labels', ), + 'search': ('serving_config', 'branch', 'query', 'image_query', 'page_size', 'page_token', 'offset', 'filter', 'order_by', 'user_info', 'facet_specs', 'boost_spec', 'params', 'query_expansion_spec', 'spell_correction_spec', 'user_pseudo_id', 'content_search_spec', 'embedding_spec', 'ranking_expression', 'safe_search', 'user_labels', ), + 'update_conversation': ('conversation', 'update_mask', ), + 'update_document': ('document', 'allow_missing', ), + 'update_schema': ('schema', 'allow_missing', ), + 'write_user_event': ('parent', 'user_event', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=discoveryengineCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the discoveryengine client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/setup.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/setup.py new file mode 100644 index 000000000000..513896d68575 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/setup.py @@ -0,0 +1,90 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-discoveryengine' + + +description = "Google Cloud Discoveryengine API client library" + +version = {} +with open(os.path.join(package_root, 'google/cloud/discoveryengine/gapic_version.py')) as fp: + exec(fp.read(), version) +version = version["__version__"] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + "proto-plus >= 1.22.0, <2.0.0dev", + "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", + "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +url = "https://github.com/googleapis/python-discoveryengine" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.PEP420PackageFinder.find() + if package.startswith("google") +] + +namespaces = ["google", "google.cloud"] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + namespace_packages=namespaces, + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.10.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.11.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.12.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.7.txt new file mode 100644 index 000000000000..6c44adfea7ee --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.7.txt @@ -0,0 +1,9 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.0 +proto-plus==1.22.0 +protobuf==3.19.5 diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.8.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.9.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/__init__.py new file mode 100644 index 000000000000..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/__init__.py new file mode 100644 index 000000000000..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/__init__.py new file mode 100644 index 000000000000..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_completion_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_completion_service.py new file mode 100644 index 000000000000..4c8d6b6683dc --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_completion_service.py @@ -0,0 +1,1920 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.discoveryengine_v1beta.services.completion_service import CompletionServiceAsyncClient +from google.cloud.discoveryengine_v1beta.services.completion_service import CompletionServiceClient +from google.cloud.discoveryengine_v1beta.services.completion_service import transports +from google.cloud.discoveryengine_v1beta.types import completion_service +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert CompletionServiceClient._get_default_mtls_endpoint(None) is None + assert CompletionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert CompletionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (CompletionServiceClient, "grpc"), + (CompletionServiceAsyncClient, "grpc_asyncio"), + (CompletionServiceClient, "rest"), +]) +def test_completion_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.CompletionServiceGrpcTransport, "grpc"), + (transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.CompletionServiceRestTransport, "rest"), +]) +def test_completion_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", [ + (CompletionServiceClient, "grpc"), + (CompletionServiceAsyncClient, "grpc_asyncio"), + (CompletionServiceClient, "rest"), +]) +def test_completion_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +def test_completion_service_client_get_transport_class(): + transport = CompletionServiceClient.get_transport_class() + available_transports = [ + transports.CompletionServiceGrpcTransport, + transports.CompletionServiceRestTransport, + ] + assert transport in available_transports + + transport = CompletionServiceClient.get_transport_class("grpc") + assert transport == transports.CompletionServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (CompletionServiceClient, transports.CompletionServiceRestTransport, "rest"), +]) +@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) +@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) +def test_completion_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(CompletionServiceClient, '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(CompletionServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "true"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "false"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (CompletionServiceClient, transports.CompletionServiceRestTransport, "rest", "true"), + (CompletionServiceClient, transports.CompletionServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) +@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_completion_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 + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + CompletionServiceClient, CompletionServiceAsyncClient +]) +@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) +@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) +def test_completion_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (CompletionServiceClient, transports.CompletionServiceRestTransport, "rest"), +]) +def test_completion_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, + 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", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (CompletionServiceClient, transports.CompletionServiceRestTransport, "rest", None), +]) +def test_completion_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, + scopes=None, + client_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_completion_service_client_client_options_from_dict(): + with mock.patch('google.cloud.discoveryengine_v1beta.services.completion_service.transports.CompletionServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = CompletionServiceClient( + 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", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_completion_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, + scopes=None, + client_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + completion_service.CompleteQueryRequest, + dict, +]) +def test_complete_query(request_type, transport: str = 'grpc'): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = completion_service.CompleteQueryResponse( + tail_match_triggered=True, + ) + response = client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == completion_service.CompleteQueryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, completion_service.CompleteQueryResponse) + assert response.tail_match_triggered is True + + +def test_complete_query_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + client.complete_query() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == completion_service.CompleteQueryRequest() + +@pytest.mark.asyncio +async def test_complete_query_async(transport: str = 'grpc_asyncio', request_type=completion_service.CompleteQueryRequest): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse( + tail_match_triggered=True, + )) + response = await client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == completion_service.CompleteQueryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, completion_service.CompleteQueryResponse) + assert response.tail_match_triggered is True + + +@pytest.mark.asyncio +async def test_complete_query_async_from_dict(): + await test_complete_query_async(request_type=dict) + + +def test_complete_query_field_headers(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = completion_service.CompleteQueryRequest() + + request.data_store = 'data_store_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + call.return_value = completion_service.CompleteQueryResponse() + client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'data_store=data_store_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_complete_query_field_headers_async(): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = completion_service.CompleteQueryRequest() + + request.data_store = 'data_store_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.complete_query), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse()) + await client.complete_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'data_store=data_store_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + completion_service.CompleteQueryRequest, + dict, +]) +def test_complete_query_rest(request_type): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'data_store': 'projects/sample1/locations/sample2/dataStores/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 = completion_service.CompleteQueryResponse( + tail_match_triggered=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = completion_service.CompleteQueryResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.complete_query(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, completion_service.CompleteQueryResponse) + assert response.tail_match_triggered is True + + +def test_complete_query_rest_required_fields(request_type=completion_service.CompleteQueryRequest): + transport_class = transports.CompletionServiceRestTransport + + request_init = {} + request_init["data_store"] = "" + request_init["query"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "query" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).complete_query._get_unset_required_fields(jsonified_request) + 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["dataStore"] = 'data_store_value' + jsonified_request["query"] = 'query_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).complete_query._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("include_tail_suggestions", "query", "query_model", "user_pseudo_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "dataStore" in jsonified_request + assert jsonified_request["dataStore"] == 'data_store_value' + assert "query" in jsonified_request + assert jsonified_request["query"] == 'query_value' + + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = completion_service.CompleteQueryResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = completion_service.CompleteQueryResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.complete_query(request) + + expected_params = [ + ( + "query", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_complete_query_rest_unset_required_fields(): + transport = transports.CompletionServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.complete_query._get_unset_required_fields({}) + assert set(unset_fields) == (set(("includeTailSuggestions", "query", "queryModel", "userPseudoId", )) & set(("dataStore", "query", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_complete_query_rest_interceptors(null_interceptor): + transport = transports.CompletionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.CompletionServiceRestInterceptor(), + ) + client = CompletionServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.CompletionServiceRestInterceptor, "post_complete_query") as post, \ + mock.patch.object(transports.CompletionServiceRestInterceptor, "pre_complete_query") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = completion_service.CompleteQueryRequest.pb(completion_service.CompleteQueryRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = completion_service.CompleteQueryResponse.to_json(completion_service.CompleteQueryResponse()) + + request = completion_service.CompleteQueryRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = completion_service.CompleteQueryResponse() + + client.complete_query(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_complete_query_rest_bad_request(transport: str = 'rest', request_type=completion_service.CompleteQueryRequest): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'data_store': 'projects/sample1/locations/sample2/dataStores/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.complete_query(request) + + +def test_complete_query_rest_error(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CompletionServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CompletionServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CompletionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CompletionServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, + transports.CompletionServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = CompletionServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.CompletionServiceGrpcTransport, + ) + +def test_completion_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.CompletionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_completion_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.discoveryengine_v1beta.services.completion_service.transports.CompletionServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.CompletionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'complete_query', + 'get_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_completion_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.discoveryengine_v1beta.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CompletionServiceTransport( + 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_completion_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.discoveryengine_v1beta.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CompletionServiceTransport() + adc.assert_called_once() + + +def test_completion_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) + CompletionServiceClient() + 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.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, + ], +) +def test_completion_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.CompletionServiceGrpcTransport, + transports.CompletionServiceGrpcAsyncIOTransport, + transports.CompletionServiceRestTransport, + ], +) +def test_completion_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.CompletionServiceGrpcTransport, grpc_helpers), + (transports.CompletionServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_completion_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) +def test_completion_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_completion_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.CompletionServiceRestTransport ( + 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_completion_service_host_no_port(transport_name): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_completion_service_host_with_port(transport_name): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_completion_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = CompletionServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = CompletionServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.complete_query._session + session2 = client2.transport.complete_query._session + assert session1 != session2 +def test_completion_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CompletionServiceGrpcTransport( + 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_completion_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.CompletionServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) +def test_completion_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.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) +def test_completion_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_data_store_path(): + project = "squid" + location = "clam" + data_store = "whelk" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) + actual = CompletionServiceClient.data_store_path(project, location, data_store) + assert expected == actual + + +def test_parse_data_store_path(): + expected = { + "project": "octopus", + "location": "oyster", + "data_store": "nudibranch", + } + path = CompletionServiceClient.data_store_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_data_store_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = CompletionServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = CompletionServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = CompletionServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = CompletionServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = CompletionServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = CompletionServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = CompletionServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = CompletionServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = CompletionServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = CompletionServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = CompletionServiceClient.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.CompletionServiceTransport, '_prep_wrapped_messages') as prep: + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = CompletionServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_get_operation(transport: str = "grpc"): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc"): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = CompletionServiceClient( + 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 = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc"): + client = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = CompletionServiceClient( + 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 = CompletionServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = CompletionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = CompletionServiceClient( + 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", [ + (CompletionServiceClient, transports.CompletionServiceGrpcTransport), + (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_conversational_search_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_conversational_search_service.py new file mode 100644 index 000000000000..5eab6d6bb3a0 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_conversational_search_service.py @@ -0,0 +1,4908 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.discoveryengine_v1beta.services.conversational_search_service import ConversationalSearchServiceAsyncClient +from google.cloud.discoveryengine_v1beta.services.conversational_search_service import ConversationalSearchServiceClient +from google.cloud.discoveryengine_v1beta.services.conversational_search_service import pagers +from google.cloud.discoveryengine_v1beta.services.conversational_search_service import transports +from google.cloud.discoveryengine_v1beta.types import conversation +from google.cloud.discoveryengine_v1beta.types import conversation as gcd_conversation +from google.cloud.discoveryengine_v1beta.types import conversational_search_service +from google.cloud.discoveryengine_v1beta.types import search_service +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ConversationalSearchServiceClient._get_default_mtls_endpoint(None) is None + assert ConversationalSearchServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ConversationalSearchServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ConversationalSearchServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ConversationalSearchServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ConversationalSearchServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ConversationalSearchServiceClient, "grpc"), + (ConversationalSearchServiceAsyncClient, "grpc_asyncio"), + (ConversationalSearchServiceClient, "rest"), +]) +def test_conversational_search_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ConversationalSearchServiceGrpcTransport, "grpc"), + (transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ConversationalSearchServiceRestTransport, "rest"), +]) +def test_conversational_search_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", [ + (ConversationalSearchServiceClient, "grpc"), + (ConversationalSearchServiceAsyncClient, "grpc_asyncio"), + (ConversationalSearchServiceClient, "rest"), +]) +def test_conversational_search_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +def test_conversational_search_service_client_get_transport_class(): + transport = ConversationalSearchServiceClient.get_transport_class() + available_transports = [ + transports.ConversationalSearchServiceGrpcTransport, + transports.ConversationalSearchServiceRestTransport, + ] + assert transport in available_transports + + transport = ConversationalSearchServiceClient.get_transport_class("grpc") + assert transport == transports.ConversationalSearchServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport, "grpc"), + (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (ConversationalSearchServiceClient, transports.ConversationalSearchServiceRestTransport, "rest"), +]) +@mock.patch.object(ConversationalSearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationalSearchServiceClient)) +@mock.patch.object(ConversationalSearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationalSearchServiceAsyncClient)) +def test_conversational_search_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(ConversationalSearchServiceClient, '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(ConversationalSearchServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport, "grpc", "true"), + (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport, "grpc", "false"), + (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (ConversationalSearchServiceClient, transports.ConversationalSearchServiceRestTransport, "rest", "true"), + (ConversationalSearchServiceClient, transports.ConversationalSearchServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(ConversationalSearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationalSearchServiceClient)) +@mock.patch.object(ConversationalSearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationalSearchServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_conversational_search_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 + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + ConversationalSearchServiceClient, ConversationalSearchServiceAsyncClient +]) +@mock.patch.object(ConversationalSearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationalSearchServiceClient)) +@mock.patch.object(ConversationalSearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationalSearchServiceAsyncClient)) +def test_conversational_search_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport, "grpc"), + (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (ConversationalSearchServiceClient, transports.ConversationalSearchServiceRestTransport, "rest"), +]) +def test_conversational_search_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, + 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", [ + (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport, "grpc", grpc_helpers), + (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (ConversationalSearchServiceClient, transports.ConversationalSearchServiceRestTransport, "rest", None), +]) +def test_conversational_search_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, + scopes=None, + client_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_conversational_search_service_client_client_options_from_dict(): + with mock.patch('google.cloud.discoveryengine_v1beta.services.conversational_search_service.transports.ConversationalSearchServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ConversationalSearchServiceClient( + 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", [ + (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport, "grpc", grpc_helpers), + (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_conversational_search_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, + scopes=None, + client_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + conversational_search_service.ConverseConversationRequest, + dict, +]) +def test_converse_conversation(request_type, transport: str = 'grpc'): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.converse_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversational_search_service.ConverseConversationResponse( + related_questions=['related_questions_value'], + ) + response = client.converse_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] == conversational_search_service.ConverseConversationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, conversational_search_service.ConverseConversationResponse) + assert response.related_questions == ['related_questions_value'] + + +def test_converse_conversation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.converse_conversation), + '__call__') as call: + client.converse_conversation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversational_search_service.ConverseConversationRequest() + +@pytest.mark.asyncio +async def test_converse_conversation_async(transport: str = 'grpc_asyncio', request_type=conversational_search_service.ConverseConversationRequest): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.converse_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversational_search_service.ConverseConversationResponse( + related_questions=['related_questions_value'], + )) + response = await client.converse_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == conversational_search_service.ConverseConversationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, conversational_search_service.ConverseConversationResponse) + assert response.related_questions == ['related_questions_value'] + + +@pytest.mark.asyncio +async def test_converse_conversation_async_from_dict(): + await test_converse_conversation_async(request_type=dict) + + +def test_converse_conversation_field_headers(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversational_search_service.ConverseConversationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.converse_conversation), + '__call__') as call: + call.return_value = conversational_search_service.ConverseConversationResponse() + client.converse_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', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_converse_conversation_field_headers_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversational_search_service.ConverseConversationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.converse_conversation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversational_search_service.ConverseConversationResponse()) + await client.converse_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', + 'name=name_value', + ) in kw['metadata'] + + +def test_converse_conversation_flattened(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.converse_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversational_search_service.ConverseConversationResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.converse_conversation( + name='name_value', + query=conversation.TextInput(input='input_value'), + ) + + # Establish that the 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].query + mock_val = conversation.TextInput(input='input_value') + assert arg == mock_val + + +def test_converse_conversation_flattened_error(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.converse_conversation( + conversational_search_service.ConverseConversationRequest(), + name='name_value', + query=conversation.TextInput(input='input_value'), + ) + +@pytest.mark.asyncio +async def test_converse_conversation_flattened_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.converse_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversational_search_service.ConverseConversationResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversational_search_service.ConverseConversationResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.converse_conversation( + name='name_value', + query=conversation.TextInput(input='input_value'), + ) + + # Establish that 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].query + mock_val = conversation.TextInput(input='input_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_converse_conversation_flattened_error_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.converse_conversation( + conversational_search_service.ConverseConversationRequest(), + name='name_value', + query=conversation.TextInput(input='input_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + conversational_search_service.CreateConversationRequest, + dict, +]) +def test_create_conversation(request_type, transport: str = 'grpc'): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_conversation.Conversation( + name='name_value', + state=gcd_conversation.Conversation.State.IN_PROGRESS, + user_pseudo_id='user_pseudo_id_value', + ) + response = client.create_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] == conversational_search_service.CreateConversationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_conversation.Conversation) + assert response.name == 'name_value' + assert response.state == gcd_conversation.Conversation.State.IN_PROGRESS + assert response.user_pseudo_id == 'user_pseudo_id_value' + + +def test_create_conversation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversation), + '__call__') as call: + client.create_conversation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversational_search_service.CreateConversationRequest() + +@pytest.mark.asyncio +async def test_create_conversation_async(transport: str = 'grpc_asyncio', request_type=conversational_search_service.CreateConversationRequest): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation.Conversation( + name='name_value', + state=gcd_conversation.Conversation.State.IN_PROGRESS, + user_pseudo_id='user_pseudo_id_value', + )) + response = await client.create_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == conversational_search_service.CreateConversationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_conversation.Conversation) + assert response.name == 'name_value' + assert response.state == gcd_conversation.Conversation.State.IN_PROGRESS + assert response.user_pseudo_id == 'user_pseudo_id_value' + + +@pytest.mark.asyncio +async def test_create_conversation_async_from_dict(): + await test_create_conversation_async(request_type=dict) + + +def test_create_conversation_field_headers(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversational_search_service.CreateConversationRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversation), + '__call__') as call: + call.return_value = gcd_conversation.Conversation() + client.create_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', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_conversation_field_headers_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversational_search_service.CreateConversationRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation.Conversation()) + await client.create_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', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_conversation_flattened(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_conversation.Conversation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_conversation( + parent='parent_value', + conversation=gcd_conversation.Conversation(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].conversation + mock_val = gcd_conversation.Conversation(name='name_value') + assert arg == mock_val + + +def test_create_conversation_flattened_error(): + client = ConversationalSearchServiceClient( + credentials=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_conversation( + conversational_search_service.CreateConversationRequest(), + parent='parent_value', + conversation=gcd_conversation.Conversation(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_conversation_flattened_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_conversation.Conversation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation.Conversation()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_conversation( + parent='parent_value', + conversation=gcd_conversation.Conversation(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].conversation + mock_val = gcd_conversation.Conversation(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_conversation_flattened_error_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_conversation( + conversational_search_service.CreateConversationRequest(), + parent='parent_value', + conversation=gcd_conversation.Conversation(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + conversational_search_service.DeleteConversationRequest, + dict, +]) +def test_delete_conversation(request_type, transport: str = 'grpc'): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_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] == conversational_search_service.DeleteConversationRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_conversation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversation), + '__call__') as call: + client.delete_conversation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversational_search_service.DeleteConversationRequest() + +@pytest.mark.asyncio +async def test_delete_conversation_async(transport: str = 'grpc_asyncio', request_type=conversational_search_service.DeleteConversationRequest): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == conversational_search_service.DeleteConversationRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_conversation_async_from_dict(): + await test_delete_conversation_async(request_type=dict) + + +def test_delete_conversation_field_headers(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversational_search_service.DeleteConversationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversation), + '__call__') as call: + call.return_value = None + client.delete_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', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_conversation_field_headers_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversational_search_service.DeleteConversationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_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', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_conversation_flattened(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, 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 = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_conversation( + 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_conversation_flattened_error(): + client = ConversationalSearchServiceClient( + credentials=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_conversation( + conversational_search_service.DeleteConversationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_conversation_flattened_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, 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 = 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_conversation( + 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_conversation_flattened_error_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_conversation( + conversational_search_service.DeleteConversationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + conversational_search_service.UpdateConversationRequest, + dict, +]) +def test_update_conversation(request_type, transport: str = 'grpc'): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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 = gcd_conversation.Conversation( + name='name_value', + state=gcd_conversation.Conversation.State.IN_PROGRESS, + user_pseudo_id='user_pseudo_id_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] + assert args[0] == conversational_search_service.UpdateConversationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_conversation.Conversation) + assert response.name == 'name_value' + assert response.state == gcd_conversation.Conversation.State.IN_PROGRESS + assert response.user_pseudo_id == 'user_pseudo_id_value' + + +def test_update_conversation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversation), + '__call__') as call: + client.update_conversation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversational_search_service.UpdateConversationRequest() + +@pytest.mark.asyncio +async def test_update_conversation_async(transport: str = 'grpc_asyncio', request_type=conversational_search_service.UpdateConversationRequest): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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(gcd_conversation.Conversation( + name='name_value', + state=gcd_conversation.Conversation.State.IN_PROGRESS, + user_pseudo_id='user_pseudo_id_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] + assert args[0] == conversational_search_service.UpdateConversationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_conversation.Conversation) + assert response.name == 'name_value' + assert response.state == gcd_conversation.Conversation.State.IN_PROGRESS + assert response.user_pseudo_id == 'user_pseudo_id_value' + + +@pytest.mark.asyncio +async def test_update_conversation_async_from_dict(): + await test_update_conversation_async(request_type=dict) + + +def test_update_conversation_field_headers(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversational_search_service.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 = gcd_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 = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversational_search_service.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(gcd_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 = ConversationalSearchServiceClient( + 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 = gcd_conversation.Conversation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_conversation( + conversation=gcd_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 = gcd_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 = ConversationalSearchServiceClient( + credentials=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( + conversational_search_service.UpdateConversationRequest(), + conversation=gcd_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 = ConversationalSearchServiceAsyncClient( + 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 = gcd_conversation.Conversation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_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=gcd_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 = gcd_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 = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_conversation( + conversational_search_service.UpdateConversationRequest(), + conversation=gcd_conversation.Conversation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + conversational_search_service.GetConversationRequest, + dict, +]) +def test_get_conversation(request_type, transport: str = 'grpc'): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.Conversation( + name='name_value', + state=conversation.Conversation.State.IN_PROGRESS, + user_pseudo_id='user_pseudo_id_value', + ) + response = client.get_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] == conversational_search_service.GetConversationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, conversation.Conversation) + assert response.name == 'name_value' + assert response.state == conversation.Conversation.State.IN_PROGRESS + assert response.user_pseudo_id == 'user_pseudo_id_value' + + +def test_get_conversation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversation), + '__call__') as call: + client.get_conversation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversational_search_service.GetConversationRequest() + +@pytest.mark.asyncio +async def test_get_conversation_async(transport: str = 'grpc_asyncio', request_type=conversational_search_service.GetConversationRequest): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation( + name='name_value', + state=conversation.Conversation.State.IN_PROGRESS, + user_pseudo_id='user_pseudo_id_value', + )) + response = await client.get_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == conversational_search_service.GetConversationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, conversation.Conversation) + assert response.name == 'name_value' + assert response.state == conversation.Conversation.State.IN_PROGRESS + assert response.user_pseudo_id == 'user_pseudo_id_value' + + +@pytest.mark.asyncio +async def test_get_conversation_async_from_dict(): + await test_get_conversation_async(request_type=dict) + + +def test_get_conversation_field_headers(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversational_search_service.GetConversationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversation), + '__call__') as call: + call.return_value = conversation.Conversation() + client.get_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', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_conversation_field_headers_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversational_search_service.GetConversationRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversation), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation()) + await client.get_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', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_conversation_flattened(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.Conversation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_conversation( + 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_conversation_flattened_error(): + client = ConversationalSearchServiceClient( + credentials=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_conversation( + conversational_search_service.GetConversationRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_conversation_flattened_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversation), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.Conversation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_conversation( + 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_conversation_flattened_error_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_conversation( + conversational_search_service.GetConversationRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + conversational_search_service.ListConversationsRequest, + dict, +]) +def test_list_conversations(request_type, transport: str = 'grpc'): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversational_search_service.ListConversationsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_conversations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == conversational_search_service.ListConversationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConversationsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_conversations_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + '__call__') as call: + client.list_conversations() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == conversational_search_service.ListConversationsRequest() + +@pytest.mark.asyncio +async def test_list_conversations_async(transport: str = 'grpc_asyncio', request_type=conversational_search_service.ListConversationsRequest): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversational_search_service.ListConversationsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_conversations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == conversational_search_service.ListConversationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConversationsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_conversations_async_from_dict(): + await test_list_conversations_async(request_type=dict) + + +def test_list_conversations_field_headers(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversational_search_service.ListConversationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + '__call__') as call: + call.return_value = conversational_search_service.ListConversationsResponse() + client.list_conversations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_conversations_field_headers_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = conversational_search_service.ListConversationsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversational_search_service.ListConversationsResponse()) + await client.list_conversations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_conversations_flattened(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversational_search_service.ListConversationsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_conversations( + 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_conversations_flattened_error(): + client = ConversationalSearchServiceClient( + credentials=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_conversations( + conversational_search_service.ListConversationsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_conversations_flattened_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = conversational_search_service.ListConversationsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversational_search_service.ListConversationsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_conversations( + 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_conversations_flattened_error_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_conversations( + conversational_search_service.ListConversationsRequest(), + parent='parent_value', + ) + + +def test_list_conversations_pager(transport_name: str = "grpc"): + client = ConversationalSearchServiceClient( + 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_conversations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + conversation.Conversation(), + ], + next_page_token='abc', + ), + conversational_search_service.ListConversationsResponse( + conversations=[], + next_page_token='def', + ), + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + ], + next_page_token='ghi', + ), + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_conversations(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, conversation.Conversation) + for i in results) +def test_list_conversations_pages(transport_name: str = "grpc"): + client = ConversationalSearchServiceClient( + 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_conversations), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + conversation.Conversation(), + ], + next_page_token='abc', + ), + conversational_search_service.ListConversationsResponse( + conversations=[], + next_page_token='def', + ), + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + ], + next_page_token='ghi', + ), + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + ], + ), + RuntimeError, + ) + pages = list(client.list_conversations(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_conversations_async_pager(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + conversation.Conversation(), + ], + next_page_token='abc', + ), + conversational_search_service.ListConversationsResponse( + conversations=[], + next_page_token='def', + ), + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + ], + next_page_token='ghi', + ), + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_conversations(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, conversation.Conversation) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_conversations_async_pages(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + conversation.Conversation(), + ], + next_page_token='abc', + ), + conversational_search_service.ListConversationsResponse( + conversations=[], + next_page_token='def', + ), + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + ], + next_page_token='ghi', + ), + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_conversations(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", [ + conversational_search_service.ConverseConversationRequest, + dict, +]) +def test_converse_conversation_rest(request_type): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/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 = conversational_search_service.ConverseConversationResponse( + related_questions=['related_questions_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 = conversational_search_service.ConverseConversationResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.converse_conversation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, conversational_search_service.ConverseConversationResponse) + assert response.related_questions == ['related_questions_value'] + + +def test_converse_conversation_rest_required_fields(request_type=conversational_search_service.ConverseConversationRequest): + transport_class = transports.ConversationalSearchServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).converse_conversation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).converse_conversation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = conversational_search_service.ConverseConversationResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = conversational_search_service.ConverseConversationResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.converse_conversation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_converse_conversation_rest_unset_required_fields(): + transport = transports.ConversationalSearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.converse_conversation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "query", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_converse_conversation_rest_interceptors(null_interceptor): + transport = transports.ConversationalSearchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConversationalSearchServiceRestInterceptor(), + ) + client = ConversationalSearchServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "post_converse_conversation") as post, \ + mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "pre_converse_conversation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = conversational_search_service.ConverseConversationRequest.pb(conversational_search_service.ConverseConversationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = conversational_search_service.ConverseConversationResponse.to_json(conversational_search_service.ConverseConversationResponse()) + + request = conversational_search_service.ConverseConversationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = conversational_search_service.ConverseConversationResponse() + + client.converse_conversation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_converse_conversation_rest_bad_request(transport: str = 'rest', request_type=conversational_search_service.ConverseConversationRequest): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.converse_conversation(request) + + +def test_converse_conversation_rest_flattened(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = conversational_search_service.ConverseConversationResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + query=conversation.TextInput(input='input_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 = conversational_search_service.ConverseConversationResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.converse_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/{name=projects/*/locations/*/dataStores/*/conversations/*}:converse" % client.transport._host, args[1]) + + +def test_converse_conversation_rest_flattened_error(transport: str = 'rest'): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.converse_conversation( + conversational_search_service.ConverseConversationRequest(), + name='name_value', + query=conversation.TextInput(input='input_value'), + ) + + +def test_converse_conversation_rest_error(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + conversational_search_service.CreateConversationRequest, + dict, +]) +def test_create_conversation_rest(request_type): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + request_init["conversation"] = {'name': 'name_value', 'state': 1, 'user_pseudo_id': 'user_pseudo_id_value', 'messages': [{'user_input': {'input': 'input_value', 'context': {'context_documents': ['context_documents_value1', 'context_documents_value2'], 'active_document': 'active_document_value'}}, 'reply': {'reply': 'reply_value', 'references': [{'uri': 'uri_value', 'anchor_text': 'anchor_text_value', 'start': 558, 'end': 311}], 'summary': {'summary_text': 'summary_text_value', 'summary_skipped_reasons': [1], 'safety_attributes': {'categories': ['categories_value1', 'categories_value2'], 'scores': [0.656, 0.657]}}}, 'create_time': {'seconds': 751, 'nanos': 543}}], 'start_time': {}, 'end_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 = conversational_search_service.CreateConversationRequest.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 = gcd_conversation.Conversation( + name='name_value', + state=gcd_conversation.Conversation.State.IN_PROGRESS, + user_pseudo_id='user_pseudo_id_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 = gcd_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 + response = client.create_conversation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_conversation.Conversation) + assert response.name == 'name_value' + assert response.state == gcd_conversation.Conversation.State.IN_PROGRESS + assert response.user_pseudo_id == 'user_pseudo_id_value' + + +def test_create_conversation_rest_required_fields(request_type=conversational_search_service.CreateConversationRequest): + transport_class = transports.ConversationalSearchServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_conversation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_conversation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcd_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': "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 = gcd_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 + + response = client.create_conversation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_conversation_rest_unset_required_fields(): + transport = transports.ConversationalSearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_conversation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "conversation", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_conversation_rest_interceptors(null_interceptor): + transport = transports.ConversationalSearchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConversationalSearchServiceRestInterceptor(), + ) + client = ConversationalSearchServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "post_create_conversation") as post, \ + mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "pre_create_conversation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = conversational_search_service.CreateConversationRequest.pb(conversational_search_service.CreateConversationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcd_conversation.Conversation.to_json(gcd_conversation.Conversation()) + + request = conversational_search_service.CreateConversationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcd_conversation.Conversation() + + client.create_conversation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_conversation_rest_bad_request(transport: str = 'rest', request_type=conversational_search_service.CreateConversationRequest): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_conversation(request) + + +def test_create_conversation_rest_flattened(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcd_conversation.Conversation() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + conversation=gcd_conversation.Conversation(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 = gcd_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 + + client.create_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/{parent=projects/*/locations/*/dataStores/*}/conversations" % client.transport._host, args[1]) + + +def test_create_conversation_rest_flattened_error(transport: str = 'rest'): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.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_conversation( + conversational_search_service.CreateConversationRequest(), + parent='parent_value', + conversation=gcd_conversation.Conversation(name='name_value'), + ) + + +def test_create_conversation_rest_error(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + conversational_search_service.DeleteConversationRequest, + dict, +]) +def test_delete_conversation_rest(request_type): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_conversation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_conversation_rest_required_fields(request_type=conversational_search_service.DeleteConversationRequest): + transport_class = transports.ConversationalSearchServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_conversation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_conversation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = ConversationalSearchServiceClient( + 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 + + response = client.delete_conversation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_conversation_rest_unset_required_fields(): + transport = transports.ConversationalSearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_conversation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_conversation_rest_interceptors(null_interceptor): + transport = transports.ConversationalSearchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConversationalSearchServiceRestInterceptor(), + ) + client = ConversationalSearchServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "pre_delete_conversation") as pre: + pre.assert_not_called() + pb_message = conversational_search_service.DeleteConversationRequest.pb(conversational_search_service.DeleteConversationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = conversational_search_service.DeleteConversationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_conversation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_conversation_rest_bad_request(transport: str = 'rest', request_type=conversational_search_service.DeleteConversationRequest): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_conversation(request) + + +def test_delete_conversation_rest_flattened(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/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 = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_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/{name=projects/*/locations/*/dataStores/*/conversations/*}" % client.transport._host, args[1]) + + +def test_delete_conversation_rest_flattened_error(transport: str = 'rest'): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.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_conversation( + conversational_search_service.DeleteConversationRequest(), + name='name_value', + ) + + +def test_delete_conversation_rest_error(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + conversational_search_service.UpdateConversationRequest, + dict, +]) +def test_update_conversation_rest(request_type): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'conversation': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'}} + request_init["conversation"] = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4', 'state': 1, 'user_pseudo_id': 'user_pseudo_id_value', 'messages': [{'user_input': {'input': 'input_value', 'context': {'context_documents': ['context_documents_value1', 'context_documents_value2'], 'active_document': 'active_document_value'}}, 'reply': {'reply': 'reply_value', 'references': [{'uri': 'uri_value', 'anchor_text': 'anchor_text_value', 'start': 558, 'end': 311}], 'summary': {'summary_text': 'summary_text_value', 'summary_skipped_reasons': [1], 'safety_attributes': {'categories': ['categories_value1', 'categories_value2'], 'scores': [0.656, 0.657]}}}, 'create_time': {'seconds': 751, 'nanos': 543}}], 'start_time': {}, 'end_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 = conversational_search_service.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 = gcd_conversation.Conversation( + name='name_value', + state=gcd_conversation.Conversation.State.IN_PROGRESS, + user_pseudo_id='user_pseudo_id_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 = gcd_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 + response = client.update_conversation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_conversation.Conversation) + assert response.name == 'name_value' + assert response.state == gcd_conversation.Conversation.State.IN_PROGRESS + assert response.user_pseudo_id == 'user_pseudo_id_value' + + +def test_update_conversation_rest_required_fields(request_type=conversational_search_service.UpdateConversationRequest): + transport_class = transports.ConversationalSearchServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_conversation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_conversation._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcd_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 = gcd_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 + + response = client.update_conversation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_conversation_rest_unset_required_fields(): + transport = transports.ConversationalSearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_conversation._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("conversation", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_conversation_rest_interceptors(null_interceptor): + transport = transports.ConversationalSearchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConversationalSearchServiceRestInterceptor(), + ) + client = ConversationalSearchServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "post_update_conversation") as post, \ + mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "pre_update_conversation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = conversational_search_service.UpdateConversationRequest.pb(conversational_search_service.UpdateConversationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcd_conversation.Conversation.to_json(gcd_conversation.Conversation()) + + request = conversational_search_service.UpdateConversationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcd_conversation.Conversation() + + client.update_conversation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_conversation_rest_bad_request(transport: str = 'rest', request_type=conversational_search_service.UpdateConversationRequest): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'conversation': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_conversation(request) + + +def test_update_conversation_rest_flattened(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcd_conversation.Conversation() + + # get arguments that satisfy an http rule for this method + sample_request = {'conversation': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + conversation=gcd_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 = gcd_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 + + 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/*/dataStores/*/conversations/*}" % client.transport._host, args[1]) + + +def test_update_conversation_rest_flattened_error(transport: str = 'rest'): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.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( + conversational_search_service.UpdateConversationRequest(), + conversation=gcd_conversation.Conversation(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_conversation_rest_error(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + conversational_search_service.GetConversationRequest, + dict, +]) +def test_get_conversation_rest(request_type): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/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 = conversation.Conversation( + name='name_value', + state=conversation.Conversation.State.IN_PROGRESS, + user_pseudo_id='user_pseudo_id_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 = 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 + response = client.get_conversation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, conversation.Conversation) + assert response.name == 'name_value' + assert response.state == conversation.Conversation.State.IN_PROGRESS + assert response.user_pseudo_id == 'user_pseudo_id_value' + + +def test_get_conversation_rest_required_fields(request_type=conversational_search_service.GetConversationRequest): + transport_class = transports.ConversationalSearchServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_conversation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_conversation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = 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': "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 = 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 + + response = client.get_conversation(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_conversation_rest_unset_required_fields(): + transport = transports.ConversationalSearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_conversation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_conversation_rest_interceptors(null_interceptor): + transport = transports.ConversationalSearchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConversationalSearchServiceRestInterceptor(), + ) + client = ConversationalSearchServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "post_get_conversation") as post, \ + mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "pre_get_conversation") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = conversational_search_service.GetConversationRequest.pb(conversational_search_service.GetConversationRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = conversation.Conversation.to_json(conversation.Conversation()) + + request = conversational_search_service.GetConversationRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = conversation.Conversation() + + client.get_conversation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_conversation_rest_bad_request(transport: str = 'rest', request_type=conversational_search_service.GetConversationRequest): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_conversation(request) + + +def test_get_conversation_rest_flattened(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = conversation.Conversation() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/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 = 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 + + client.get_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/{name=projects/*/locations/*/dataStores/*/conversations/*}" % client.transport._host, args[1]) + + +def test_get_conversation_rest_flattened_error(transport: str = 'rest'): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.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_conversation( + conversational_search_service.GetConversationRequest(), + name='name_value', + ) + + +def test_get_conversation_rest_error(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + conversational_search_service.ListConversationsRequest, + dict, +]) +def test_list_conversations_rest(request_type): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/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 = conversational_search_service.ListConversationsResponse( + next_page_token='next_page_token_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 = conversational_search_service.ListConversationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_conversations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConversationsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_conversations_rest_required_fields(request_type=conversational_search_service.ListConversationsRequest): + transport_class = transports.ConversationalSearchServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_conversations._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_conversations._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = conversational_search_service.ListConversationsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = conversational_search_service.ListConversationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_conversations(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_conversations_rest_unset_required_fields(): + transport = transports.ConversationalSearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_conversations._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_conversations_rest_interceptors(null_interceptor): + transport = transports.ConversationalSearchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConversationalSearchServiceRestInterceptor(), + ) + client = ConversationalSearchServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "post_list_conversations") as post, \ + mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "pre_list_conversations") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = conversational_search_service.ListConversationsRequest.pb(conversational_search_service.ListConversationsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = conversational_search_service.ListConversationsResponse.to_json(conversational_search_service.ListConversationsResponse()) + + request = conversational_search_service.ListConversationsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = conversational_search_service.ListConversationsResponse() + + client.list_conversations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_conversations_rest_bad_request(transport: str = 'rest', request_type=conversational_search_service.ListConversationsRequest): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_conversations(request) + + +def test_list_conversations_rest_flattened(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = conversational_search_service.ListConversationsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/dataStores/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 = conversational_search_service.ListConversationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_conversations(**mock_args) + + # Establish that the underlying call 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/*/dataStores/*}/conversations" % client.transport._host, args[1]) + + +def test_list_conversations_rest_flattened_error(transport: str = 'rest'): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.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_conversations( + conversational_search_service.ListConversationsRequest(), + parent='parent_value', + ) + + +def test_list_conversations_rest_pager(transport: str = 'rest'): + client = ConversationalSearchServiceClient( + 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 = ( + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + conversation.Conversation(), + ], + next_page_token='abc', + ), + conversational_search_service.ListConversationsResponse( + conversations=[], + next_page_token='def', + ), + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + ], + next_page_token='ghi', + ), + conversational_search_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(conversational_search_service.ListConversationsResponse.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/dataStores/sample3'} + + pager = client.list_conversations(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, conversation.Conversation) + for i in results) + + pages = list(client.list_conversations(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.ConversationalSearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ConversationalSearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ConversationalSearchServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ConversationalSearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ConversationalSearchServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ConversationalSearchServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ConversationalSearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ConversationalSearchServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ConversationalSearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ConversationalSearchServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ConversationalSearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ConversationalSearchServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ConversationalSearchServiceGrpcTransport, + transports.ConversationalSearchServiceGrpcAsyncIOTransport, + transports.ConversationalSearchServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = ConversationalSearchServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ConversationalSearchServiceGrpcTransport, + ) + +def test_conversational_search_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ConversationalSearchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_conversational_search_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.discoveryengine_v1beta.services.conversational_search_service.transports.ConversationalSearchServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ConversationalSearchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'converse_conversation', + 'create_conversation', + 'delete_conversation', + 'update_conversation', + 'get_conversation', + 'list_conversations', + 'get_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_conversational_search_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.discoveryengine_v1beta.services.conversational_search_service.transports.ConversationalSearchServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ConversationalSearchServiceTransport( + 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_conversational_search_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.discoveryengine_v1beta.services.conversational_search_service.transports.ConversationalSearchServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ConversationalSearchServiceTransport() + adc.assert_called_once() + + +def test_conversational_search_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) + ConversationalSearchServiceClient() + 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.ConversationalSearchServiceGrpcTransport, + transports.ConversationalSearchServiceGrpcAsyncIOTransport, + ], +) +def test_conversational_search_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.ConversationalSearchServiceGrpcTransport, + transports.ConversationalSearchServiceGrpcAsyncIOTransport, + transports.ConversationalSearchServiceRestTransport, + ], +) +def test_conversational_search_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.ConversationalSearchServiceGrpcTransport, grpc_helpers), + (transports.ConversationalSearchServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_conversational_search_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ConversationalSearchServiceGrpcTransport, transports.ConversationalSearchServiceGrpcAsyncIOTransport]) +def test_conversational_search_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_conversational_search_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.ConversationalSearchServiceRestTransport ( + 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_conversational_search_service_host_no_port(transport_name): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_conversational_search_service_host_with_port(transport_name): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_conversational_search_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ConversationalSearchServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ConversationalSearchServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.converse_conversation._session + session2 = client2.transport.converse_conversation._session + assert session1 != session2 + session1 = client1.transport.create_conversation._session + session2 = client2.transport.create_conversation._session + assert session1 != session2 + 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 + session1 = client1.transport.list_conversations._session + session2 = client2.transport.list_conversations._session + assert session1 != session2 +def test_conversational_search_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ConversationalSearchServiceGrpcTransport( + 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_conversational_search_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ConversationalSearchServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.ConversationalSearchServiceGrpcTransport, transports.ConversationalSearchServiceGrpcAsyncIOTransport]) +def test_conversational_search_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.ConversationalSearchServiceGrpcTransport, transports.ConversationalSearchServiceGrpcAsyncIOTransport]) +def test_conversational_search_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_conversation_path(): + project = "squid" + location = "clam" + data_store = "whelk" + conversation = "octopus" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/conversations/{conversation}".format(project=project, location=location, data_store=data_store, conversation=conversation, ) + actual = ConversationalSearchServiceClient.conversation_path(project, location, data_store, conversation) + assert expected == actual + + +def test_parse_conversation_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "data_store": "cuttlefish", + "conversation": "mussel", + } + path = ConversationalSearchServiceClient.conversation_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationalSearchServiceClient.parse_conversation_path(path) + assert expected == actual + +def test_data_store_path(): + project = "winkle" + location = "nautilus" + data_store = "scallop" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) + actual = ConversationalSearchServiceClient.data_store_path(project, location, data_store) + assert expected == actual + + +def test_parse_data_store_path(): + expected = { + "project": "abalone", + "location": "squid", + "data_store": "clam", + } + path = ConversationalSearchServiceClient.data_store_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationalSearchServiceClient.parse_data_store_path(path) + assert expected == actual + +def test_document_path(): + project = "whelk" + location = "octopus" + data_store = "oyster" + branch = "nudibranch" + document = "cuttlefish" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) + actual = ConversationalSearchServiceClient.document_path(project, location, data_store, branch, document) + assert expected == actual + + +def test_parse_document_path(): + expected = { + "project": "mussel", + "location": "winkle", + "data_store": "nautilus", + "branch": "scallop", + "document": "abalone", + } + path = ConversationalSearchServiceClient.document_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationalSearchServiceClient.parse_document_path(path) + assert expected == actual + +def test_serving_config_path(): + project = "squid" + location = "clam" + data_store = "whelk" + serving_config = "octopus" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/servingConfigs/{serving_config}".format(project=project, location=location, data_store=data_store, serving_config=serving_config, ) + actual = ConversationalSearchServiceClient.serving_config_path(project, location, data_store, serving_config) + assert expected == actual + + +def test_parse_serving_config_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "data_store": "cuttlefish", + "serving_config": "mussel", + } + path = ConversationalSearchServiceClient.serving_config_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationalSearchServiceClient.parse_serving_config_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ConversationalSearchServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = ConversationalSearchServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationalSearchServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format(folder=folder, ) + actual = ConversationalSearchServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = ConversationalSearchServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationalSearchServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ConversationalSearchServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = ConversationalSearchServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationalSearchServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format(project=project, ) + actual = ConversationalSearchServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = ConversationalSearchServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationalSearchServiceClient.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 = ConversationalSearchServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = ConversationalSearchServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationalSearchServiceClient.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.ConversationalSearchServiceTransport, '_prep_wrapped_messages') as prep: + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ConversationalSearchServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = ConversationalSearchServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_get_operation(transport: str = "grpc"): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc"): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = ConversationalSearchServiceClient( + 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 = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc"): + client = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = ConversationalSearchServiceClient( + 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 = ConversationalSearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ConversationalSearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = ConversationalSearchServiceClient( + 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", [ + (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport), + (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_document_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_document_service.py new file mode 100644 index 000000000000..69f92669c32a --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_document_service.py @@ -0,0 +1,4999 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.discoveryengine_v1beta.services.document_service import DocumentServiceAsyncClient +from google.cloud.discoveryengine_v1beta.services.document_service import DocumentServiceClient +from google.cloud.discoveryengine_v1beta.services.document_service import pagers +from google.cloud.discoveryengine_v1beta.services.document_service import transports +from google.cloud.discoveryengine_v1beta.types import document +from google.cloud.discoveryengine_v1beta.types import document as gcd_document +from google.cloud.discoveryengine_v1beta.types import document_service +from google.cloud.discoveryengine_v1beta.types import import_config +from google.cloud.discoveryengine_v1beta.types import purge_config +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import struct_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert DocumentServiceClient._get_default_mtls_endpoint(None) is None + assert DocumentServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert DocumentServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert DocumentServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert DocumentServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert DocumentServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (DocumentServiceClient, "grpc"), + (DocumentServiceAsyncClient, "grpc_asyncio"), + (DocumentServiceClient, "rest"), +]) +def test_document_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.DocumentServiceGrpcTransport, "grpc"), + (transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.DocumentServiceRestTransport, "rest"), +]) +def test_document_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", [ + (DocumentServiceClient, "grpc"), + (DocumentServiceAsyncClient, "grpc_asyncio"), + (DocumentServiceClient, "rest"), +]) +def test_document_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +def test_document_service_client_get_transport_class(): + transport = DocumentServiceClient.get_transport_class() + available_transports = [ + transports.DocumentServiceGrpcTransport, + transports.DocumentServiceRestTransport, + ] + assert transport in available_transports + + transport = DocumentServiceClient.get_transport_class("grpc") + assert transport == transports.DocumentServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc"), + (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (DocumentServiceClient, transports.DocumentServiceRestTransport, "rest"), +]) +@mock.patch.object(DocumentServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceClient)) +@mock.patch.object(DocumentServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceAsyncClient)) +def test_document_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(DocumentServiceClient, '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(DocumentServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc", "true"), + (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc", "false"), + (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (DocumentServiceClient, transports.DocumentServiceRestTransport, "rest", "true"), + (DocumentServiceClient, transports.DocumentServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(DocumentServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceClient)) +@mock.patch.object(DocumentServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_document_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 + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + DocumentServiceClient, DocumentServiceAsyncClient +]) +@mock.patch.object(DocumentServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceClient)) +@mock.patch.object(DocumentServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceAsyncClient)) +def test_document_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc"), + (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (DocumentServiceClient, transports.DocumentServiceRestTransport, "rest"), +]) +def test_document_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, + 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", [ + (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc", grpc_helpers), + (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (DocumentServiceClient, transports.DocumentServiceRestTransport, "rest", None), +]) +def test_document_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, + scopes=None, + client_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_document_service_client_client_options_from_dict(): + with mock.patch('google.cloud.discoveryengine_v1beta.services.document_service.transports.DocumentServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = DocumentServiceClient( + 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", [ + (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc", grpc_helpers), + (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_document_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, + scopes=None, + client_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + document_service.GetDocumentRequest, + dict, +]) +def test_get_document(request_type, transport: str = 'grpc'): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document.Document( + name='name_value', + id='id_value', + schema_id='schema_id_value', + parent_document_id='parent_document_id_value', + json_data='json_data_value', + ) + response = client.get_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.GetDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, document.Document) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.schema_id == 'schema_id_value' + assert response.parent_document_id == 'parent_document_id_value' + + +def test_get_document_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_document), + '__call__') as call: + client.get_document() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.GetDocumentRequest() + +@pytest.mark.asyncio +async def test_get_document_async(transport: str = 'grpc_asyncio', request_type=document_service.GetDocumentRequest): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document.Document( + name='name_value', + id='id_value', + schema_id='schema_id_value', + parent_document_id='parent_document_id_value', + )) + response = await client.get_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.GetDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, document.Document) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.schema_id == 'schema_id_value' + assert response.parent_document_id == 'parent_document_id_value' + + +@pytest.mark.asyncio +async def test_get_document_async_from_dict(): + await test_get_document_async(request_type=dict) + + +def test_get_document_field_headers(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_service.GetDocumentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_document), + '__call__') as call: + call.return_value = document.Document() + client.get_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_document_field_headers_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_service.GetDocumentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_document), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.Document()) + await client.get_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_document_flattened(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document.Document() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_document( + 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_document_flattened_error(): + client = DocumentServiceClient( + credentials=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_document( + document_service.GetDocumentRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_document_flattened_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document.Document() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.Document()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_document( + 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_document_flattened_error_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_document( + document_service.GetDocumentRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + document_service.ListDocumentsRequest, + dict, +]) +def test_list_documents(request_type, transport: str = 'grpc'): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_documents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_service.ListDocumentsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.ListDocumentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDocumentsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_documents_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_documents), + '__call__') as call: + client.list_documents() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.ListDocumentsRequest() + +@pytest.mark.asyncio +async def test_list_documents_async(transport: str = 'grpc_asyncio', request_type=document_service.ListDocumentsRequest): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_documents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document_service.ListDocumentsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.ListDocumentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDocumentsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_documents_async_from_dict(): + await test_list_documents_async(request_type=dict) + + +def test_list_documents_field_headers(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_service.ListDocumentsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_documents), + '__call__') as call: + call.return_value = document_service.ListDocumentsResponse() + client.list_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_documents_field_headers_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_service.ListDocumentsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_documents), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_service.ListDocumentsResponse()) + await client.list_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_documents_flattened(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_documents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_service.ListDocumentsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_documents( + 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_documents_flattened_error(): + client = DocumentServiceClient( + credentials=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_documents( + document_service.ListDocumentsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_documents_flattened_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_documents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document_service.ListDocumentsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_service.ListDocumentsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_documents( + 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_documents_flattened_error_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_documents( + document_service.ListDocumentsRequest(), + parent='parent_value', + ) + + +def test_list_documents_pager(transport_name: str = "grpc"): + client = DocumentServiceClient( + 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_documents), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + document.Document(), + ], + next_page_token='abc', + ), + document_service.ListDocumentsResponse( + documents=[], + next_page_token='def', + ), + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + ], + next_page_token='ghi', + ), + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_documents(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, document.Document) + for i in results) +def test_list_documents_pages(transport_name: str = "grpc"): + client = DocumentServiceClient( + 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_documents), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + document.Document(), + ], + next_page_token='abc', + ), + document_service.ListDocumentsResponse( + documents=[], + next_page_token='def', + ), + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + ], + next_page_token='ghi', + ), + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + ], + ), + RuntimeError, + ) + pages = list(client.list_documents(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_documents_async_pager(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_documents), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + document.Document(), + ], + next_page_token='abc', + ), + document_service.ListDocumentsResponse( + documents=[], + next_page_token='def', + ), + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + ], + next_page_token='ghi', + ), + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_documents(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, document.Document) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_documents_async_pages(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_documents), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + document.Document(), + ], + next_page_token='abc', + ), + document_service.ListDocumentsResponse( + documents=[], + next_page_token='def', + ), + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + ], + next_page_token='ghi', + ), + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_documents(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", [ + document_service.CreateDocumentRequest, + dict, +]) +def test_create_document(request_type, transport: str = 'grpc'): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_document.Document( + name='name_value', + id='id_value', + schema_id='schema_id_value', + parent_document_id='parent_document_id_value', + json_data='json_data_value', + ) + response = client.create_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.CreateDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_document.Document) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.schema_id == 'schema_id_value' + assert response.parent_document_id == 'parent_document_id_value' + + +def test_create_document_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_document), + '__call__') as call: + client.create_document() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.CreateDocumentRequest() + +@pytest.mark.asyncio +async def test_create_document_async(transport: str = 'grpc_asyncio', request_type=document_service.CreateDocumentRequest): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_document.Document( + name='name_value', + id='id_value', + schema_id='schema_id_value', + parent_document_id='parent_document_id_value', + )) + response = await client.create_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.CreateDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_document.Document) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.schema_id == 'schema_id_value' + assert response.parent_document_id == 'parent_document_id_value' + + +@pytest.mark.asyncio +async def test_create_document_async_from_dict(): + await test_create_document_async(request_type=dict) + + +def test_create_document_field_headers(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_service.CreateDocumentRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_document), + '__call__') as call: + call.return_value = gcd_document.Document() + client.create_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_document_field_headers_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_service.CreateDocumentRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_document), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_document.Document()) + await client.create_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_document_flattened(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_document.Document() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_document( + parent='parent_value', + document=gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), + document_id='document_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].document + mock_val = gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})) + assert arg == mock_val + arg = args[0].document_id + mock_val = 'document_id_value' + assert arg == mock_val + + +def test_create_document_flattened_error(): + client = DocumentServiceClient( + credentials=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_document( + document_service.CreateDocumentRequest(), + parent='parent_value', + document=gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), + document_id='document_id_value', + ) + +@pytest.mark.asyncio +async def test_create_document_flattened_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_document.Document() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_document.Document()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_document( + parent='parent_value', + document=gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), + document_id='document_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].document + mock_val = gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})) + assert arg == mock_val + arg = args[0].document_id + mock_val = 'document_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_document_flattened_error_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_document( + document_service.CreateDocumentRequest(), + parent='parent_value', + document=gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), + document_id='document_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + document_service.UpdateDocumentRequest, + dict, +]) +def test_update_document(request_type, transport: str = 'grpc'): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = document.Document( + name='name_value', + id='id_value', + schema_id='schema_id_value', + parent_document_id='parent_document_id_value', + json_data='json_data_value', + ) + response = client.update_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.UpdateDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, document.Document) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.schema_id == 'schema_id_value' + assert response.parent_document_id == 'parent_document_id_value' + + +def test_update_document_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_document), + '__call__') as call: + client.update_document() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.UpdateDocumentRequest() + +@pytest.mark.asyncio +async def test_update_document_async(transport: str = 'grpc_asyncio', request_type=document_service.UpdateDocumentRequest): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document.Document( + name='name_value', + id='id_value', + schema_id='schema_id_value', + parent_document_id='parent_document_id_value', + )) + response = await client.update_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.UpdateDocumentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, document.Document) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.schema_id == 'schema_id_value' + assert response.parent_document_id == 'parent_document_id_value' + + +@pytest.mark.asyncio +async def test_update_document_async_from_dict(): + await test_update_document_async(request_type=dict) + + +def test_update_document_field_headers(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_service.UpdateDocumentRequest() + + request.document.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_document), + '__call__') as call: + call.return_value = document.Document() + client.update_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'document.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_document_field_headers_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_service.UpdateDocumentRequest() + + request.document.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_document), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.Document()) + await client.update_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'document.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + document_service.DeleteDocumentRequest, + dict, +]) +def test_delete_document(request_type, transport: str = 'grpc'): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.DeleteDocumentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_document_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_document), + '__call__') as call: + client.delete_document() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.DeleteDocumentRequest() + +@pytest.mark.asyncio +async def test_delete_document_async(transport: str = 'grpc_asyncio', request_type=document_service.DeleteDocumentRequest): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_document), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == document_service.DeleteDocumentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_document_async_from_dict(): + await test_delete_document_async(request_type=dict) + + +def test_delete_document_field_headers(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_service.DeleteDocumentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_document), + '__call__') as call: + call.return_value = None + client.delete_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_document_field_headers_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_service.DeleteDocumentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_document), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_document(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_document_flattened(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_document), + '__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_document( + 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_document_flattened_error(): + client = DocumentServiceClient( + credentials=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_document( + document_service.DeleteDocumentRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_document_flattened_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_document), + '__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_document( + 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_document_flattened_error_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_document( + document_service.DeleteDocumentRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportDocumentsRequest, + dict, +]) +def test_import_documents(request_type, transport: str = 'grpc'): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_documents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportDocumentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_documents_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_documents), + '__call__') as call: + client.import_documents() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportDocumentsRequest() + +@pytest.mark.asyncio +async def test_import_documents_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportDocumentsRequest): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_documents), + '__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_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportDocumentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_documents_async_from_dict(): + await test_import_documents_async(request_type=dict) + + +def test_import_documents_field_headers(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportDocumentsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_documents), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_import_documents_field_headers_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportDocumentsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_documents), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + purge_config.PurgeDocumentsRequest, + dict, +]) +def test_purge_documents(request_type, transport: str = 'grpc'): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_documents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.purge_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeDocumentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_purge_documents_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_documents), + '__call__') as call: + client.purge_documents() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeDocumentsRequest() + +@pytest.mark.asyncio +async def test_purge_documents_async(transport: str = 'grpc_asyncio', request_type=purge_config.PurgeDocumentsRequest): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_documents), + '__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.purge_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == purge_config.PurgeDocumentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_purge_documents_async_from_dict(): + await test_purge_documents_async(request_type=dict) + + +def test_purge_documents_field_headers(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = purge_config.PurgeDocumentsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_documents), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.purge_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_purge_documents_field_headers_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = purge_config.PurgeDocumentsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.purge_documents), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.purge_documents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + document_service.GetDocumentRequest, + dict, +]) +def test_get_document_rest(request_type): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = document.Document( + name='name_value', + id='id_value', + schema_id='schema_id_value', + parent_document_id='parent_document_id_value', + json_data='json_data_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 = document.Document.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_document(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, document.Document) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.schema_id == 'schema_id_value' + assert response.parent_document_id == 'parent_document_id_value' + + +def test_get_document_rest_required_fields(request_type=document_service.GetDocumentRequest): + transport_class = transports.DocumentServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_document._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_document._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = document.Document() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = document.Document.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_document(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_document_rest_unset_required_fields(): + transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_document._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_document_rest_interceptors(null_interceptor): + transport = transports.DocumentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), + ) + client = DocumentServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DocumentServiceRestInterceptor, "post_get_document") as post, \ + mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_get_document") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_service.GetDocumentRequest.pb(document_service.GetDocumentRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = document.Document.to_json(document.Document()) + + request = document_service.GetDocumentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = document.Document() + + client.get_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_document_rest_bad_request(transport: str = 'rest', request_type=document_service.GetDocumentRequest): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_document(request) + + +def test_get_document_rest_flattened(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = document.Document() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = document.Document.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_document(**mock_args) + + # Establish that the underlying call 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/*/dataStores/*/branches/*/documents/*}" % client.transport._host, args[1]) + + +def test_get_document_rest_flattened_error(transport: str = 'rest'): + client = DocumentServiceClient( + credentials=ga_credentials.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_document( + document_service.GetDocumentRequest(), + name='name_value', + ) + + +def test_get_document_rest_error(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_service.ListDocumentsRequest, + dict, +]) +def test_list_documents_rest(request_type): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/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 = document_service.ListDocumentsResponse( + next_page_token='next_page_token_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 = document_service.ListDocumentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_documents(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDocumentsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_documents_rest_required_fields(request_type=document_service.ListDocumentsRequest): + transport_class = transports.DocumentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_documents._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_documents._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = document_service.ListDocumentsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = document_service.ListDocumentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_documents(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_documents_rest_unset_required_fields(): + transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_documents._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_documents_rest_interceptors(null_interceptor): + transport = transports.DocumentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), + ) + client = DocumentServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DocumentServiceRestInterceptor, "post_list_documents") as post, \ + mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_list_documents") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_service.ListDocumentsRequest.pb(document_service.ListDocumentsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = document_service.ListDocumentsResponse.to_json(document_service.ListDocumentsResponse()) + + request = document_service.ListDocumentsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = document_service.ListDocumentsResponse() + + client.list_documents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_documents_rest_bad_request(transport: str = 'rest', request_type=document_service.ListDocumentsRequest): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_documents(request) + + +def test_list_documents_rest_flattened(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = document_service.ListDocumentsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = document_service.ListDocumentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_documents(**mock_args) + + # Establish that the underlying call 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/*/dataStores/*/branches/*}/documents" % client.transport._host, args[1]) + + +def test_list_documents_rest_flattened_error(transport: str = 'rest'): + client = DocumentServiceClient( + credentials=ga_credentials.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_documents( + document_service.ListDocumentsRequest(), + parent='parent_value', + ) + + +def test_list_documents_rest_pager(transport: str = 'rest'): + client = DocumentServiceClient( + 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 = ( + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + document.Document(), + ], + next_page_token='abc', + ), + document_service.ListDocumentsResponse( + documents=[], + next_page_token='def', + ), + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + ], + next_page_token='ghi', + ), + document_service.ListDocumentsResponse( + documents=[ + document.Document(), + document.Document(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(document_service.ListDocumentsResponse.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/dataStores/sample3/branches/sample4'} + + pager = client.list_documents(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, document.Document) + for i in results) + + pages = list(client.list_documents(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + document_service.CreateDocumentRequest, + dict, +]) +def test_create_document_rest(request_type): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} + request_init["document"] = {'struct_data': {'fields': {}}, 'json_data': 'json_data_value', 'name': 'name_value', 'id': 'id_value', 'schema_id': 'schema_id_value', 'content': {'raw_bytes': b'raw_bytes_blob', 'uri': 'uri_value', 'mime_type': 'mime_type_value'}, 'parent_document_id': 'parent_document_id_value', 'derived_struct_data': {}} + # 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 = document_service.CreateDocumentRequest.meta.fields["document"] + + 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["document"].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["document"][field])): + del request_init["document"][field][i][subfield] + else: + del request_init["document"][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 = gcd_document.Document( + name='name_value', + id='id_value', + schema_id='schema_id_value', + parent_document_id='parent_document_id_value', + json_data='json_data_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 = gcd_document.Document.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_document(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_document.Document) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.schema_id == 'schema_id_value' + assert response.parent_document_id == 'parent_document_id_value' + + +def test_create_document_rest_required_fields(request_type=document_service.CreateDocumentRequest): + transport_class = transports.DocumentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["document_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "documentId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_document._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "documentId" in jsonified_request + assert jsonified_request["documentId"] == request_init["document_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["documentId"] = 'document_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_document._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("document_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "documentId" in jsonified_request + assert jsonified_request["documentId"] == 'document_id_value' + + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcd_document.Document() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = gcd_document.Document.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_document(request) + + expected_params = [ + ( + "documentId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_document_rest_unset_required_fields(): + transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_document._get_unset_required_fields({}) + assert set(unset_fields) == (set(("documentId", )) & set(("parent", "document", "documentId", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_document_rest_interceptors(null_interceptor): + transport = transports.DocumentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), + ) + client = DocumentServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DocumentServiceRestInterceptor, "post_create_document") as post, \ + mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_create_document") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_service.CreateDocumentRequest.pb(document_service.CreateDocumentRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = gcd_document.Document.to_json(gcd_document.Document()) + + request = document_service.CreateDocumentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcd_document.Document() + + client.create_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_document_rest_bad_request(transport: str = 'rest', request_type=document_service.CreateDocumentRequest): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_document(request) + + +def test_create_document_rest_flattened(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = gcd_document.Document() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + document=gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), + document_id='document_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 = gcd_document.Document.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_document(**mock_args) + + # Establish that the underlying call 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/*/dataStores/*/branches/*}/documents" % client.transport._host, args[1]) + + +def test_create_document_rest_flattened_error(transport: str = 'rest'): + client = DocumentServiceClient( + credentials=ga_credentials.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_document( + document_service.CreateDocumentRequest(), + parent='parent_value', + document=gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), + document_id='document_id_value', + ) + + +def test_create_document_rest_error(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_service.UpdateDocumentRequest, + dict, +]) +def test_update_document_rest(request_type): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'document': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'}} + request_init["document"] = {'struct_data': {'fields': {}}, 'json_data': 'json_data_value', 'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5', 'id': 'id_value', 'schema_id': 'schema_id_value', 'content': {'raw_bytes': b'raw_bytes_blob', 'uri': 'uri_value', 'mime_type': 'mime_type_value'}, 'parent_document_id': 'parent_document_id_value', 'derived_struct_data': {}} + # 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 = document_service.UpdateDocumentRequest.meta.fields["document"] + + 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["document"].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["document"][field])): + del request_init["document"][field][i][subfield] + else: + del request_init["document"][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 = document.Document( + name='name_value', + id='id_value', + schema_id='schema_id_value', + parent_document_id='parent_document_id_value', + json_data='json_data_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 = document.Document.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_document(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, document.Document) + assert response.name == 'name_value' + assert response.id == 'id_value' + assert response.schema_id == 'schema_id_value' + assert response.parent_document_id == 'parent_document_id_value' + + +def test_update_document_rest_required_fields(request_type=document_service.UpdateDocumentRequest): + transport_class = transports.DocumentServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_document._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_document._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = document.Document() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = document.Document.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_document(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_document_rest_unset_required_fields(): + transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_document._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", )) & set(("document", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_document_rest_interceptors(null_interceptor): + transport = transports.DocumentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), + ) + client = DocumentServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DocumentServiceRestInterceptor, "post_update_document") as post, \ + mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_update_document") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = document_service.UpdateDocumentRequest.pb(document_service.UpdateDocumentRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = document.Document.to_json(document.Document()) + + request = document_service.UpdateDocumentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = document.Document() + + client.update_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_document_rest_bad_request(transport: str = 'rest', request_type=document_service.UpdateDocumentRequest): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'document': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_document(request) + + +def test_update_document_rest_error(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + document_service.DeleteDocumentRequest, + dict, +]) +def test_delete_document_rest(request_type): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_document(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_document_rest_required_fields(request_type=document_service.DeleteDocumentRequest): + transport_class = transports.DocumentServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_document._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_document._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = DocumentServiceClient( + 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 + + response = client.delete_document(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_document_rest_unset_required_fields(): + transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_document._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_document_rest_interceptors(null_interceptor): + transport = transports.DocumentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), + ) + client = DocumentServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_delete_document") as pre: + pre.assert_not_called() + pb_message = document_service.DeleteDocumentRequest.pb(document_service.DeleteDocumentRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = document_service.DeleteDocumentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_document_rest_bad_request(transport: str = 'rest', request_type=document_service.DeleteDocumentRequest): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_document(request) + + +def test_delete_document_rest_flattened(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and 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': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_document(**mock_args) + + # Establish that the underlying call 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/*/dataStores/*/branches/*/documents/*}" % client.transport._host, args[1]) + + +def test_delete_document_rest_flattened_error(transport: str = 'rest'): + client = DocumentServiceClient( + credentials=ga_credentials.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_document( + document_service.DeleteDocumentRequest(), + name='name_value', + ) + + +def test_delete_document_rest_error(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportDocumentsRequest, + dict, +]) +def test_import_documents_rest(request_type): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.import_documents(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_import_documents_rest_required_fields(request_type=import_config.ImportDocumentsRequest): + transport_class = transports.DocumentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_documents._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_documents._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.import_documents(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_import_documents_rest_unset_required_fields(): + transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.import_documents._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_import_documents_rest_interceptors(null_interceptor): + transport = transports.DocumentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), + ) + client = DocumentServiceClient(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.DocumentServiceRestInterceptor, "post_import_documents") as post, \ + mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_import_documents") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = import_config.ImportDocumentsRequest.pb(import_config.ImportDocumentsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = import_config.ImportDocumentsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.import_documents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_import_documents_rest_bad_request(transport: str = 'rest', request_type=import_config.ImportDocumentsRequest): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.import_documents(request) + + +def test_import_documents_rest_error(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + purge_config.PurgeDocumentsRequest, + dict, +]) +def test_purge_documents_rest(request_type): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.purge_documents(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_purge_documents_rest_required_fields(request_type=purge_config.PurgeDocumentsRequest): + transport_class = transports.DocumentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["filter"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).purge_documents._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + jsonified_request["filter"] = 'filter_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).purge_documents._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "filter" in jsonified_request + assert jsonified_request["filter"] == 'filter_value' + + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.purge_documents(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_purge_documents_rest_unset_required_fields(): + transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.purge_documents._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "filter", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_purge_documents_rest_interceptors(null_interceptor): + transport = transports.DocumentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), + ) + client = DocumentServiceClient(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.DocumentServiceRestInterceptor, "post_purge_documents") as post, \ + mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_purge_documents") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = purge_config.PurgeDocumentsRequest.pb(purge_config.PurgeDocumentsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = purge_config.PurgeDocumentsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.purge_documents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_purge_documents_rest_bad_request(transport: str = 'rest', request_type=purge_config.PurgeDocumentsRequest): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.purge_documents(request) + + +def test_purge_documents_rest_error(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.DocumentServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.DocumentServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DocumentServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.DocumentServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DocumentServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DocumentServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.DocumentServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DocumentServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.DocumentServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = DocumentServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.DocumentServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.DocumentServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.DocumentServiceGrpcTransport, + transports.DocumentServiceGrpcAsyncIOTransport, + transports.DocumentServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = DocumentServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.DocumentServiceGrpcTransport, + ) + +def test_document_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.DocumentServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_document_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.discoveryengine_v1beta.services.document_service.transports.DocumentServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.DocumentServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_document', + 'list_documents', + 'create_document', + 'update_document', + 'delete_document', + 'import_documents', + 'purge_documents', + 'get_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_document_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.discoveryengine_v1beta.services.document_service.transports.DocumentServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DocumentServiceTransport( + 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_document_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.discoveryengine_v1beta.services.document_service.transports.DocumentServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.DocumentServiceTransport() + adc.assert_called_once() + + +def test_document_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) + DocumentServiceClient() + 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.DocumentServiceGrpcTransport, + transports.DocumentServiceGrpcAsyncIOTransport, + ], +) +def test_document_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.DocumentServiceGrpcTransport, + transports.DocumentServiceGrpcAsyncIOTransport, + transports.DocumentServiceRestTransport, + ], +) +def test_document_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.DocumentServiceGrpcTransport, grpc_helpers), + (transports.DocumentServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_document_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.DocumentServiceGrpcTransport, transports.DocumentServiceGrpcAsyncIOTransport]) +def test_document_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_document_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.DocumentServiceRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_document_service_rest_lro_client(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_document_service_host_no_port(transport_name): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_document_service_host_with_port(transport_name): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_document_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = DocumentServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = DocumentServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_document._session + session2 = client2.transport.get_document._session + assert session1 != session2 + session1 = client1.transport.list_documents._session + session2 = client2.transport.list_documents._session + assert session1 != session2 + session1 = client1.transport.create_document._session + session2 = client2.transport.create_document._session + assert session1 != session2 + session1 = client1.transport.update_document._session + session2 = client2.transport.update_document._session + assert session1 != session2 + session1 = client1.transport.delete_document._session + session2 = client2.transport.delete_document._session + assert session1 != session2 + session1 = client1.transport.import_documents._session + session2 = client2.transport.import_documents._session + assert session1 != session2 + session1 = client1.transport.purge_documents._session + session2 = client2.transport.purge_documents._session + assert session1 != session2 +def test_document_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DocumentServiceGrpcTransport( + 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_document_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.DocumentServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.DocumentServiceGrpcTransport, transports.DocumentServiceGrpcAsyncIOTransport]) +def test_document_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.DocumentServiceGrpcTransport, transports.DocumentServiceGrpcAsyncIOTransport]) +def test_document_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_document_service_grpc_lro_client(): + client = DocumentServiceClient( + 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_document_service_grpc_lro_async_client(): + client = DocumentServiceAsyncClient( + 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_branch_path(): + project = "squid" + location = "clam" + data_store = "whelk" + branch = "octopus" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}".format(project=project, location=location, data_store=data_store, branch=branch, ) + actual = DocumentServiceClient.branch_path(project, location, data_store, branch) + assert expected == actual + + +def test_parse_branch_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "data_store": "cuttlefish", + "branch": "mussel", + } + path = DocumentServiceClient.branch_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentServiceClient.parse_branch_path(path) + assert expected == actual + +def test_document_path(): + project = "winkle" + location = "nautilus" + data_store = "scallop" + branch = "abalone" + document = "squid" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) + actual = DocumentServiceClient.document_path(project, location, data_store, branch, document) + assert expected == actual + + +def test_parse_document_path(): + expected = { + "project": "clam", + "location": "whelk", + "data_store": "octopus", + "branch": "oyster", + "document": "nudibranch", + } + path = DocumentServiceClient.document_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentServiceClient.parse_document_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = DocumentServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = DocumentServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = DocumentServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = DocumentServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = DocumentServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = DocumentServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = DocumentServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = DocumentServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = DocumentServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = DocumentServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentServiceClient.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.DocumentServiceTransport, '_prep_wrapped_messages') as prep: + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.DocumentServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = DocumentServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_get_operation(transport: str = "grpc"): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc"): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DocumentServiceClient( + 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 = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc"): + client = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = DocumentServiceClient( + 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 = DocumentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = DocumentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = DocumentServiceClient( + 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", [ + (DocumentServiceClient, transports.DocumentServiceGrpcTransport), + (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_recommendation_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_recommendation_service.py new file mode 100644 index 000000000000..82e0f7234c14 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_recommendation_service.py @@ -0,0 +1,1952 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.discoveryengine_v1beta.services.recommendation_service import RecommendationServiceAsyncClient +from google.cloud.discoveryengine_v1beta.services.recommendation_service import RecommendationServiceClient +from google.cloud.discoveryengine_v1beta.services.recommendation_service import transports +from google.cloud.discoveryengine_v1beta.types import common +from google.cloud.discoveryengine_v1beta.types import recommendation_service +from google.cloud.discoveryengine_v1beta.types import user_event +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert RecommendationServiceClient._get_default_mtls_endpoint(None) is None + assert RecommendationServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert RecommendationServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert RecommendationServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert RecommendationServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert RecommendationServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (RecommendationServiceClient, "grpc"), + (RecommendationServiceAsyncClient, "grpc_asyncio"), + (RecommendationServiceClient, "rest"), +]) +def test_recommendation_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.RecommendationServiceGrpcTransport, "grpc"), + (transports.RecommendationServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.RecommendationServiceRestTransport, "rest"), +]) +def test_recommendation_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", [ + (RecommendationServiceClient, "grpc"), + (RecommendationServiceAsyncClient, "grpc_asyncio"), + (RecommendationServiceClient, "rest"), +]) +def test_recommendation_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +def test_recommendation_service_client_get_transport_class(): + transport = RecommendationServiceClient.get_transport_class() + available_transports = [ + transports.RecommendationServiceGrpcTransport, + transports.RecommendationServiceRestTransport, + ] + assert transport in available_transports + + transport = RecommendationServiceClient.get_transport_class("grpc") + assert transport == transports.RecommendationServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (RecommendationServiceClient, transports.RecommendationServiceGrpcTransport, "grpc"), + (RecommendationServiceAsyncClient, transports.RecommendationServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (RecommendationServiceClient, transports.RecommendationServiceRestTransport, "rest"), +]) +@mock.patch.object(RecommendationServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RecommendationServiceClient)) +@mock.patch.object(RecommendationServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RecommendationServiceAsyncClient)) +def test_recommendation_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(RecommendationServiceClient, '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(RecommendationServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (RecommendationServiceClient, transports.RecommendationServiceGrpcTransport, "grpc", "true"), + (RecommendationServiceAsyncClient, transports.RecommendationServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (RecommendationServiceClient, transports.RecommendationServiceGrpcTransport, "grpc", "false"), + (RecommendationServiceAsyncClient, transports.RecommendationServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (RecommendationServiceClient, transports.RecommendationServiceRestTransport, "rest", "true"), + (RecommendationServiceClient, transports.RecommendationServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(RecommendationServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RecommendationServiceClient)) +@mock.patch.object(RecommendationServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RecommendationServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_recommendation_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 + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + RecommendationServiceClient, RecommendationServiceAsyncClient +]) +@mock.patch.object(RecommendationServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RecommendationServiceClient)) +@mock.patch.object(RecommendationServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RecommendationServiceAsyncClient)) +def test_recommendation_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (RecommendationServiceClient, transports.RecommendationServiceGrpcTransport, "grpc"), + (RecommendationServiceAsyncClient, transports.RecommendationServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (RecommendationServiceClient, transports.RecommendationServiceRestTransport, "rest"), +]) +def test_recommendation_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, + 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", [ + (RecommendationServiceClient, transports.RecommendationServiceGrpcTransport, "grpc", grpc_helpers), + (RecommendationServiceAsyncClient, transports.RecommendationServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (RecommendationServiceClient, transports.RecommendationServiceRestTransport, "rest", None), +]) +def test_recommendation_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, + scopes=None, + client_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_recommendation_service_client_client_options_from_dict(): + with mock.patch('google.cloud.discoveryengine_v1beta.services.recommendation_service.transports.RecommendationServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = RecommendationServiceClient( + 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", [ + (RecommendationServiceClient, transports.RecommendationServiceGrpcTransport, "grpc", grpc_helpers), + (RecommendationServiceAsyncClient, transports.RecommendationServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_recommendation_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, + scopes=None, + client_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + recommendation_service.RecommendRequest, + dict, +]) +def test_recommend(request_type, transport: str = 'grpc'): + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.recommend), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = recommendation_service.RecommendResponse( + attribution_token='attribution_token_value', + missing_ids=['missing_ids_value'], + validate_only=True, + ) + response = client.recommend(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == recommendation_service.RecommendRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, recommendation_service.RecommendResponse) + assert response.attribution_token == 'attribution_token_value' + assert response.missing_ids == ['missing_ids_value'] + assert response.validate_only is True + + +def test_recommend_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.recommend), + '__call__') as call: + client.recommend() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == recommendation_service.RecommendRequest() + +@pytest.mark.asyncio +async def test_recommend_async(transport: str = 'grpc_asyncio', request_type=recommendation_service.RecommendRequest): + client = RecommendationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.recommend), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(recommendation_service.RecommendResponse( + attribution_token='attribution_token_value', + missing_ids=['missing_ids_value'], + validate_only=True, + )) + response = await client.recommend(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == recommendation_service.RecommendRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, recommendation_service.RecommendResponse) + assert response.attribution_token == 'attribution_token_value' + assert response.missing_ids == ['missing_ids_value'] + assert response.validate_only is True + + +@pytest.mark.asyncio +async def test_recommend_async_from_dict(): + await test_recommend_async(request_type=dict) + + +def test_recommend_field_headers(): + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recommendation_service.RecommendRequest() + + request.serving_config = 'serving_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.recommend), + '__call__') as call: + call.return_value = recommendation_service.RecommendResponse() + client.recommend(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config=serving_config_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_recommend_field_headers_async(): + client = RecommendationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = recommendation_service.RecommendRequest() + + request.serving_config = 'serving_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.recommend), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(recommendation_service.RecommendResponse()) + await client.recommend(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config=serving_config_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + recommendation_service.RecommendRequest, + dict, +]) +def test_recommend_rest(request_type): + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'serving_config': 'projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/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 = recommendation_service.RecommendResponse( + attribution_token='attribution_token_value', + missing_ids=['missing_ids_value'], + validate_only=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = recommendation_service.RecommendResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.recommend(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, recommendation_service.RecommendResponse) + assert response.attribution_token == 'attribution_token_value' + assert response.missing_ids == ['missing_ids_value'] + assert response.validate_only is True + + +def test_recommend_rest_required_fields(request_type=recommendation_service.RecommendRequest): + transport_class = transports.RecommendationServiceRestTransport + + request_init = {} + request_init["serving_config"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).recommend._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["servingConfig"] = 'serving_config_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).recommend._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "servingConfig" in jsonified_request + assert jsonified_request["servingConfig"] == 'serving_config_value' + + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = recommendation_service.RecommendResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = recommendation_service.RecommendResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.recommend(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_recommend_rest_unset_required_fields(): + transport = transports.RecommendationServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.recommend._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("servingConfig", "userEvent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_recommend_rest_interceptors(null_interceptor): + transport = transports.RecommendationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RecommendationServiceRestInterceptor(), + ) + client = RecommendationServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RecommendationServiceRestInterceptor, "post_recommend") as post, \ + mock.patch.object(transports.RecommendationServiceRestInterceptor, "pre_recommend") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = recommendation_service.RecommendRequest.pb(recommendation_service.RecommendRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = recommendation_service.RecommendResponse.to_json(recommendation_service.RecommendResponse()) + + request = recommendation_service.RecommendRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = recommendation_service.RecommendResponse() + + client.recommend(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_recommend_rest_bad_request(transport: str = 'rest', request_type=recommendation_service.RecommendRequest): + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'serving_config': 'projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.recommend(request) + + +def test_recommend_rest_error(): + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.RecommendationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.RecommendationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RecommendationServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.RecommendationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RecommendationServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RecommendationServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.RecommendationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RecommendationServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.RecommendationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = RecommendationServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.RecommendationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.RecommendationServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.RecommendationServiceGrpcTransport, + transports.RecommendationServiceGrpcAsyncIOTransport, + transports.RecommendationServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = RecommendationServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.RecommendationServiceGrpcTransport, + ) + +def test_recommendation_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.RecommendationServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_recommendation_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.discoveryengine_v1beta.services.recommendation_service.transports.RecommendationServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.RecommendationServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'recommend', + 'get_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_recommendation_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.discoveryengine_v1beta.services.recommendation_service.transports.RecommendationServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RecommendationServiceTransport( + 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_recommendation_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.discoveryengine_v1beta.services.recommendation_service.transports.RecommendationServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RecommendationServiceTransport() + adc.assert_called_once() + + +def test_recommendation_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) + RecommendationServiceClient() + 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.RecommendationServiceGrpcTransport, + transports.RecommendationServiceGrpcAsyncIOTransport, + ], +) +def test_recommendation_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.RecommendationServiceGrpcTransport, + transports.RecommendationServiceGrpcAsyncIOTransport, + transports.RecommendationServiceRestTransport, + ], +) +def test_recommendation_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.RecommendationServiceGrpcTransport, grpc_helpers), + (transports.RecommendationServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_recommendation_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.RecommendationServiceGrpcTransport, transports.RecommendationServiceGrpcAsyncIOTransport]) +def test_recommendation_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_recommendation_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.RecommendationServiceRestTransport ( + 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_recommendation_service_host_no_port(transport_name): + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_recommendation_service_host_with_port(transport_name): + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_recommendation_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = RecommendationServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = RecommendationServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.recommend._session + session2 = client2.transport.recommend._session + assert session1 != session2 +def test_recommendation_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RecommendationServiceGrpcTransport( + 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_recommendation_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RecommendationServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.RecommendationServiceGrpcTransport, transports.RecommendationServiceGrpcAsyncIOTransport]) +def test_recommendation_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.RecommendationServiceGrpcTransport, transports.RecommendationServiceGrpcAsyncIOTransport]) +def test_recommendation_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_document_path(): + project = "squid" + location = "clam" + data_store = "whelk" + branch = "octopus" + document = "oyster" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) + actual = RecommendationServiceClient.document_path(project, location, data_store, branch, document) + assert expected == actual + + +def test_parse_document_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "data_store": "mussel", + "branch": "winkle", + "document": "nautilus", + } + path = RecommendationServiceClient.document_path(**expected) + + # Check that the path construction is reversible. + actual = RecommendationServiceClient.parse_document_path(path) + assert expected == actual + +def test_serving_config_path(): + project = "scallop" + location = "abalone" + data_store = "squid" + serving_config = "clam" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/servingConfigs/{serving_config}".format(project=project, location=location, data_store=data_store, serving_config=serving_config, ) + actual = RecommendationServiceClient.serving_config_path(project, location, data_store, serving_config) + assert expected == actual + + +def test_parse_serving_config_path(): + expected = { + "project": "whelk", + "location": "octopus", + "data_store": "oyster", + "serving_config": "nudibranch", + } + path = RecommendationServiceClient.serving_config_path(**expected) + + # Check that the path construction is reversible. + actual = RecommendationServiceClient.parse_serving_config_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = RecommendationServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = RecommendationServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = RecommendationServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = RecommendationServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = RecommendationServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = RecommendationServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = RecommendationServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = RecommendationServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = RecommendationServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = RecommendationServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = RecommendationServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = RecommendationServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = RecommendationServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = RecommendationServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = RecommendationServiceClient.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.RecommendationServiceTransport, '_prep_wrapped_messages') as prep: + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.RecommendationServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = RecommendationServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = RecommendationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_get_operation(transport: str = "grpc"): + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc"): + client = RecommendationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = RecommendationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = RecommendationServiceClient( + 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 = RecommendationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc"): + client = RecommendationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = RecommendationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = RecommendationServiceClient( + 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 = RecommendationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = RecommendationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = RecommendationServiceClient( + 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", [ + (RecommendationServiceClient, transports.RecommendationServiceGrpcTransport), + (RecommendationServiceAsyncClient, transports.RecommendationServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_schema_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_schema_service.py new file mode 100644 index 000000000000..13021b222ce4 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_schema_service.py @@ -0,0 +1,4265 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.discoveryengine_v1beta.services.schema_service import SchemaServiceAsyncClient +from google.cloud.discoveryengine_v1beta.services.schema_service import SchemaServiceClient +from google.cloud.discoveryengine_v1beta.services.schema_service import pagers +from google.cloud.discoveryengine_v1beta.services.schema_service import transports +from google.cloud.discoveryengine_v1beta.types import schema +from google.cloud.discoveryengine_v1beta.types import schema as gcd_schema +from google.cloud.discoveryengine_v1beta.types import schema_service +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert SchemaServiceClient._get_default_mtls_endpoint(None) is None + assert SchemaServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert SchemaServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert SchemaServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert SchemaServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert SchemaServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (SchemaServiceClient, "grpc"), + (SchemaServiceAsyncClient, "grpc_asyncio"), + (SchemaServiceClient, "rest"), +]) +def test_schema_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.SchemaServiceGrpcTransport, "grpc"), + (transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.SchemaServiceRestTransport, "rest"), +]) +def test_schema_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", [ + (SchemaServiceClient, "grpc"), + (SchemaServiceAsyncClient, "grpc_asyncio"), + (SchemaServiceClient, "rest"), +]) +def test_schema_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +def test_schema_service_client_get_transport_class(): + transport = SchemaServiceClient.get_transport_class() + available_transports = [ + transports.SchemaServiceGrpcTransport, + transports.SchemaServiceRestTransport, + ] + assert transport in available_transports + + transport = SchemaServiceClient.get_transport_class("grpc") + assert transport == transports.SchemaServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc"), + (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (SchemaServiceClient, transports.SchemaServiceRestTransport, "rest"), +]) +@mock.patch.object(SchemaServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceClient)) +@mock.patch.object(SchemaServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceAsyncClient)) +def test_schema_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(SchemaServiceClient, '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(SchemaServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc", "true"), + (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc", "false"), + (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (SchemaServiceClient, transports.SchemaServiceRestTransport, "rest", "true"), + (SchemaServiceClient, transports.SchemaServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(SchemaServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceClient)) +@mock.patch.object(SchemaServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_schema_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 + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + SchemaServiceClient, SchemaServiceAsyncClient +]) +@mock.patch.object(SchemaServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceClient)) +@mock.patch.object(SchemaServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceAsyncClient)) +def test_schema_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc"), + (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (SchemaServiceClient, transports.SchemaServiceRestTransport, "rest"), +]) +def test_schema_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, + 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", [ + (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc", grpc_helpers), + (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (SchemaServiceClient, transports.SchemaServiceRestTransport, "rest", None), +]) +def test_schema_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, + scopes=None, + client_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_schema_service_client_client_options_from_dict(): + with mock.patch('google.cloud.discoveryengine_v1beta.services.schema_service.transports.SchemaServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = SchemaServiceClient( + 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", [ + (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc", grpc_helpers), + (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_schema_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, + scopes=None, + client_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + schema_service.GetSchemaRequest, + dict, +]) +def test_get_schema(request_type, transport: str = 'grpc'): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = schema.Schema( + name='name_value', + json_schema='json_schema_value', + ) + response = client.get_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.GetSchemaRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, schema.Schema) + assert response.name == 'name_value' + + +def test_get_schema_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_schema), + '__call__') as call: + client.get_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.GetSchemaRequest() + +@pytest.mark.asyncio +async def test_get_schema_async(transport: str = 'grpc_asyncio', request_type=schema_service.GetSchemaRequest): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(schema.Schema( + name='name_value', + )) + response = await client.get_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.GetSchemaRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, schema.Schema) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_schema_async_from_dict(): + await test_get_schema_async(request_type=dict) + + +def test_get_schema_field_headers(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema_service.GetSchemaRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_schema), + '__call__') as call: + call.return_value = schema.Schema() + client.get_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_schema_field_headers_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema_service.GetSchemaRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_schema), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.Schema()) + await client.get_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_schema_flattened(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = schema.Schema() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_schema( + 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_schema_flattened_error(): + client = SchemaServiceClient( + credentials=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_schema( + schema_service.GetSchemaRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_schema_flattened_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = schema.Schema() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.Schema()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_schema( + 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_schema_flattened_error_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_schema( + schema_service.GetSchemaRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + schema_service.ListSchemasRequest, + dict, +]) +def test_list_schemas(request_type, transport: str = 'grpc'): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_schemas), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = schema_service.ListSchemasResponse( + next_page_token='next_page_token_value', + ) + response = client.list_schemas(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.ListSchemasRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSchemasPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_schemas_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_schemas), + '__call__') as call: + client.list_schemas() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.ListSchemasRequest() + +@pytest.mark.asyncio +async def test_list_schemas_async(transport: str = 'grpc_asyncio', request_type=schema_service.ListSchemasRequest): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_schemas), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(schema_service.ListSchemasResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_schemas(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.ListSchemasRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSchemasAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_schemas_async_from_dict(): + await test_list_schemas_async(request_type=dict) + + +def test_list_schemas_field_headers(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema_service.ListSchemasRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_schemas), + '__call__') as call: + call.return_value = schema_service.ListSchemasResponse() + client.list_schemas(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_schemas_field_headers_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema_service.ListSchemasRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_schemas), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema_service.ListSchemasResponse()) + await client.list_schemas(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_schemas_flattened(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_schemas), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = schema_service.ListSchemasResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_schemas( + 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_schemas_flattened_error(): + client = SchemaServiceClient( + credentials=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_schemas( + schema_service.ListSchemasRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_schemas_flattened_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_schemas), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = schema_service.ListSchemasResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema_service.ListSchemasResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_schemas( + 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_schemas_flattened_error_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_schemas( + schema_service.ListSchemasRequest(), + parent='parent_value', + ) + + +def test_list_schemas_pager(transport_name: str = "grpc"): + client = SchemaServiceClient( + 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_schemas), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + schema.Schema(), + ], + next_page_token='abc', + ), + schema_service.ListSchemasResponse( + schemas=[], + next_page_token='def', + ), + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + ], + next_page_token='ghi', + ), + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_schemas(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, schema.Schema) + for i in results) +def test_list_schemas_pages(transport_name: str = "grpc"): + client = SchemaServiceClient( + 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_schemas), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + schema.Schema(), + ], + next_page_token='abc', + ), + schema_service.ListSchemasResponse( + schemas=[], + next_page_token='def', + ), + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + ], + next_page_token='ghi', + ), + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + ], + ), + RuntimeError, + ) + pages = list(client.list_schemas(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_schemas_async_pager(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_schemas), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + schema.Schema(), + ], + next_page_token='abc', + ), + schema_service.ListSchemasResponse( + schemas=[], + next_page_token='def', + ), + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + ], + next_page_token='ghi', + ), + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_schemas(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, schema.Schema) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_schemas_async_pages(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_schemas), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + schema.Schema(), + ], + next_page_token='abc', + ), + schema_service.ListSchemasResponse( + schemas=[], + next_page_token='def', + ), + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + ], + next_page_token='ghi', + ), + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_schemas(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", [ + schema_service.CreateSchemaRequest, + dict, +]) +def test_create_schema(request_type, transport: str = 'grpc'): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.CreateSchemaRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_schema_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_schema), + '__call__') as call: + client.create_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.CreateSchemaRequest() + +@pytest.mark.asyncio +async def test_create_schema_async(transport: str = 'grpc_asyncio', request_type=schema_service.CreateSchemaRequest): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_schema), + '__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_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.CreateSchemaRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_schema_async_from_dict(): + await test_create_schema_async(request_type=dict) + + +def test_create_schema_field_headers(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema_service.CreateSchemaRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_schema), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_schema_field_headers_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema_service.CreateSchemaRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_schema), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_schema_flattened(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_schema), + '__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_schema( + parent='parent_value', + schema=gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), + schema_id='schema_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].schema + mock_val = gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})) + assert arg == mock_val + arg = args[0].schema_id + mock_val = 'schema_id_value' + assert arg == mock_val + + +def test_create_schema_flattened_error(): + client = SchemaServiceClient( + credentials=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_schema( + schema_service.CreateSchemaRequest(), + parent='parent_value', + schema=gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), + schema_id='schema_id_value', + ) + +@pytest.mark.asyncio +async def test_create_schema_flattened_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_schema), + '__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_schema( + parent='parent_value', + schema=gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), + schema_id='schema_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].schema + mock_val = gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})) + assert arg == mock_val + arg = args[0].schema_id + mock_val = 'schema_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_schema_flattened_error_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_schema( + schema_service.CreateSchemaRequest(), + parent='parent_value', + schema=gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), + schema_id='schema_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + schema_service.UpdateSchemaRequest, + dict, +]) +def test_update_schema(request_type, transport: str = 'grpc'): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.UpdateSchemaRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_schema_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_schema), + '__call__') as call: + client.update_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.UpdateSchemaRequest() + +@pytest.mark.asyncio +async def test_update_schema_async(transport: str = 'grpc_asyncio', request_type=schema_service.UpdateSchemaRequest): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_schema), + '__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_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.UpdateSchemaRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_schema_async_from_dict(): + await test_update_schema_async(request_type=dict) + + +def test_update_schema_field_headers(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema_service.UpdateSchemaRequest() + + request.schema.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_schema), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'schema.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_schema_field_headers_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema_service.UpdateSchemaRequest() + + request.schema.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_schema), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'schema.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + schema_service.DeleteSchemaRequest, + dict, +]) +def test_delete_schema(request_type, transport: str = 'grpc'): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.DeleteSchemaRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_schema_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_schema), + '__call__') as call: + client.delete_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.DeleteSchemaRequest() + +@pytest.mark.asyncio +async def test_delete_schema_async(transport: str = 'grpc_asyncio', request_type=schema_service.DeleteSchemaRequest): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_schema), + '__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_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == schema_service.DeleteSchemaRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_schema_async_from_dict(): + await test_delete_schema_async(request_type=dict) + + +def test_delete_schema_field_headers(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema_service.DeleteSchemaRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_schema), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_schema_field_headers_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = schema_service.DeleteSchemaRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_schema), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_schema_flattened(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_schema), + '__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_schema( + 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_schema_flattened_error(): + client = SchemaServiceClient( + credentials=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_schema( + schema_service.DeleteSchemaRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_schema_flattened_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_schema), + '__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_schema( + 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_schema_flattened_error_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_schema( + schema_service.DeleteSchemaRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + schema_service.GetSchemaRequest, + dict, +]) +def test_get_schema_rest(request_type): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/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 = schema.Schema( + name='name_value', + json_schema='json_schema_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 = schema.Schema.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_schema(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, schema.Schema) + assert response.name == 'name_value' + + +def test_get_schema_rest_required_fields(request_type=schema_service.GetSchemaRequest): + transport_class = transports.SchemaServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = schema.Schema() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = schema.Schema.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_schema(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_schema_rest_unset_required_fields(): + transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_schema._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_schema_rest_interceptors(null_interceptor): + transport = transports.SchemaServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), + ) + client = SchemaServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SchemaServiceRestInterceptor, "post_get_schema") as post, \ + mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_get_schema") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = schema_service.GetSchemaRequest.pb(schema_service.GetSchemaRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = schema.Schema.to_json(schema.Schema()) + + request = schema_service.GetSchemaRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = schema.Schema() + + client.get_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_schema_rest_bad_request(transport: str = 'rest', request_type=schema_service.GetSchemaRequest): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_schema(request) + + +def test_get_schema_rest_flattened(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = schema.Schema() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/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 = schema.Schema.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_schema(**mock_args) + + # Establish that the underlying call 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/*/dataStores/*/schemas/*}" % client.transport._host, args[1]) + + +def test_get_schema_rest_flattened_error(transport: str = 'rest'): + client = SchemaServiceClient( + credentials=ga_credentials.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_schema( + schema_service.GetSchemaRequest(), + name='name_value', + ) + + +def test_get_schema_rest_error(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + schema_service.ListSchemasRequest, + dict, +]) +def test_list_schemas_rest(request_type): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/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 = schema_service.ListSchemasResponse( + next_page_token='next_page_token_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 = schema_service.ListSchemasResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_schemas(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSchemasPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_schemas_rest_required_fields(request_type=schema_service.ListSchemasRequest): + transport_class = transports.SchemaServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_schemas._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_schemas._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = schema_service.ListSchemasResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = schema_service.ListSchemasResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_schemas(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_schemas_rest_unset_required_fields(): + transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_schemas._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_schemas_rest_interceptors(null_interceptor): + transport = transports.SchemaServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), + ) + client = SchemaServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SchemaServiceRestInterceptor, "post_list_schemas") as post, \ + mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_list_schemas") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = schema_service.ListSchemasRequest.pb(schema_service.ListSchemasRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = schema_service.ListSchemasResponse.to_json(schema_service.ListSchemasResponse()) + + request = schema_service.ListSchemasRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = schema_service.ListSchemasResponse() + + client.list_schemas(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_schemas_rest_bad_request(transport: str = 'rest', request_type=schema_service.ListSchemasRequest): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_schemas(request) + + +def test_list_schemas_rest_flattened(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = schema_service.ListSchemasResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/dataStores/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 = schema_service.ListSchemasResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_schemas(**mock_args) + + # Establish that the underlying call 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/*/dataStores/*}/schemas" % client.transport._host, args[1]) + + +def test_list_schemas_rest_flattened_error(transport: str = 'rest'): + client = SchemaServiceClient( + credentials=ga_credentials.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_schemas( + schema_service.ListSchemasRequest(), + parent='parent_value', + ) + + +def test_list_schemas_rest_pager(transport: str = 'rest'): + client = SchemaServiceClient( + 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 = ( + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + schema.Schema(), + ], + next_page_token='abc', + ), + schema_service.ListSchemasResponse( + schemas=[], + next_page_token='def', + ), + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + ], + next_page_token='ghi', + ), + schema_service.ListSchemasResponse( + schemas=[ + schema.Schema(), + schema.Schema(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(schema_service.ListSchemasResponse.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/dataStores/sample3'} + + pager = client.list_schemas(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, schema.Schema) + for i in results) + + pages = list(client.list_schemas(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + schema_service.CreateSchemaRequest, + dict, +]) +def test_create_schema_rest(request_type): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + request_init["schema"] = {'struct_schema': {'fields': {}}, 'json_schema': 'json_schema_value', 'name': 'name_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 = schema_service.CreateSchemaRequest.meta.fields["schema"] + + 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["schema"].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["schema"][field])): + del request_init["schema"][field][i][subfield] + else: + del request_init["schema"][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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_schema(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_schema_rest_required_fields(request_type=schema_service.CreateSchemaRequest): + transport_class = transports.SchemaServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["schema_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "schemaId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "schemaId" in jsonified_request + assert jsonified_request["schemaId"] == request_init["schema_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["schemaId"] = 'schema_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_schema._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("schema_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "schemaId" in jsonified_request + assert jsonified_request["schemaId"] == 'schema_id_value' + + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_schema(request) + + expected_params = [ + ( + "schemaId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_schema_rest_unset_required_fields(): + transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_schema._get_unset_required_fields({}) + assert set(unset_fields) == (set(("schemaId", )) & set(("parent", "schema", "schemaId", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_schema_rest_interceptors(null_interceptor): + transport = transports.SchemaServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), + ) + client = SchemaServiceClient(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.SchemaServiceRestInterceptor, "post_create_schema") as post, \ + mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_create_schema") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = schema_service.CreateSchemaRequest.pb(schema_service.CreateSchemaRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = schema_service.CreateSchemaRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_schema_rest_bad_request(transport: str = 'rest', request_type=schema_service.CreateSchemaRequest): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_schema(request) + + +def test_create_schema_rest_flattened(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.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/dataStores/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + schema=gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), + schema_id='schema_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_schema(**mock_args) + + # Establish that the underlying call 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/*/dataStores/*}/schemas" % client.transport._host, args[1]) + + +def test_create_schema_rest_flattened_error(transport: str = 'rest'): + client = SchemaServiceClient( + credentials=ga_credentials.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_schema( + schema_service.CreateSchemaRequest(), + parent='parent_value', + schema=gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), + schema_id='schema_id_value', + ) + + +def test_create_schema_rest_error(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + schema_service.UpdateSchemaRequest, + dict, +]) +def test_update_schema_rest(request_type): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'schema': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/sample4'}} + request_init["schema"] = {'struct_schema': {'fields': {}}, 'json_schema': 'json_schema_value', 'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/sample4'} + # 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 = schema_service.UpdateSchemaRequest.meta.fields["schema"] + + 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["schema"].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["schema"][field])): + del request_init["schema"][field][i][subfield] + else: + del request_init["schema"][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 = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_schema(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_schema_rest_required_fields(request_type=schema_service.UpdateSchemaRequest): + transport_class = transports.SchemaServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_schema._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_schema(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_schema_rest_unset_required_fields(): + transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_schema._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", )) & set(("schema", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_schema_rest_interceptors(null_interceptor): + transport = transports.SchemaServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), + ) + client = SchemaServiceClient(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.SchemaServiceRestInterceptor, "post_update_schema") as post, \ + mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_update_schema") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = schema_service.UpdateSchemaRequest.pb(schema_service.UpdateSchemaRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = schema_service.UpdateSchemaRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_schema_rest_bad_request(transport: str = 'rest', request_type=schema_service.UpdateSchemaRequest): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'schema': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/sample4'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_schema(request) + + +def test_update_schema_rest_error(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + schema_service.DeleteSchemaRequest, + dict, +]) +def test_delete_schema_rest(request_type): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_schema(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_schema_rest_required_fields(request_type=schema_service.DeleteSchemaRequest): + transport_class = transports.SchemaServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_schema(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_schema_rest_unset_required_fields(): + transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_schema._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_schema_rest_interceptors(null_interceptor): + transport = transports.SchemaServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), + ) + client = SchemaServiceClient(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.SchemaServiceRestInterceptor, "post_delete_schema") as post, \ + mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_delete_schema") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = schema_service.DeleteSchemaRequest.pb(schema_service.DeleteSchemaRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = schema_service.DeleteSchemaRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_schema_rest_bad_request(transport: str = 'rest', request_type=schema_service.DeleteSchemaRequest): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_schema(request) + + +def test_delete_schema_rest_flattened(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.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/dataStores/sample3/schemas/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_schema(**mock_args) + + # Establish that the underlying call 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/*/dataStores/*/schemas/*}" % client.transport._host, args[1]) + + +def test_delete_schema_rest_flattened_error(transport: str = 'rest'): + client = SchemaServiceClient( + credentials=ga_credentials.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_schema( + schema_service.DeleteSchemaRequest(), + name='name_value', + ) + + +def test_delete_schema_rest_error(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SchemaServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SchemaServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SchemaServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SchemaServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SchemaServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SchemaServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SchemaServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SchemaServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SchemaServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SchemaServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SchemaServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SchemaServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.SchemaServiceGrpcTransport, + transports.SchemaServiceGrpcAsyncIOTransport, + transports.SchemaServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = SchemaServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SchemaServiceGrpcTransport, + ) + +def test_schema_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SchemaServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_schema_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.discoveryengine_v1beta.services.schema_service.transports.SchemaServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.SchemaServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_schema', + 'list_schemas', + 'create_schema', + 'update_schema', + 'delete_schema', + 'get_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_schema_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.discoveryengine_v1beta.services.schema_service.transports.SchemaServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SchemaServiceTransport( + 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_schema_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.discoveryengine_v1beta.services.schema_service.transports.SchemaServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SchemaServiceTransport() + adc.assert_called_once() + + +def test_schema_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) + SchemaServiceClient() + 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.SchemaServiceGrpcTransport, + transports.SchemaServiceGrpcAsyncIOTransport, + ], +) +def test_schema_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.SchemaServiceGrpcTransport, + transports.SchemaServiceGrpcAsyncIOTransport, + transports.SchemaServiceRestTransport, + ], +) +def test_schema_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.SchemaServiceGrpcTransport, grpc_helpers), + (transports.SchemaServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_schema_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.SchemaServiceGrpcTransport, transports.SchemaServiceGrpcAsyncIOTransport]) +def test_schema_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_schema_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.SchemaServiceRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_schema_service_rest_lro_client(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_schema_service_host_no_port(transport_name): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_schema_service_host_with_port(transport_name): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_schema_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = SchemaServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = SchemaServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_schema._session + session2 = client2.transport.get_schema._session + assert session1 != session2 + session1 = client1.transport.list_schemas._session + session2 = client2.transport.list_schemas._session + assert session1 != session2 + session1 = client1.transport.create_schema._session + session2 = client2.transport.create_schema._session + assert session1 != session2 + session1 = client1.transport.update_schema._session + session2 = client2.transport.update_schema._session + assert session1 != session2 + session1 = client1.transport.delete_schema._session + session2 = client2.transport.delete_schema._session + assert session1 != session2 +def test_schema_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SchemaServiceGrpcTransport( + 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_schema_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SchemaServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.SchemaServiceGrpcTransport, transports.SchemaServiceGrpcAsyncIOTransport]) +def test_schema_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.SchemaServiceGrpcTransport, transports.SchemaServiceGrpcAsyncIOTransport]) +def test_schema_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_schema_service_grpc_lro_client(): + client = SchemaServiceClient( + 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_schema_service_grpc_lro_async_client(): + client = SchemaServiceAsyncClient( + 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_data_store_path(): + project = "squid" + location = "clam" + data_store = "whelk" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) + actual = SchemaServiceClient.data_store_path(project, location, data_store) + assert expected == actual + + +def test_parse_data_store_path(): + expected = { + "project": "octopus", + "location": "oyster", + "data_store": "nudibranch", + } + path = SchemaServiceClient.data_store_path(**expected) + + # Check that the path construction is reversible. + actual = SchemaServiceClient.parse_data_store_path(path) + assert expected == actual + +def test_schema_path(): + project = "cuttlefish" + location = "mussel" + data_store = "winkle" + schema = "nautilus" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/schemas/{schema}".format(project=project, location=location, data_store=data_store, schema=schema, ) + actual = SchemaServiceClient.schema_path(project, location, data_store, schema) + assert expected == actual + + +def test_parse_schema_path(): + expected = { + "project": "scallop", + "location": "abalone", + "data_store": "squid", + "schema": "clam", + } + path = SchemaServiceClient.schema_path(**expected) + + # Check that the path construction is reversible. + actual = SchemaServiceClient.parse_schema_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = SchemaServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = SchemaServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SchemaServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = SchemaServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = SchemaServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SchemaServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SchemaServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = SchemaServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SchemaServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = SchemaServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = SchemaServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SchemaServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = SchemaServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = SchemaServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SchemaServiceClient.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.SchemaServiceTransport, '_prep_wrapped_messages') as prep: + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.SchemaServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = SchemaServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_get_operation(transport: str = "grpc"): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc"): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SchemaServiceClient( + 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 = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc"): + client = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SchemaServiceClient( + 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 = SchemaServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = SchemaServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = SchemaServiceClient( + 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", [ + (SchemaServiceClient, transports.SchemaServiceGrpcTransport), + (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_search_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_search_service.py new file mode 100644 index 000000000000..7e11d808f030 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_search_service.py @@ -0,0 +1,2239 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.discoveryengine_v1beta.services.search_service import SearchServiceAsyncClient +from google.cloud.discoveryengine_v1beta.services.search_service import SearchServiceClient +from google.cloud.discoveryengine_v1beta.services.search_service import pagers +from google.cloud.discoveryengine_v1beta.services.search_service import transports +from google.cloud.discoveryengine_v1beta.types import common +from google.cloud.discoveryengine_v1beta.types import search_service +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import struct_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert SearchServiceClient._get_default_mtls_endpoint(None) is None + assert SearchServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert SearchServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (SearchServiceClient, "grpc"), + (SearchServiceAsyncClient, "grpc_asyncio"), + (SearchServiceClient, "rest"), +]) +def test_search_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.SearchServiceGrpcTransport, "grpc"), + (transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.SearchServiceRestTransport, "rest"), +]) +def test_search_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", [ + (SearchServiceClient, "grpc"), + (SearchServiceAsyncClient, "grpc_asyncio"), + (SearchServiceClient, "rest"), +]) +def test_search_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +def test_search_service_client_get_transport_class(): + transport = SearchServiceClient.get_transport_class() + available_transports = [ + transports.SearchServiceGrpcTransport, + transports.SearchServiceRestTransport, + ] + assert transport in available_transports + + transport = SearchServiceClient.get_transport_class("grpc") + assert transport == transports.SearchServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (SearchServiceClient, transports.SearchServiceRestTransport, "rest"), +]) +@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) +@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) +def test_search_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(SearchServiceClient, '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(SearchServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "true"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "false"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (SearchServiceClient, transports.SearchServiceRestTransport, "rest", "true"), + (SearchServiceClient, transports.SearchServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) +@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_search_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 + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + SearchServiceClient, SearchServiceAsyncClient +]) +@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) +@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) +def test_search_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (SearchServiceClient, transports.SearchServiceRestTransport, "rest"), +]) +def test_search_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, + 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", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (SearchServiceClient, transports.SearchServiceRestTransport, "rest", None), +]) +def test_search_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, + scopes=None, + client_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_search_service_client_client_options_from_dict(): + with mock.patch('google.cloud.discoveryengine_v1beta.services.search_service.transports.SearchServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = SearchServiceClient( + 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", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_search_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, + scopes=None, + client_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + search_service.SearchRequest, + dict, +]) +def test_search(request_type, transport: str = 'grpc'): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = search_service.SearchResponse( + total_size=1086, + attribution_token='attribution_token_value', + redirect_uri='redirect_uri_value', + next_page_token='next_page_token_value', + corrected_query='corrected_query_value', + applied_controls=['applied_controls_value'], + ) + response = client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == search_service.SearchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchPager) + assert response.total_size == 1086 + assert response.attribution_token == 'attribution_token_value' + assert response.redirect_uri == 'redirect_uri_value' + assert response.next_page_token == 'next_page_token_value' + assert response.corrected_query == 'corrected_query_value' + assert response.applied_controls == ['applied_controls_value'] + + +def test_search_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + client.search() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == search_service.SearchRequest() + +@pytest.mark.asyncio +async def test_search_async(transport: str = 'grpc_asyncio', request_type=search_service.SearchRequest): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse( + total_size=1086, + attribution_token='attribution_token_value', + redirect_uri='redirect_uri_value', + next_page_token='next_page_token_value', + corrected_query='corrected_query_value', + applied_controls=['applied_controls_value'], + )) + response = await client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == search_service.SearchRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAsyncPager) + assert response.total_size == 1086 + assert response.attribution_token == 'attribution_token_value' + assert response.redirect_uri == 'redirect_uri_value' + assert response.next_page_token == 'next_page_token_value' + assert response.corrected_query == 'corrected_query_value' + assert response.applied_controls == ['applied_controls_value'] + + +@pytest.mark.asyncio +async def test_search_async_from_dict(): + await test_search_async(request_type=dict) + + +def test_search_field_headers(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = search_service.SearchRequest() + + request.serving_config = 'serving_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + call.return_value = search_service.SearchResponse() + client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config=serving_config_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_search_field_headers_async(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = search_service.SearchRequest() + + request.serving_config = 'serving_config_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse()) + await client.search(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'serving_config=serving_config_value', + ) in kw['metadata'] + + +def test_search_pager(transport_name: str = "grpc"): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('serving_config', ''), + )), + ) + pager = client.search(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, search_service.SearchResponse.SearchResult) + for i in results) +def test_search_pages(transport_name: str = "grpc"): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + pages = list(client.search(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_search_async_pager(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.search(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, search_service.SearchResponse.SearchResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_search_async_pages(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.search(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", [ + search_service.SearchRequest, + dict, +]) +def test_search_rest(request_type): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'serving_config': 'projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/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 = search_service.SearchResponse( + total_size=1086, + attribution_token='attribution_token_value', + redirect_uri='redirect_uri_value', + next_page_token='next_page_token_value', + corrected_query='corrected_query_value', + applied_controls=['applied_controls_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 = search_service.SearchResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.search(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchPager) + assert response.total_size == 1086 + assert response.attribution_token == 'attribution_token_value' + assert response.redirect_uri == 'redirect_uri_value' + assert response.next_page_token == 'next_page_token_value' + assert response.corrected_query == 'corrected_query_value' + assert response.applied_controls == ['applied_controls_value'] + + +def test_search_rest_required_fields(request_type=search_service.SearchRequest): + transport_class = transports.SearchServiceRestTransport + + request_init = {} + request_init["serving_config"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["servingConfig"] = 'serving_config_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "servingConfig" in jsonified_request + assert jsonified_request["servingConfig"] == 'serving_config_value' + + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = search_service.SearchResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = search_service.SearchResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.search(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_search_rest_unset_required_fields(): + transport = transports.SearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.search._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("servingConfig", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_rest_interceptors(null_interceptor): + transport = transports.SearchServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SearchServiceRestInterceptor(), + ) + client = SearchServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.SearchServiceRestInterceptor, "post_search") as post, \ + mock.patch.object(transports.SearchServiceRestInterceptor, "pre_search") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = search_service.SearchRequest.pb(search_service.SearchRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = search_service.SearchResponse.to_json(search_service.SearchResponse()) + + request = search_service.SearchRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = search_service.SearchResponse() + + client.search(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_search_rest_bad_request(transport: str = 'rest', request_type=search_service.SearchRequest): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'serving_config': 'projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.search(request) + + +def test_search_rest_pager(transport: str = 'rest'): + client = SearchServiceClient( + 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 = ( + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + next_page_token='abc', + ), + search_service.SearchResponse( + results=[], + next_page_token='def', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + ], + next_page_token='ghi', + ), + search_service.SearchResponse( + results=[ + search_service.SearchResponse.SearchResult(), + search_service.SearchResponse.SearchResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(search_service.SearchResponse.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 = {'serving_config': 'projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/sample4'} + + pager = client.search(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, search_service.SearchResponse.SearchResult) + for i in results) + + pages = list(client.search(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.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SearchServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SearchServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SearchServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SearchServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.SearchServiceGrpcTransport, + transports.SearchServiceGrpcAsyncIOTransport, + transports.SearchServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = SearchServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SearchServiceGrpcTransport, + ) + +def test_search_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SearchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_search_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.discoveryengine_v1beta.services.search_service.transports.SearchServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.SearchServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'search', + 'get_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_search_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.discoveryengine_v1beta.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SearchServiceTransport( + 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_search_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.discoveryengine_v1beta.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SearchServiceTransport() + adc.assert_called_once() + + +def test_search_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) + SearchServiceClient() + 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.SearchServiceGrpcTransport, + transports.SearchServiceGrpcAsyncIOTransport, + ], +) +def test_search_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.SearchServiceGrpcTransport, + transports.SearchServiceGrpcAsyncIOTransport, + transports.SearchServiceRestTransport, + ], +) +def test_search_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.SearchServiceGrpcTransport, grpc_helpers), + (transports.SearchServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_search_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) +def test_search_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_search_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.SearchServiceRestTransport ( + 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_search_service_host_no_port(transport_name): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_search_service_host_with_port(transport_name): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_search_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = SearchServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = SearchServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.search._session + session2 = client2.transport.search._session + assert session1 != session2 +def test_search_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SearchServiceGrpcTransport( + 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_search_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SearchServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) +def test_search_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.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) +def test_search_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_branch_path(): + project = "squid" + location = "clam" + data_store = "whelk" + branch = "octopus" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}".format(project=project, location=location, data_store=data_store, branch=branch, ) + actual = SearchServiceClient.branch_path(project, location, data_store, branch) + assert expected == actual + + +def test_parse_branch_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "data_store": "cuttlefish", + "branch": "mussel", + } + path = SearchServiceClient.branch_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_branch_path(path) + assert expected == actual + +def test_document_path(): + project = "winkle" + location = "nautilus" + data_store = "scallop" + branch = "abalone" + document = "squid" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) + actual = SearchServiceClient.document_path(project, location, data_store, branch, document) + assert expected == actual + + +def test_parse_document_path(): + expected = { + "project": "clam", + "location": "whelk", + "data_store": "octopus", + "branch": "oyster", + "document": "nudibranch", + } + path = SearchServiceClient.document_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_document_path(path) + assert expected == actual + +def test_serving_config_path(): + project = "cuttlefish" + location = "mussel" + data_store = "winkle" + serving_config = "nautilus" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/servingConfigs/{serving_config}".format(project=project, location=location, data_store=data_store, serving_config=serving_config, ) + actual = SearchServiceClient.serving_config_path(project, location, data_store, serving_config) + assert expected == actual + + +def test_parse_serving_config_path(): + expected = { + "project": "scallop", + "location": "abalone", + "data_store": "squid", + "serving_config": "clam", + } + path = SearchServiceClient.serving_config_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_serving_config_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = SearchServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = SearchServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = SearchServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = SearchServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = SearchServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = SearchServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = SearchServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = SearchServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = SearchServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = SearchServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SearchServiceClient.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.SearchServiceTransport, '_prep_wrapped_messages') as prep: + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = SearchServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_get_operation(transport: str = "grpc"): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc"): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SearchServiceClient( + 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 = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc"): + client = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = SearchServiceClient( + 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 = SearchServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = SearchServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = SearchServiceClient( + 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", [ + (SearchServiceClient, transports.SearchServiceGrpcTransport), + (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_user_event_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_user_event_service.py new file mode 100644 index 000000000000..3f0f8f4975d6 --- /dev/null +++ b/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_user_event_service.py @@ -0,0 +1,2786 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.discoveryengine_v1beta.services.user_event_service import UserEventServiceAsyncClient +from google.cloud.discoveryengine_v1beta.services.user_event_service import UserEventServiceClient +from google.cloud.discoveryengine_v1beta.services.user_event_service import transports +from google.cloud.discoveryengine_v1beta.types import common +from google.cloud.discoveryengine_v1beta.types import import_config +from google.cloud.discoveryengine_v1beta.types import user_event +from google.cloud.discoveryengine_v1beta.types import user_event_service +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import date_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert UserEventServiceClient._get_default_mtls_endpoint(None) is None + assert UserEventServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert UserEventServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (UserEventServiceClient, "grpc"), + (UserEventServiceAsyncClient, "grpc_asyncio"), + (UserEventServiceClient, "rest"), +]) +def test_user_event_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.UserEventServiceGrpcTransport, "grpc"), + (transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.UserEventServiceRestTransport, "rest"), +]) +def test_user_event_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", [ + (UserEventServiceClient, "grpc"), + (UserEventServiceAsyncClient, "grpc_asyncio"), + (UserEventServiceClient, "rest"), +]) +def test_user_event_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 == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://discoveryengine.googleapis.com' + ) + + +def test_user_event_service_client_get_transport_class(): + transport = UserEventServiceClient.get_transport_class() + available_transports = [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceRestTransport, + ] + assert transport in available_transports + + transport = UserEventServiceClient.get_transport_class("grpc") + assert transport == transports.UserEventServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (UserEventServiceClient, transports.UserEventServiceRestTransport, "rest"), +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +def test_user_event_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(UserEventServiceClient, '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(UserEventServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "true"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "false"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (UserEventServiceClient, transports.UserEventServiceRestTransport, "rest", "true"), + (UserEventServiceClient, transports.UserEventServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_user_event_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 + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + UserEventServiceClient, UserEventServiceAsyncClient +]) +@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) +@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) +def test_user_event_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (UserEventServiceClient, transports.UserEventServiceRestTransport, "rest"), +]) +def test_user_event_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, + 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", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (UserEventServiceClient, transports.UserEventServiceRestTransport, "rest", None), +]) +def test_user_event_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, + scopes=None, + client_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_user_event_service_client_client_options_from_dict(): + with mock.patch('google.cloud.discoveryengine_v1beta.services.user_event_service.transports.UserEventServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = UserEventServiceClient( + 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", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_user_event_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, + scopes=None, + client_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + user_event_service.WriteUserEventRequest, + dict, +]) +def test_write_user_event(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = user_event.UserEvent( + event_type='event_type_value', + user_pseudo_id='user_pseudo_id_value', + direct_user_request=True, + session_id='session_id_value', + attribution_token='attribution_token_value', + filter='filter_value', + tag_ids=['tag_ids_value'], + promotion_ids=['promotion_ids_value'], + ) + response = client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, user_event.UserEvent) + assert response.event_type == 'event_type_value' + assert response.user_pseudo_id == 'user_pseudo_id_value' + assert response.direct_user_request is True + assert response.session_id == 'session_id_value' + assert response.attribution_token == 'attribution_token_value' + assert response.filter == 'filter_value' + assert response.tag_ids == ['tag_ids_value'] + assert response.promotion_ids == ['promotion_ids_value'] + + +def test_write_user_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + client.write_user_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + +@pytest.mark.asyncio +async def test_write_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.WriteUserEventRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent( + event_type='event_type_value', + user_pseudo_id='user_pseudo_id_value', + direct_user_request=True, + session_id='session_id_value', + attribution_token='attribution_token_value', + filter='filter_value', + tag_ids=['tag_ids_value'], + promotion_ids=['promotion_ids_value'], + )) + response = await client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.WriteUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, user_event.UserEvent) + assert response.event_type == 'event_type_value' + assert response.user_pseudo_id == 'user_pseudo_id_value' + assert response.direct_user_request is True + assert response.session_id == 'session_id_value' + assert response.attribution_token == 'attribution_token_value' + assert response.filter == 'filter_value' + assert response.tag_ids == ['tag_ids_value'] + assert response.promotion_ids == ['promotion_ids_value'] + + +@pytest.mark.asyncio +async def test_write_user_event_async_from_dict(): + await test_write_user_event_async(request_type=dict) + + +def test_write_user_event_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.WriteUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + call.return_value = user_event.UserEvent() + client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_write_user_event_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.WriteUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.write_user_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent()) + await client.write_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + user_event_service.CollectUserEventRequest, + dict, +]) +def test_collect_user_event(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + ) + response = client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +def test_collect_user_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + client.collect_user_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + +@pytest.mark.asyncio +async def test_collect_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.CollectUserEventRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + )) + response = await client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == user_event_service.CollectUserEventRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +@pytest.mark.asyncio +async def test_collect_user_event_async_from_dict(): + await test_collect_user_event_async(request_type=dict) + + +def test_collect_user_event_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.CollectUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + call.return_value = httpbody_pb2.HttpBody() + client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_collect_user_event_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = user_event_service.CollectUserEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.collect_user_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody()) + await client.collect_user_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportUserEventsRequest, + dict, +]) +def test_import_user_events(request_type, transport: str = 'grpc'): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_user_events_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + client.import_user_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportUserEventsRequest() + +@pytest.mark.asyncio +async def test_import_user_events_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportUserEventsRequest): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__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_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == import_config.ImportUserEventsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_user_events_async_from_dict(): + await test_import_user_events_async(request_type=dict) + + +def test_import_user_events_field_headers(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_import_user_events_field_headers_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = import_config.ImportUserEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_user_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.import_user_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + user_event_service.WriteUserEventRequest, + dict, +]) +def test_write_user_event_rest(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + request_init["user_event"] = {'event_type': 'event_type_value', 'user_pseudo_id': 'user_pseudo_id_value', 'event_time': {'seconds': 751, 'nanos': 543}, 'user_info': {'user_id': 'user_id_value', 'user_agent': 'user_agent_value'}, 'direct_user_request': True, 'session_id': 'session_id_value', 'page_info': {'pageview_id': 'pageview_id_value', 'page_category': 'page_category_value', 'uri': 'uri_value', 'referrer_uri': 'referrer_uri_value'}, 'attribution_token': 'attribution_token_value', 'filter': 'filter_value', 'documents': [{'id': 'id_value', 'name': 'name_value', 'uri': 'uri_value', 'quantity': 895, 'promotion_ids': ['promotion_ids_value1', 'promotion_ids_value2']}], 'panel': {'panel_id': 'panel_id_value', 'display_name': 'display_name_value', 'panel_position': 1508, 'total_panels': 1286}, 'search_info': {'search_query': 'search_query_value', 'order_by': 'order_by_value', 'offset': 647}, 'completion_info': {'selected_suggestion': 'selected_suggestion_value', 'selected_position': 1821}, 'transaction_info': {'value': 0.541, 'currency': 'currency_value', 'transaction_id': 'transaction_id_value', 'tax': 0.333, 'cost': 0.441, 'discount_value': 0.1509}, 'tag_ids': ['tag_ids_value1', 'tag_ids_value2'], 'promotion_ids': ['promotion_ids_value1', 'promotion_ids_value2'], 'attributes': {}, 'media_info': {'media_progress_duration': {'seconds': 751, 'nanos': 543}, 'media_progress_percentage': 0.2641}} + # 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 = user_event_service.WriteUserEventRequest.meta.fields["user_event"] + + 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_event"].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_event"][field])): + del request_init["user_event"][field][i][subfield] + else: + del request_init["user_event"][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 = user_event.UserEvent( + event_type='event_type_value', + user_pseudo_id='user_pseudo_id_value', + direct_user_request=True, + session_id='session_id_value', + attribution_token='attribution_token_value', + filter='filter_value', + tag_ids=['tag_ids_value'], + promotion_ids=['promotion_ids_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 = user_event.UserEvent.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.write_user_event(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, user_event.UserEvent) + assert response.event_type == 'event_type_value' + assert response.user_pseudo_id == 'user_pseudo_id_value' + assert response.direct_user_request is True + assert response.session_id == 'session_id_value' + assert response.attribution_token == 'attribution_token_value' + assert response.filter == 'filter_value' + assert response.tag_ids == ['tag_ids_value'] + assert response.promotion_ids == ['promotion_ids_value'] + + +def test_write_user_event_rest_required_fields(request_type=user_event_service.WriteUserEventRequest): + transport_class = transports.UserEventServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).write_user_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).write_user_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = user_event.UserEvent() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 = user_event.UserEvent.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.write_user_event(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_write_user_event_rest_unset_required_fields(): + transport = transports.UserEventServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.write_user_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "userEvent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_write_user_event_rest_interceptors(null_interceptor): + transport = transports.UserEventServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.UserEventServiceRestInterceptor(), + ) + client = UserEventServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.UserEventServiceRestInterceptor, "post_write_user_event") as post, \ + mock.patch.object(transports.UserEventServiceRestInterceptor, "pre_write_user_event") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = user_event_service.WriteUserEventRequest.pb(user_event_service.WriteUserEventRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = user_event.UserEvent.to_json(user_event.UserEvent()) + + request = user_event_service.WriteUserEventRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = user_event.UserEvent() + + client.write_user_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_write_user_event_rest_bad_request(transport: str = 'rest', request_type=user_event_service.WriteUserEventRequest): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.write_user_event(request) + + +def test_write_user_event_rest_error(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + user_event_service.CollectUserEventRequest, + dict, +]) +def test_collect_user_event_rest(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/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 = httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.collect_user_event(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +def test_collect_user_event_rest_required_fields(request_type=user_event_service.CollectUserEventRequest): + transport_class = transports.UserEventServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["user_event"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "userEvent" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).collect_user_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "userEvent" in jsonified_request + assert jsonified_request["userEvent"] == request_init["user_event"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["userEvent"] = 'user_event_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).collect_user_event._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("ets", "uri", "user_event", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "userEvent" in jsonified_request + assert jsonified_request["userEvent"] == 'user_event_value' + + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = httpbody_pb2.HttpBody() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force 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 + + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.collect_user_event(request) + + expected_params = [ + ( + "userEvent", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_collect_user_event_rest_unset_required_fields(): + transport = transports.UserEventServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.collect_user_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(("ets", "uri", "userEvent", )) & set(("parent", "userEvent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_collect_user_event_rest_interceptors(null_interceptor): + transport = transports.UserEventServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.UserEventServiceRestInterceptor(), + ) + client = UserEventServiceClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.UserEventServiceRestInterceptor, "post_collect_user_event") as post, \ + mock.patch.object(transports.UserEventServiceRestInterceptor, "pre_collect_user_event") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = user_event_service.CollectUserEventRequest.pb(user_event_service.CollectUserEventRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(httpbody_pb2.HttpBody()) + + request = user_event_service.CollectUserEventRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = httpbody_pb2.HttpBody() + + client.collect_user_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_collect_user_event_rest_bad_request(transport: str = 'rest', request_type=user_event_service.CollectUserEventRequest): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.collect_user_event(request) + + +def test_collect_user_event_rest_error(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + import_config.ImportUserEventsRequest, + dict, +]) +def test_import_user_events_rest(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.import_user_events(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_import_user_events_rest_required_fields(request_type=import_config.ImportUserEventsRequest): + transport_class = transports.UserEventServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_user_events._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_user_events._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.import_user_events(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_import_user_events_rest_unset_required_fields(): + transport = transports.UserEventServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.import_user_events._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_import_user_events_rest_interceptors(null_interceptor): + transport = transports.UserEventServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.UserEventServiceRestInterceptor(), + ) + client = UserEventServiceClient(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.UserEventServiceRestInterceptor, "post_import_user_events") as post, \ + mock.patch.object(transports.UserEventServiceRestInterceptor, "pre_import_user_events") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = import_config.ImportUserEventsRequest.pb(import_config.ImportUserEventsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = import_config.ImportUserEventsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.import_user_events(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_import_user_events_rest_bad_request(transport: str = 'rest', request_type=import_config.ImportUserEventsRequest): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.import_user_events(request) + + +def test_import_user_events_rest_error(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = UserEventServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = UserEventServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.UserEventServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.UserEventServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, + transports.UserEventServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = UserEventServiceClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.UserEventServiceGrpcTransport, + ) + +def test_user_event_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.UserEventServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_user_event_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.discoveryengine_v1beta.services.user_event_service.transports.UserEventServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.UserEventServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'write_user_event', + 'collect_user_event', + 'import_user_events', + 'get_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_user_event_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.discoveryengine_v1beta.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.UserEventServiceTransport( + 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_user_event_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.discoveryengine_v1beta.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.UserEventServiceTransport() + adc.assert_called_once() + + +def test_user_event_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) + UserEventServiceClient() + 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.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, + ], +) +def test_user_event_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.UserEventServiceGrpcTransport, + transports.UserEventServiceGrpcAsyncIOTransport, + transports.UserEventServiceRestTransport, + ], +) +def test_user_event_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.UserEventServiceGrpcTransport, grpc_helpers), + (transports.UserEventServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_user_event_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( + "discoveryengine.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="discoveryengine.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_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_user_event_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.UserEventServiceRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_user_event_service_rest_lro_client(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_user_event_service_host_no_port(transport_name): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_user_event_service_host_with_port(transport_name): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'discoveryengine.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://discoveryengine.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_user_event_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = UserEventServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = UserEventServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.write_user_event._session + session2 = client2.transport.write_user_event._session + assert session1 != session2 + session1 = client1.transport.collect_user_event._session + session2 = client2.transport.collect_user_event._session + assert session1 != session2 + session1 = client1.transport.import_user_events._session + session2 = client2.transport.import_user_events._session + assert session1 != session2 +def test_user_event_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.UserEventServiceGrpcTransport( + 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_user_event_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.UserEventServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_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.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) +def test_user_event_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_user_event_service_grpc_lro_client(): + client = UserEventServiceClient( + 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_user_event_service_grpc_lro_async_client(): + client = UserEventServiceAsyncClient( + 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_data_store_path(): + project = "squid" + location = "clam" + data_store = "whelk" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) + actual = UserEventServiceClient.data_store_path(project, location, data_store) + assert expected == actual + + +def test_parse_data_store_path(): + expected = { + "project": "octopus", + "location": "oyster", + "data_store": "nudibranch", + } + path = UserEventServiceClient.data_store_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_data_store_path(path) + assert expected == actual + +def test_document_path(): + project = "cuttlefish" + location = "mussel" + data_store = "winkle" + branch = "nautilus" + document = "scallop" + expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) + actual = UserEventServiceClient.document_path(project, location, data_store, branch, document) + assert expected == actual + + +def test_parse_document_path(): + expected = { + "project": "abalone", + "location": "squid", + "data_store": "clam", + "branch": "whelk", + "document": "octopus", + } + path = UserEventServiceClient.document_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_document_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = UserEventServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = UserEventServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = UserEventServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = UserEventServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = UserEventServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = UserEventServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = UserEventServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = UserEventServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = UserEventServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = UserEventServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = UserEventServiceClient.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.UserEventServiceTransport, '_prep_wrapped_messages') as prep: + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = UserEventServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_get_operation(transport: str = "grpc"): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc"): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = UserEventServiceClient( + 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 = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc"): + client = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = UserEventServiceClient( + 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 = UserEventServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = UserEventServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = UserEventServiceClient( + 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", [ + (UserEventServiceClient, transports.UserEventServiceGrpcTransport), + (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) From f100b34006db13fe311a5f25f9e373fee6d65b41 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Mon, 13 Nov 2023 20:55:18 +0000 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20po?= =?UTF-8?q?st-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .../v1/.coveragerc | 13 - .../google-cloud-discoveryengine/v1/.flake8 | 33 - .../v1/MANIFEST.in | 2 - .../v1/README.rst | 49 - .../v1/docs/_static/custom.css | 3 - .../v1/docs/conf.py | 376 - .../discoveryengine_v1/completion_service.rst | 6 - .../conversational_search_service.rst | 10 - .../discoveryengine_v1/document_service.rst | 10 - .../discoveryengine_v1/schema_service.rst | 10 - .../discoveryengine_v1/search_service.rst | 10 - .../v1/docs/discoveryengine_v1/services_.rst | 11 - .../v1/docs/discoveryengine_v1/types_.rst | 6 - .../discoveryengine_v1/user_event_service.rst | 6 - .../v1/docs/index.rst | 7 - .../google/cloud/discoveryengine/__init__.py | 165 - .../cloud/discoveryengine/gapic_version.py | 16 - .../v1/google/cloud/discoveryengine/py.typed | 2 - .../cloud/discoveryengine_v1/__init__.py | 166 - .../discoveryengine_v1/gapic_metadata.json | 468 -- .../cloud/discoveryengine_v1/gapic_version.py | 16 - .../google/cloud/discoveryengine_v1/py.typed | 2 - .../discoveryengine_v1/services/__init__.py | 15 - .../services/completion_service/__init__.py | 22 - .../completion_service/async_client.py | 386 - .../services/completion_service/client.py | 594 -- .../completion_service/transports/__init__.py | 38 - .../completion_service/transports/base.py | 168 - .../completion_service/transports/grpc.py | 303 - .../transports/grpc_asyncio.py | 302 - .../completion_service/transports/rest.py | 574 -- .../conversational_search_service/__init__.py | 22 - .../async_client.py | 971 --- .../conversational_search_service/client.py | 1205 ---- .../conversational_search_service/pagers.py | 140 - .../transports/__init__.py | 38 - .../transports/base.py | 241 - .../transports/grpc.py | 449 -- .../transports/grpc_asyncio.py | 448 -- .../transports/rest.py | 1164 --- .../services/document_service/__init__.py | 22 - .../services/document_service/async_client.py | 1109 --- .../services/document_service/client.py | 1322 ---- .../services/document_service/pagers.py | 140 - .../document_service/transports/__init__.py | 38 - .../document_service/transports/base.py | 269 - .../document_service/transports/grpc.py | 509 -- .../transports/grpc_asyncio.py | 508 -- .../document_service/transports/rest.py | 1445 ---- .../services/schema_service/__init__.py | 22 - .../services/schema_service/async_client.py | 902 --- .../services/schema_service/client.py | 1119 --- .../services/schema_service/pagers.py | 140 - .../schema_service/transports/__init__.py | 38 - .../schema_service/transports/base.py | 231 - .../schema_service/transports/grpc.py | 427 -- .../schema_service/transports/grpc_asyncio.py | 426 -- .../schema_service/transports/rest.py | 1208 ---- .../services/search_service/__init__.py | 22 - .../services/search_service/async_client.py | 402 -- .../services/search_service/client.py | 628 -- .../services/search_service/pagers.py | 139 - .../search_service/transports/__init__.py | 38 - .../search_service/transports/base.py | 168 - .../search_service/transports/grpc.py | 302 - .../search_service/transports/grpc_asyncio.py | 301 - .../search_service/transports/rest.py | 584 -- .../services/user_event_service/__init__.py | 22 - .../user_event_service/async_client.py | 644 -- .../services/user_event_service/client.py | 857 --- .../user_event_service/transports/__init__.py | 38 - .../user_event_service/transports/base.py | 211 - .../user_event_service/transports/grpc.py | 389 - .../transports/grpc_asyncio.py | 388 - .../user_event_service/transports/rest.py | 1021 --- .../discoveryengine_v1/types/__init__.py | 162 - .../cloud/discoveryengine_v1/types/common.py | 167 - .../types/completion_service.py | 158 - .../discoveryengine_v1/types/conversation.py | 204 - .../types/conversational_search_service.py | 322 - .../discoveryengine_v1/types/document.py | 189 - .../types/document_service.py | 262 - .../discoveryengine_v1/types/import_config.py | 604 -- .../discoveryengine_v1/types/purge_config.py | 133 - .../cloud/discoveryengine_v1/types/schema.py | 78 - .../types/schema_service.py | 289 - .../types/search_service.py | 1089 --- .../discoveryengine_v1/types/user_event.py | 754 -- .../types/user_event_service.py | 110 - .../google-cloud-discoveryengine/v1/mypy.ini | 3 - .../v1/noxfile.py | 184 - ...completion_service_complete_query_async.py | 53 - ..._completion_service_complete_query_sync.py | 53 - ...rch_service_converse_conversation_async.py | 52 - ...arch_service_converse_conversation_sync.py | 52 - ...earch_service_create_conversation_async.py | 52 - ...search_service_create_conversation_sync.py | 52 - ...earch_service_delete_conversation_async.py | 50 - ...search_service_delete_conversation_sync.py | 50 - ...l_search_service_get_conversation_async.py | 52 - ...al_search_service_get_conversation_sync.py | 52 - ...search_service_list_conversations_async.py | 53 - ..._search_service_list_conversations_sync.py | 53 - ...earch_service_update_conversation_async.py | 51 - ...search_service_update_conversation_sync.py | 51 - ..._document_service_create_document_async.py | 53 - ...d_document_service_create_document_sync.py | 53 - ..._document_service_delete_document_async.py | 50 - ...d_document_service_delete_document_sync.py | 50 - ...ted_document_service_get_document_async.py | 52 - ...ated_document_service_get_document_sync.py | 52 - ...document_service_import_documents_async.py | 56 - ..._document_service_import_documents_sync.py | 56 - ...d_document_service_list_documents_async.py | 53 - ...ed_document_service_list_documents_sync.py | 53 - ..._document_service_purge_documents_async.py | 57 - ...d_document_service_purge_documents_sync.py | 57 - ..._document_service_update_document_async.py | 51 - ...d_document_service_update_document_sync.py | 51 - ...ated_schema_service_create_schema_async.py | 57 - ...rated_schema_service_create_schema_sync.py | 57 - ...ated_schema_service_delete_schema_async.py | 56 - ...rated_schema_service_delete_schema_sync.py | 56 - ...nerated_schema_service_get_schema_async.py | 52 - ...enerated_schema_service_get_schema_sync.py | 52 - ...rated_schema_service_list_schemas_async.py | 53 - ...erated_schema_service_list_schemas_sync.py | 53 - ...ated_schema_service_update_schema_async.py | 55 - ...rated_schema_service_update_schema_sync.py | 55 - ...1_generated_search_service_search_async.py | 53 - ...v1_generated_search_service_search_sync.py | 53 - ..._event_service_collect_user_event_async.py | 53 - ...r_event_service_collect_user_event_sync.py | 53 - ..._event_service_import_user_events_async.py | 61 - ...r_event_service_import_user_events_sync.py | 61 - ...er_event_service_write_user_event_async.py | 52 - ...ser_event_service_write_user_event_sync.py | 52 - ...adata_google.cloud.discoveryengine.v1.json | 3690 ---------- .../fixup_discoveryengine_v1_keywords.py | 198 - .../google-cloud-discoveryengine/v1/setup.py | 90 - .../v1/testing/constraints-3.10.txt | 6 - .../v1/testing/constraints-3.11.txt | 6 - .../v1/testing/constraints-3.12.txt | 6 - .../v1/testing/constraints-3.7.txt | 9 - .../v1/testing/constraints-3.8.txt | 6 - .../v1/testing/constraints-3.9.txt | 6 - .../v1/tests/__init__.py | 16 - .../v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../unit/gapic/discoveryengine_v1/__init__.py | 16 - .../test_completion_service.py | 1920 ----- .../test_conversational_search_service.py | 4902 ------------- .../test_document_service.py | 4999 ------------- .../discoveryengine_v1/test_schema_service.py | 4265 ----------- .../discoveryengine_v1/test_search_service.py | 2233 ------ .../test_user_event_service.py | 2786 -------- .../v1alpha/.coveragerc | 13 - .../v1alpha/.flake8 | 33 - .../v1alpha/MANIFEST.in | 2 - .../v1alpha/README.rst | 49 - .../v1alpha/docs/_static/custom.css | 3 - .../v1alpha/docs/conf.py | 376 - .../completion_service.rst | 6 - .../conversational_search_service.rst | 10 - .../document_service.rst | 10 - .../recommendation_service.rst | 6 - .../schema_service.rst | 10 - .../search_service.rst | 10 - .../discoveryengine_v1alpha/services_.rst | 15 - .../site_search_engine_service.rst | 6 - .../docs/discoveryengine_v1alpha/types_.rst | 6 - .../user_event_service.rst | 6 - .../v1alpha/docs/index.rst | 7 - .../google/cloud/discoveryengine/__init__.py | 255 - .../cloud/discoveryengine/gapic_version.py | 16 - .../google/cloud/discoveryengine/py.typed | 2 - .../cloud/discoveryengine_v1alpha/__init__.py | 256 - .../gapic_metadata.json | 784 -- .../discoveryengine_v1alpha/gapic_version.py | 16 - .../cloud/discoveryengine_v1alpha/py.typed | 2 - .../services/__init__.py | 15 - .../services/completion_service/__init__.py | 22 - .../completion_service/async_client.py | 386 - .../services/completion_service/client.py | 594 -- .../completion_service/transports/__init__.py | 38 - .../completion_service/transports/base.py | 168 - .../completion_service/transports/grpc.py | 303 - .../transports/grpc_asyncio.py | 302 - .../completion_service/transports/rest.py | 566 -- .../conversational_search_service/__init__.py | 22 - .../async_client.py | 971 --- .../conversational_search_service/client.py | 1205 ---- .../conversational_search_service/pagers.py | 140 - .../transports/__init__.py | 38 - .../transports/base.py | 241 - .../transports/grpc.py | 449 -- .../transports/grpc_asyncio.py | 448 -- .../transports/rest.py | 1156 --- .../services/document_service/__init__.py | 22 - .../services/document_service/async_client.py | 1113 --- .../services/document_service/client.py | 1326 ---- .../services/document_service/pagers.py | 140 - .../document_service/transports/__init__.py | 38 - .../document_service/transports/base.py | 269 - .../document_service/transports/grpc.py | 513 -- .../transports/grpc_asyncio.py | 512 -- .../document_service/transports/rest.py | 1429 ---- .../recommendation_service/__init__.py | 22 - .../recommendation_service/async_client.py | 389 - .../services/recommendation_service/client.py | 606 -- .../transports/__init__.py | 38 - .../recommendation_service/transports/base.py | 168 - .../recommendation_service/transports/grpc.py | 303 - .../transports/grpc_asyncio.py | 302 - .../recommendation_service/transports/rest.py | 578 -- .../services/schema_service/__init__.py | 22 - .../services/schema_service/async_client.py | 902 --- .../services/schema_service/client.py | 1119 --- .../services/schema_service/pagers.py | 140 - .../schema_service/transports/__init__.py | 38 - .../schema_service/transports/base.py | 231 - .../schema_service/transports/grpc.py | 427 -- .../schema_service/transports/grpc_asyncio.py | 426 -- .../schema_service/transports/rest.py | 1192 ---- .../services/search_service/__init__.py | 22 - .../services/search_service/async_client.py | 402 -- .../services/search_service/client.py | 628 -- .../services/search_service/pagers.py | 139 - .../search_service/transports/__init__.py | 38 - .../search_service/transports/base.py | 168 - .../search_service/transports/grpc.py | 302 - .../search_service/transports/grpc_asyncio.py | 301 - .../search_service/transports/rest.py | 581 -- .../site_search_engine_service/__init__.py | 22 - .../async_client.py | 401 -- .../site_search_engine_service/client.py | 609 -- .../transports/__init__.py | 38 - .../transports/base.py | 174 - .../transports/grpc.py | 320 - .../transports/grpc_asyncio.py | 319 - .../transports/rest.py | 709 -- .../services/user_event_service/__init__.py | 22 - .../user_event_service/async_client.py | 746 -- .../services/user_event_service/client.py | 960 --- .../user_event_service/transports/__init__.py | 38 - .../user_event_service/transports/base.py | 226 - .../user_event_service/transports/grpc.py | 420 -- .../transports/grpc_asyncio.py | 419 -- .../user_event_service/transports/rest.py | 1132 --- .../discoveryengine_v1alpha/types/__init__.py | 248 - .../discoveryengine_v1alpha/types/common.py | 257 - .../types/completion_service.py | 169 - .../types/conversation.py | 248 - .../types/conversational_search_service.py | 328 - .../discoveryengine_v1alpha/types/document.py | 189 - .../types/document_service.py | 266 - .../types/import_config.py | 607 -- .../types/purge_config.py | 247 - .../types/recommendation_service.py | 287 - .../discoveryengine_v1alpha/types/schema.py | 413 -- .../types/schema_service.py | 291 - .../types/search_service.py | 1365 ---- .../types/site_search_engine_service.py | 211 - .../types/user_event.py | 761 -- .../types/user_event_service.py | 110 - .../v1alpha/mypy.ini | 3 - .../v1alpha/noxfile.py | 184 - ...completion_service_complete_query_async.py | 53 - ..._completion_service_complete_query_sync.py | 53 - ...rch_service_converse_conversation_async.py | 52 - ...arch_service_converse_conversation_sync.py | 52 - ...earch_service_create_conversation_async.py | 52 - ...search_service_create_conversation_sync.py | 52 - ...earch_service_delete_conversation_async.py | 50 - ...search_service_delete_conversation_sync.py | 50 - ...l_search_service_get_conversation_async.py | 52 - ...al_search_service_get_conversation_sync.py | 52 - ...search_service_list_conversations_async.py | 53 - ..._search_service_list_conversations_sync.py | 53 - ...earch_service_update_conversation_async.py | 51 - ...search_service_update_conversation_sync.py | 51 - ..._document_service_create_document_async.py | 53 - ...d_document_service_create_document_sync.py | 53 - ..._document_service_delete_document_async.py | 50 - ...d_document_service_delete_document_sync.py | 50 - ...ted_document_service_get_document_async.py | 52 - ...ated_document_service_get_document_sync.py | 52 - ...document_service_import_documents_async.py | 56 - ..._document_service_import_documents_sync.py | 56 - ...d_document_service_list_documents_async.py | 53 - ...ed_document_service_list_documents_sync.py | 53 - ..._document_service_purge_documents_async.py | 57 - ...d_document_service_purge_documents_sync.py | 57 - ..._document_service_update_document_async.py | 51 - ...d_document_service_update_document_sync.py | 51 - ..._recommendation_service_recommend_async.py | 57 - ...d_recommendation_service_recommend_sync.py | 57 - ...ated_schema_service_create_schema_async.py | 57 - ...rated_schema_service_create_schema_sync.py | 57 - ...ated_schema_service_delete_schema_async.py | 56 - ...rated_schema_service_delete_schema_sync.py | 56 - ...nerated_schema_service_get_schema_async.py | 52 - ...enerated_schema_service_get_schema_sync.py | 52 - ...rated_schema_service_list_schemas_async.py | 53 - ...erated_schema_service_list_schemas_sync.py | 53 - ...ated_schema_service_update_schema_async.py | 55 - ...rated_schema_service_update_schema_sync.py | 55 - ...a_generated_search_service_search_async.py | 53 - ...ha_generated_search_service_search_sync.py | 53 - ...earch_engine_service_recrawl_uris_async.py | 57 - ...search_engine_service_recrawl_uris_sync.py | 57 - ..._event_service_collect_user_event_async.py | 53 - ...r_event_service_collect_user_event_sync.py | 53 - ..._event_service_import_user_events_async.py | 61 - ...r_event_service_import_user_events_sync.py | 61 - ...r_event_service_purge_user_events_async.py | 57 - ...er_event_service_purge_user_events_sync.py | 57 - ...er_event_service_write_user_event_async.py | 52 - ...ser_event_service_write_user_event_sync.py | 52 - ..._google.cloud.discoveryengine.v1alpha.json | 6290 ----------------- .../fixup_discoveryengine_v1alpha_keywords.py | 214 - .../v1alpha/setup.py | 90 - .../v1alpha/testing/constraints-3.10.txt | 6 - .../v1alpha/testing/constraints-3.11.txt | 6 - .../v1alpha/testing/constraints-3.12.txt | 6 - .../v1alpha/testing/constraints-3.7.txt | 9 - .../v1alpha/testing/constraints-3.8.txt | 6 - .../v1alpha/testing/constraints-3.9.txt | 6 - .../v1alpha/tests/__init__.py | 16 - .../v1alpha/tests/unit/__init__.py | 16 - .../v1alpha/tests/unit/gapic/__init__.py | 16 - .../gapic/discoveryengine_v1alpha/__init__.py | 16 - .../test_completion_service.py | 1920 ----- .../test_conversational_search_service.py | 4908 ------------- .../test_document_service.py | 4999 ------------- .../test_recommendation_service.py | 1952 ----- .../test_schema_service.py | 4265 ----------- .../test_search_service.py | 2239 ------ .../test_site_search_engine_service.py | 1961 ----- .../test_user_event_service.py | 3118 -------- .../v1beta/.coveragerc | 13 - .../v1beta/.flake8 | 33 - .../v1beta/MANIFEST.in | 2 - .../v1beta/README.rst | 49 - .../v1beta/docs/_static/custom.css | 3 - .../v1beta/docs/conf.py | 376 - .../completion_service.rst | 6 - .../conversational_search_service.rst | 10 - .../document_service.rst | 10 - .../recommendation_service.rst | 6 - .../discoveryengine_v1beta/schema_service.rst | 10 - .../discoveryengine_v1beta/search_service.rst | 10 - .../docs/discoveryengine_v1beta/services_.rst | 12 - .../docs/discoveryengine_v1beta/types_.rst | 6 - .../user_event_service.rst | 6 - .../v1beta/docs/index.rst | 7 - .../google/cloud/discoveryengine/__init__.py | 175 - .../cloud/discoveryengine/gapic_version.py | 16 - .../google/cloud/discoveryengine/py.typed | 2 - .../cloud/discoveryengine_v1beta/__init__.py | 176 - .../gapic_metadata.json | 502 -- .../discoveryengine_v1beta/gapic_version.py | 16 - .../cloud/discoveryengine_v1beta/py.typed | 2 - .../services/__init__.py | 15 - .../services/completion_service/__init__.py | 22 - .../completion_service/async_client.py | 386 - .../services/completion_service/client.py | 594 -- .../completion_service/transports/__init__.py | 38 - .../completion_service/transports/base.py | 168 - .../completion_service/transports/grpc.py | 303 - .../transports/grpc_asyncio.py | 302 - .../completion_service/transports/rest.py | 566 -- .../conversational_search_service/__init__.py | 22 - .../async_client.py | 971 --- .../conversational_search_service/client.py | 1205 ---- .../conversational_search_service/pagers.py | 140 - .../transports/__init__.py | 38 - .../transports/base.py | 241 - .../transports/grpc.py | 449 -- .../transports/grpc_asyncio.py | 448 -- .../transports/rest.py | 1156 --- .../services/document_service/__init__.py | 22 - .../services/document_service/async_client.py | 1112 --- .../services/document_service/client.py | 1325 ---- .../services/document_service/pagers.py | 140 - .../document_service/transports/__init__.py | 38 - .../document_service/transports/base.py | 269 - .../document_service/transports/grpc.py | 512 -- .../transports/grpc_asyncio.py | 511 -- .../document_service/transports/rest.py | 1429 ---- .../recommendation_service/__init__.py | 22 - .../recommendation_service/async_client.py | 389 - .../services/recommendation_service/client.py | 606 -- .../transports/__init__.py | 38 - .../recommendation_service/transports/base.py | 168 - .../recommendation_service/transports/grpc.py | 303 - .../transports/grpc_asyncio.py | 302 - .../recommendation_service/transports/rest.py | 573 -- .../services/schema_service/__init__.py | 22 - .../services/schema_service/async_client.py | 902 --- .../services/schema_service/client.py | 1119 --- .../services/schema_service/pagers.py | 140 - .../schema_service/transports/__init__.py | 38 - .../schema_service/transports/base.py | 231 - .../schema_service/transports/grpc.py | 427 -- .../schema_service/transports/grpc_asyncio.py | 426 -- .../schema_service/transports/rest.py | 1192 ---- .../services/search_service/__init__.py | 22 - .../services/search_service/async_client.py | 402 -- .../services/search_service/client.py | 628 -- .../services/search_service/pagers.py | 139 - .../search_service/transports/__init__.py | 38 - .../search_service/transports/base.py | 168 - .../search_service/transports/grpc.py | 302 - .../search_service/transports/grpc_asyncio.py | 301 - .../search_service/transports/rest.py | 576 -- .../services/user_event_service/__init__.py | 22 - .../user_event_service/async_client.py | 644 -- .../services/user_event_service/client.py | 857 --- .../user_event_service/transports/__init__.py | 38 - .../user_event_service/transports/base.py | 211 - .../user_event_service/transports/grpc.py | 389 - .../transports/grpc_asyncio.py | 388 - .../user_event_service/transports/rest.py | 1005 --- .../discoveryengine_v1beta/types/__init__.py | 170 - .../discoveryengine_v1beta/types/common.py | 182 - .../types/completion_service.py | 158 - .../types/conversation.py | 248 - .../types/conversational_search_service.py | 328 - .../discoveryengine_v1beta/types/document.py | 189 - .../types/document_service.py | 265 - .../types/import_config.py | 607 -- .../types/purge_config.py | 133 - .../types/recommendation_service.py | 264 - .../discoveryengine_v1beta/types/schema.py | 78 - .../types/schema_service.py | 291 - .../types/search_service.py | 1312 ---- .../types/user_event.py | 758 -- .../types/user_event_service.py | 110 - .../v1beta/mypy.ini | 3 - .../v1beta/noxfile.py | 184 - ...completion_service_complete_query_async.py | 53 - ..._completion_service_complete_query_sync.py | 53 - ...rch_service_converse_conversation_async.py | 52 - ...arch_service_converse_conversation_sync.py | 52 - ...earch_service_create_conversation_async.py | 52 - ...search_service_create_conversation_sync.py | 52 - ...earch_service_delete_conversation_async.py | 50 - ...search_service_delete_conversation_sync.py | 50 - ...l_search_service_get_conversation_async.py | 52 - ...al_search_service_get_conversation_sync.py | 52 - ...search_service_list_conversations_async.py | 53 - ..._search_service_list_conversations_sync.py | 53 - ...earch_service_update_conversation_async.py | 51 - ...search_service_update_conversation_sync.py | 51 - ..._document_service_create_document_async.py | 53 - ...d_document_service_create_document_sync.py | 53 - ..._document_service_delete_document_async.py | 50 - ...d_document_service_delete_document_sync.py | 50 - ...ted_document_service_get_document_async.py | 52 - ...ated_document_service_get_document_sync.py | 52 - ...document_service_import_documents_async.py | 56 - ..._document_service_import_documents_sync.py | 56 - ...d_document_service_list_documents_async.py | 53 - ...ed_document_service_list_documents_sync.py | 53 - ..._document_service_purge_documents_async.py | 57 - ...d_document_service_purge_documents_sync.py | 57 - ..._document_service_update_document_async.py | 51 - ...d_document_service_update_document_sync.py | 51 - ..._recommendation_service_recommend_async.py | 57 - ...d_recommendation_service_recommend_sync.py | 57 - ...ated_schema_service_create_schema_async.py | 57 - ...rated_schema_service_create_schema_sync.py | 57 - ...ated_schema_service_delete_schema_async.py | 56 - ...rated_schema_service_delete_schema_sync.py | 56 - ...nerated_schema_service_get_schema_async.py | 52 - ...enerated_schema_service_get_schema_sync.py | 52 - ...rated_schema_service_list_schemas_async.py | 53 - ...erated_schema_service_list_schemas_sync.py | 53 - ...ated_schema_service_update_schema_async.py | 55 - ...rated_schema_service_update_schema_sync.py | 55 - ...a_generated_search_service_search_async.py | 53 - ...ta_generated_search_service_search_sync.py | 53 - ..._event_service_collect_user_event_async.py | 53 - ...r_event_service_collect_user_event_sync.py | 53 - ..._event_service_import_user_events_async.py | 61 - ...r_event_service_import_user_events_sync.py | 61 - ...er_event_service_write_user_event_async.py | 52 - ...ser_event_service_write_user_event_sync.py | 52 - ...a_google.cloud.discoveryengine.v1beta.json | 3843 ---------- .../fixup_discoveryengine_v1beta_keywords.py | 199 - .../v1beta/setup.py | 90 - .../v1beta/testing/constraints-3.10.txt | 6 - .../v1beta/testing/constraints-3.11.txt | 6 - .../v1beta/testing/constraints-3.12.txt | 6 - .../v1beta/testing/constraints-3.7.txt | 9 - .../v1beta/testing/constraints-3.8.txt | 6 - .../v1beta/testing/constraints-3.9.txt | 6 - .../v1beta/tests/__init__.py | 16 - .../v1beta/tests/unit/__init__.py | 16 - .../v1beta/tests/unit/gapic/__init__.py | 16 - .../gapic/discoveryengine_v1beta/__init__.py | 16 - .../test_completion_service.py | 1920 ----- .../test_conversational_search_service.py | 4908 ------------- .../test_document_service.py | 4999 ------------- .../test_recommendation_service.py | 1952 ----- .../test_schema_service.py | 4265 ----------- .../test_search_service.py | 2239 ------ .../test_user_event_service.py | 2786 -------- .../data_store_service.rst | 0 .../engine_service.rst | 0 .../discoveryengine_v1alpha/services_.rst | 2 + .../cloud/discoveryengine_v1alpha/__init__.py | 73 +- .../gapic_metadata.json | 233 + .../services/data_store_service/__init__.py | 6 +- .../data_store_service/async_client.py | 267 +- .../services/data_store_service/client.py | 395 +- .../services/data_store_service/pagers.py | 49 +- .../data_store_service/transports/__init__.py | 20 +- .../data_store_service/transports/base.py | 158 +- .../data_store_service/transports/grpc.py | 169 +- .../transports/grpc_asyncio.py | 165 +- .../data_store_service/transports/rest.py | 931 +-- .../services/engine_service/__init__.py | 6 +- .../services/engine_service/async_client.py | 340 +- .../services/engine_service/client.py | 472 +- .../services/engine_service/pagers.py | 49 +- .../engine_service/transports/__init__.py | 20 +- .../engine_service/transports/base.py | 192 +- .../engine_service/transports/grpc.py | 200 +- .../engine_service/transports/grpc_asyncio.py | 203 +- .../engine_service/transports/rest.py | 1081 +-- .../discoveryengine_v1alpha/types/__init__.py | 64 +- .../discoveryengine_v1alpha/types/common.py | 54 + .../types/data_store.py | 8 +- .../types/data_store_service.py | 23 +- .../discoveryengine_v1alpha/types/engine.py | 56 +- .../types/engine_service.py | 36 +- .../types/recommendation_service.py | 15 +- .../types/search_service.py | 30 +- .../google-cloud-discoveryengine/noxfile.py | 3 + ...a_store_service_create_data_store_async.py | 0 ...ta_store_service_create_data_store_sync.py | 0 ...a_store_service_delete_data_store_async.py | 0 ...ta_store_service_delete_data_store_sync.py | 0 ...data_store_service_get_data_store_async.py | 0 ..._data_store_service_get_data_store_sync.py | 0 ...ta_store_service_list_data_stores_async.py | 0 ...ata_store_service_list_data_stores_sync.py | 0 ...a_store_service_update_data_store_async.py | 0 ...ta_store_service_update_data_store_sync.py | 0 ...ated_engine_service_create_engine_async.py | 0 ...rated_engine_service_create_engine_sync.py | 0 ...ated_engine_service_delete_engine_async.py | 0 ...rated_engine_service_delete_engine_sync.py | 0 ...nerated_engine_service_get_engine_async.py | 0 ...enerated_engine_service_get_engine_sync.py | 0 ...rated_engine_service_list_engines_async.py | 0 ...erated_engine_service_list_engines_sync.py | 0 ...rated_engine_service_pause_engine_async.py | 0 ...erated_engine_service_pause_engine_sync.py | 0 ...ated_engine_service_resume_engine_async.py | 0 ...rated_engine_service_resume_engine_sync.py | 0 ...erated_engine_service_tune_engine_async.py | 0 ...nerated_engine_service_tune_engine_sync.py | 0 ...ated_engine_service_update_engine_async.py | 0 ...rated_engine_service_update_engine_sync.py | 0 ..._google.cloud.discoveryengine.v1alpha.json | 2651 ++++++- .../fixup_discoveryengine_v1alpha_keywords.py | 13 + .../test_data_store_service.py | 2479 ++++--- .../test_engine_service.py | 3240 +++++---- 571 files changed, 9129 insertions(+), 194871 deletions(-) delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/.coveragerc delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/.flake8 delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/MANIFEST.in delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/README.rst delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/docs/conf.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/completion_service.rst delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/conversational_search_service.rst delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/document_service.rst delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/schema_service.rst delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/search_service.rst delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/services_.rst delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/types_.rst delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/user_event_service.rst delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/docs/index.rst delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine/py.typed delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/py.typed delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/async_client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/async_client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/pagers.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/async_client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/pagers.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/async_client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/pagers.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/async_client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/pagers.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/async_client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/common.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/completion_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/conversation.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/conversational_search_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/document.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/document_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/import_config.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/purge_config.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/schema.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/schema_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/search_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/user_event.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/user_event_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/mypy.ini delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/noxfile.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_completion_service_complete_query_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_completion_service_complete_query_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_converse_conversation_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_converse_conversation_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_create_conversation_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_create_conversation_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_delete_conversation_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_delete_conversation_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_get_conversation_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_get_conversation_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_list_conversations_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_list_conversations_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_update_conversation_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_update_conversation_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_create_document_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_create_document_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_delete_document_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_delete_document_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_get_document_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_get_document_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_import_documents_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_import_documents_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_list_documents_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_list_documents_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_purge_documents_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_purge_documents_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_update_document_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_update_document_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_create_schema_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_create_schema_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_delete_schema_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_delete_schema_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_get_schema_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_get_schema_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_list_schemas_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_list_schemas_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_update_schema_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_update_schema_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_search_service_search_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_search_service_search_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_collect_user_event_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_collect_user_event_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_import_user_events_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_import_user_events_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_write_user_event_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_write_user_event_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1.json delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/scripts/fixup_discoveryengine_v1_keywords.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/setup.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/tests/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_completion_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_conversational_search_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_document_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_schema_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_search_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_user_event_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/.coveragerc delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/.flake8 delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/MANIFEST.in delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/README.rst delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/conf.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/completion_service.rst delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/conversational_search_service.rst delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/document_service.rst delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/recommendation_service.rst delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/schema_service.rst delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/search_service.rst delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/services_.rst delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/site_search_engine_service.rst delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/types_.rst delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/user_event_service.rst delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/index.rst delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine/py.typed delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/gapic_metadata.json delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/py.typed delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/async_client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/async_client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/pagers.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/async_client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/pagers.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/async_client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/async_client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/pagers.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/async_client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/pagers.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/async_client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/async_client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/common.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/completion_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/conversation.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/conversational_search_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/document.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/document_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/import_config.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/purge_config.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/recommendation_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/schema.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/schema_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/search_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/site_search_engine_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/user_event.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/user_event_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/mypy.ini delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/noxfile.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_completion_service_complete_query_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_completion_service_complete_query_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_converse_conversation_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_converse_conversation_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_create_conversation_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_create_conversation_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_delete_conversation_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_delete_conversation_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_get_conversation_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_get_conversation_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_list_conversations_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_list_conversations_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_update_conversation_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_update_conversation_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_create_document_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_create_document_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_delete_document_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_delete_document_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_get_document_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_get_document_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_import_documents_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_import_documents_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_list_documents_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_list_documents_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_purge_documents_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_purge_documents_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_update_document_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_update_document_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_recommendation_service_recommend_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_recommendation_service_recommend_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_create_schema_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_create_schema_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_delete_schema_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_delete_schema_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_get_schema_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_get_schema_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_list_schemas_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_list_schemas_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_update_schema_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_update_schema_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_search_service_search_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_search_service_search_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_site_search_engine_service_recrawl_uris_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_site_search_engine_service_recrawl_uris_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_collect_user_event_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_collect_user_event_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_import_user_events_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_import_user_events_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_purge_user_events_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_purge_user_events_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_write_user_event_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_write_user_event_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1alpha.json delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/scripts/fixup_discoveryengine_v1alpha_keywords.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/setup.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_completion_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_conversational_search_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_document_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_recommendation_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_schema_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_search_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_site_search_engine_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_user_event_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/.coveragerc delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/.flake8 delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/MANIFEST.in delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/README.rst delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/conf.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/completion_service.rst delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/conversational_search_service.rst delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/document_service.rst delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/recommendation_service.rst delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/schema_service.rst delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/search_service.rst delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/services_.rst delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/types_.rst delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/user_event_service.rst delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/index.rst delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine/py.typed delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/gapic_metadata.json delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/py.typed delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/async_client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/async_client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/pagers.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/async_client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/pagers.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/async_client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/async_client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/pagers.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/async_client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/pagers.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/async_client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/client.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/common.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/completion_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/conversation.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/conversational_search_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/document.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/document_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/import_config.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/purge_config.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/recommendation_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/schema.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/schema_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/search_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/user_event.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/user_event_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/mypy.ini delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/noxfile.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_completion_service_complete_query_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_completion_service_complete_query_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_converse_conversation_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_converse_conversation_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_create_conversation_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_create_conversation_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_delete_conversation_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_delete_conversation_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_get_conversation_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_get_conversation_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_list_conversations_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_list_conversations_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_update_conversation_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_update_conversation_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_create_document_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_create_document_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_delete_document_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_delete_document_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_get_document_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_get_document_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_import_documents_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_import_documents_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_list_documents_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_list_documents_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_purge_documents_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_purge_documents_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_update_document_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_update_document_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_recommendation_service_recommend_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_recommendation_service_recommend_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_create_schema_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_create_schema_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_delete_schema_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_delete_schema_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_get_schema_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_get_schema_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_list_schemas_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_list_schemas_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_update_schema_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_update_schema_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_search_service_search_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_search_service_search_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_collect_user_event_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_collect_user_event_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_import_user_events_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_import_user_events_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_write_user_event_async.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_write_user_event_sync.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1beta.json delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/scripts/fixup_discoveryengine_v1beta_keywords.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/setup.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/__init__.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_completion_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_conversational_search_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_document_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_recommendation_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_schema_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_search_service.py delete mode 100644 owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_user_event_service.py rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/docs/discoveryengine_v1alpha/data_store_service.rst (100%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/docs/discoveryengine_v1alpha/engine_service.rst (100%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/google/cloud/discoveryengine_v1alpha/services/data_store_service/__init__.py (91%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/google/cloud/discoveryengine_v1alpha/services/data_store_service/async_client.py (86%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/google/cloud/discoveryengine_v1alpha/services/data_store_service/client.py (83%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/google/cloud/discoveryengine_v1alpha/services/data_store_service/pagers.py (84%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/__init__.py (67%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/base.py (64%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/grpc.py (80%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/grpc_asyncio.py (80%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/rest.py (58%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/google/cloud/discoveryengine_v1alpha/services/engine_service/__init__.py (92%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/google/cloud/discoveryengine_v1alpha/services/engine_service/async_client.py (86%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/google/cloud/discoveryengine_v1alpha/services/engine_service/client.py (83%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/google/cloud/discoveryengine_v1alpha/services/engine_service/pagers.py (84%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/__init__.py (68%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/base.py (63%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/grpc.py (79%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/grpc_asyncio.py (78%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/rest.py (62%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/google/cloud/discoveryengine_v1alpha/types/data_store.py (98%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/google/cloud/discoveryengine_v1alpha/types/data_store_service.py (97%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/google/cloud/discoveryengine_v1alpha/types/engine.py (94%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/google/cloud/discoveryengine_v1alpha/types/engine_service.py (95%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_create_data_store_async.py (100%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_create_data_store_sync.py (100%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_delete_data_store_async.py (100%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_delete_data_store_sync.py (100%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_get_data_store_async.py (100%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_get_data_store_sync.py (100%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_list_data_stores_async.py (100%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_list_data_stores_sync.py (100%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_update_data_store_async.py (100%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_update_data_store_sync.py (100%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_create_engine_async.py (100%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_create_engine_sync.py (100%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_delete_engine_async.py (100%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_delete_engine_sync.py (100%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_get_engine_async.py (100%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_get_engine_sync.py (100%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_list_engines_async.py (100%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_list_engines_sync.py (100%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_pause_engine_async.py (100%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_pause_engine_sync.py (100%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_resume_engine_async.py (100%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_resume_engine_sync.py (100%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_tune_engine_async.py (100%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_tune_engine_sync.py (100%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_update_engine_async.py (100%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_update_engine_sync.py (100%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/tests/unit/gapic/discoveryengine_v1alpha/test_data_store_service.py (71%) rename {owl-bot-staging/google-cloud-discoveryengine/v1alpha => packages/google-cloud-discoveryengine}/tests/unit/gapic/discoveryengine_v1alpha/test_engine_service.py (69%) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/.coveragerc b/owl-bot-staging/google-cloud-discoveryengine/v1/.coveragerc deleted file mode 100644 index f2c9bc595be9..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/discoveryengine/__init__.py - google/cloud/discoveryengine/gapic_version.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/.flake8 b/owl-bot-staging/google-cloud-discoveryengine/v1/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/MANIFEST.in b/owl-bot-staging/google-cloud-discoveryengine/v1/MANIFEST.in deleted file mode 100644 index 9d84ac93f6c8..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/discoveryengine *.py -recursive-include google/cloud/discoveryengine_v1 *.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/README.rst b/owl-bot-staging/google-cloud-discoveryengine/v1/README.rst deleted file mode 100644 index 25f579284266..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Discoveryengine API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Discoveryengine API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/docs/_static/custom.css b/owl-bot-staging/google-cloud-discoveryengine/v1/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/docs/conf.py b/owl-bot-staging/google-cloud-discoveryengine/v1/docs/conf.py deleted file mode 100644 index 9852ef988546..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-cloud-discoveryengine documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-cloud-discoveryengine" -copyright = u"2023, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = 'en' - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-discoveryengine-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-cloud-discoveryengine.tex", - u"google-cloud-discoveryengine Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - root_doc, - "google-cloud-discoveryengine", - u"Google Cloud Discoveryengine Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-cloud-discoveryengine", - u"google-cloud-discoveryengine Documentation", - author, - "google-cloud-discoveryengine", - "GAPIC library for Google Cloud Discoveryengine API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/completion_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/completion_service.rst deleted file mode 100644 index f18a0cfa68f6..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/completion_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -CompletionService ------------------------------------ - -.. automodule:: google.cloud.discoveryengine_v1.services.completion_service - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/conversational_search_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/conversational_search_service.rst deleted file mode 100644 index 1b538eb65974..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/conversational_search_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -ConversationalSearchService ---------------------------------------------- - -.. automodule:: google.cloud.discoveryengine_v1.services.conversational_search_service - :members: - :inherited-members: - -.. automodule:: google.cloud.discoveryengine_v1.services.conversational_search_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/document_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/document_service.rst deleted file mode 100644 index a0513d278416..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/document_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -DocumentService ---------------------------------- - -.. automodule:: google.cloud.discoveryengine_v1.services.document_service - :members: - :inherited-members: - -.. automodule:: google.cloud.discoveryengine_v1.services.document_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/schema_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/schema_service.rst deleted file mode 100644 index 725b280ca3bf..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/schema_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -SchemaService -------------------------------- - -.. automodule:: google.cloud.discoveryengine_v1.services.schema_service - :members: - :inherited-members: - -.. automodule:: google.cloud.discoveryengine_v1.services.schema_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/search_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/search_service.rst deleted file mode 100644 index 54969826c038..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/search_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -SearchService -------------------------------- - -.. automodule:: google.cloud.discoveryengine_v1.services.search_service - :members: - :inherited-members: - -.. automodule:: google.cloud.discoveryengine_v1.services.search_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/services_.rst b/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/services_.rst deleted file mode 100644 index f93a1c0cd465..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/services_.rst +++ /dev/null @@ -1,11 +0,0 @@ -Services for Google Cloud Discoveryengine v1 API -================================================ -.. toctree:: - :maxdepth: 2 - - completion_service - conversational_search_service - document_service - schema_service - search_service - user_event_service diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/types_.rst b/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/types_.rst deleted file mode 100644 index 07127eae56ef..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Discoveryengine v1 API -============================================= - -.. automodule:: google.cloud.discoveryengine_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/user_event_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/user_event_service.rst deleted file mode 100644 index 74a5dca6bc44..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/docs/discoveryengine_v1/user_event_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -UserEventService ----------------------------------- - -.. automodule:: google.cloud.discoveryengine_v1.services.user_event_service - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/docs/index.rst b/owl-bot-staging/google-cloud-discoveryengine/v1/docs/index.rst deleted file mode 100644 index b3ce373dfe99..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - discoveryengine_v1/services - discoveryengine_v1/types diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine/__init__.py deleted file mode 100644 index 1910fb7ef9bb..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine/__init__.py +++ /dev/null @@ -1,165 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.cloud.discoveryengine import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.discoveryengine_v1.services.completion_service.client import CompletionServiceClient -from google.cloud.discoveryengine_v1.services.completion_service.async_client import CompletionServiceAsyncClient -from google.cloud.discoveryengine_v1.services.conversational_search_service.client import ConversationalSearchServiceClient -from google.cloud.discoveryengine_v1.services.conversational_search_service.async_client import ConversationalSearchServiceAsyncClient -from google.cloud.discoveryengine_v1.services.document_service.client import DocumentServiceClient -from google.cloud.discoveryengine_v1.services.document_service.async_client import DocumentServiceAsyncClient -from google.cloud.discoveryengine_v1.services.schema_service.client import SchemaServiceClient -from google.cloud.discoveryengine_v1.services.schema_service.async_client import SchemaServiceAsyncClient -from google.cloud.discoveryengine_v1.services.search_service.client import SearchServiceClient -from google.cloud.discoveryengine_v1.services.search_service.async_client import SearchServiceAsyncClient -from google.cloud.discoveryengine_v1.services.user_event_service.client import UserEventServiceClient -from google.cloud.discoveryengine_v1.services.user_event_service.async_client import UserEventServiceAsyncClient - -from google.cloud.discoveryengine_v1.types.common import CustomAttribute -from google.cloud.discoveryengine_v1.types.common import Interval -from google.cloud.discoveryengine_v1.types.common import UserInfo -from google.cloud.discoveryengine_v1.types.completion_service import CompleteQueryRequest -from google.cloud.discoveryengine_v1.types.completion_service import CompleteQueryResponse -from google.cloud.discoveryengine_v1.types.conversation import Conversation -from google.cloud.discoveryengine_v1.types.conversation import ConversationContext -from google.cloud.discoveryengine_v1.types.conversation import ConversationMessage -from google.cloud.discoveryengine_v1.types.conversation import Reply -from google.cloud.discoveryengine_v1.types.conversation import TextInput -from google.cloud.discoveryengine_v1.types.conversational_search_service import ConverseConversationRequest -from google.cloud.discoveryengine_v1.types.conversational_search_service import ConverseConversationResponse -from google.cloud.discoveryengine_v1.types.conversational_search_service import CreateConversationRequest -from google.cloud.discoveryengine_v1.types.conversational_search_service import DeleteConversationRequest -from google.cloud.discoveryengine_v1.types.conversational_search_service import GetConversationRequest -from google.cloud.discoveryengine_v1.types.conversational_search_service import ListConversationsRequest -from google.cloud.discoveryengine_v1.types.conversational_search_service import ListConversationsResponse -from google.cloud.discoveryengine_v1.types.conversational_search_service import UpdateConversationRequest -from google.cloud.discoveryengine_v1.types.document import Document -from google.cloud.discoveryengine_v1.types.document_service import CreateDocumentRequest -from google.cloud.discoveryengine_v1.types.document_service import DeleteDocumentRequest -from google.cloud.discoveryengine_v1.types.document_service import GetDocumentRequest -from google.cloud.discoveryengine_v1.types.document_service import ListDocumentsRequest -from google.cloud.discoveryengine_v1.types.document_service import ListDocumentsResponse -from google.cloud.discoveryengine_v1.types.document_service import UpdateDocumentRequest -from google.cloud.discoveryengine_v1.types.import_config import BigQuerySource -from google.cloud.discoveryengine_v1.types.import_config import GcsSource -from google.cloud.discoveryengine_v1.types.import_config import ImportDocumentsMetadata -from google.cloud.discoveryengine_v1.types.import_config import ImportDocumentsRequest -from google.cloud.discoveryengine_v1.types.import_config import ImportDocumentsResponse -from google.cloud.discoveryengine_v1.types.import_config import ImportErrorConfig -from google.cloud.discoveryengine_v1.types.import_config import ImportUserEventsMetadata -from google.cloud.discoveryengine_v1.types.import_config import ImportUserEventsRequest -from google.cloud.discoveryengine_v1.types.import_config import ImportUserEventsResponse -from google.cloud.discoveryengine_v1.types.purge_config import PurgeDocumentsMetadata -from google.cloud.discoveryengine_v1.types.purge_config import PurgeDocumentsRequest -from google.cloud.discoveryengine_v1.types.purge_config import PurgeDocumentsResponse -from google.cloud.discoveryengine_v1.types.schema import Schema -from google.cloud.discoveryengine_v1.types.schema_service import CreateSchemaMetadata -from google.cloud.discoveryengine_v1.types.schema_service import CreateSchemaRequest -from google.cloud.discoveryengine_v1.types.schema_service import DeleteSchemaMetadata -from google.cloud.discoveryengine_v1.types.schema_service import DeleteSchemaRequest -from google.cloud.discoveryengine_v1.types.schema_service import GetSchemaRequest -from google.cloud.discoveryengine_v1.types.schema_service import ListSchemasRequest -from google.cloud.discoveryengine_v1.types.schema_service import ListSchemasResponse -from google.cloud.discoveryengine_v1.types.schema_service import UpdateSchemaMetadata -from google.cloud.discoveryengine_v1.types.schema_service import UpdateSchemaRequest -from google.cloud.discoveryengine_v1.types.search_service import SearchRequest -from google.cloud.discoveryengine_v1.types.search_service import SearchResponse -from google.cloud.discoveryengine_v1.types.user_event import CompletionInfo -from google.cloud.discoveryengine_v1.types.user_event import DocumentInfo -from google.cloud.discoveryengine_v1.types.user_event import MediaInfo -from google.cloud.discoveryengine_v1.types.user_event import PageInfo -from google.cloud.discoveryengine_v1.types.user_event import PanelInfo -from google.cloud.discoveryengine_v1.types.user_event import SearchInfo -from google.cloud.discoveryengine_v1.types.user_event import TransactionInfo -from google.cloud.discoveryengine_v1.types.user_event import UserEvent -from google.cloud.discoveryengine_v1.types.user_event_service import CollectUserEventRequest -from google.cloud.discoveryengine_v1.types.user_event_service import WriteUserEventRequest - -__all__ = ('CompletionServiceClient', - 'CompletionServiceAsyncClient', - 'ConversationalSearchServiceClient', - 'ConversationalSearchServiceAsyncClient', - 'DocumentServiceClient', - 'DocumentServiceAsyncClient', - 'SchemaServiceClient', - 'SchemaServiceAsyncClient', - 'SearchServiceClient', - 'SearchServiceAsyncClient', - 'UserEventServiceClient', - 'UserEventServiceAsyncClient', - 'CustomAttribute', - 'Interval', - 'UserInfo', - 'CompleteQueryRequest', - 'CompleteQueryResponse', - 'Conversation', - 'ConversationContext', - 'ConversationMessage', - 'Reply', - 'TextInput', - 'ConverseConversationRequest', - 'ConverseConversationResponse', - 'CreateConversationRequest', - 'DeleteConversationRequest', - 'GetConversationRequest', - 'ListConversationsRequest', - 'ListConversationsResponse', - 'UpdateConversationRequest', - 'Document', - 'CreateDocumentRequest', - 'DeleteDocumentRequest', - 'GetDocumentRequest', - 'ListDocumentsRequest', - 'ListDocumentsResponse', - 'UpdateDocumentRequest', - 'BigQuerySource', - 'GcsSource', - 'ImportDocumentsMetadata', - 'ImportDocumentsRequest', - 'ImportDocumentsResponse', - 'ImportErrorConfig', - 'ImportUserEventsMetadata', - 'ImportUserEventsRequest', - 'ImportUserEventsResponse', - 'PurgeDocumentsMetadata', - 'PurgeDocumentsRequest', - 'PurgeDocumentsResponse', - 'Schema', - 'CreateSchemaMetadata', - 'CreateSchemaRequest', - 'DeleteSchemaMetadata', - 'DeleteSchemaRequest', - 'GetSchemaRequest', - 'ListSchemasRequest', - 'ListSchemasResponse', - 'UpdateSchemaMetadata', - 'UpdateSchemaRequest', - 'SearchRequest', - 'SearchResponse', - 'CompletionInfo', - 'DocumentInfo', - 'MediaInfo', - 'PageInfo', - 'PanelInfo', - 'SearchInfo', - 'TransactionInfo', - 'UserEvent', - 'CollectUserEventRequest', - 'WriteUserEventRequest', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine/gapic_version.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine/gapic_version.py deleted file mode 100644 index 360a0d13ebdd..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine/py.typed b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine/py.typed deleted file mode 100644 index 2ff6437cf473..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-discoveryengine package uses inline types. diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/__init__.py deleted file mode 100644 index c55b70e7ad19..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/__init__.py +++ /dev/null @@ -1,166 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.cloud.discoveryengine_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.completion_service import CompletionServiceClient -from .services.completion_service import CompletionServiceAsyncClient -from .services.conversational_search_service import ConversationalSearchServiceClient -from .services.conversational_search_service import ConversationalSearchServiceAsyncClient -from .services.document_service import DocumentServiceClient -from .services.document_service import DocumentServiceAsyncClient -from .services.schema_service import SchemaServiceClient -from .services.schema_service import SchemaServiceAsyncClient -from .services.search_service import SearchServiceClient -from .services.search_service import SearchServiceAsyncClient -from .services.user_event_service import UserEventServiceClient -from .services.user_event_service import UserEventServiceAsyncClient - -from .types.common import CustomAttribute -from .types.common import Interval -from .types.common import UserInfo -from .types.completion_service import CompleteQueryRequest -from .types.completion_service import CompleteQueryResponse -from .types.conversation import Conversation -from .types.conversation import ConversationContext -from .types.conversation import ConversationMessage -from .types.conversation import Reply -from .types.conversation import TextInput -from .types.conversational_search_service import ConverseConversationRequest -from .types.conversational_search_service import ConverseConversationResponse -from .types.conversational_search_service import CreateConversationRequest -from .types.conversational_search_service import DeleteConversationRequest -from .types.conversational_search_service import GetConversationRequest -from .types.conversational_search_service import ListConversationsRequest -from .types.conversational_search_service import ListConversationsResponse -from .types.conversational_search_service import UpdateConversationRequest -from .types.document import Document -from .types.document_service import CreateDocumentRequest -from .types.document_service import DeleteDocumentRequest -from .types.document_service import GetDocumentRequest -from .types.document_service import ListDocumentsRequest -from .types.document_service import ListDocumentsResponse -from .types.document_service import UpdateDocumentRequest -from .types.import_config import BigQuerySource -from .types.import_config import GcsSource -from .types.import_config import ImportDocumentsMetadata -from .types.import_config import ImportDocumentsRequest -from .types.import_config import ImportDocumentsResponse -from .types.import_config import ImportErrorConfig -from .types.import_config import ImportUserEventsMetadata -from .types.import_config import ImportUserEventsRequest -from .types.import_config import ImportUserEventsResponse -from .types.purge_config import PurgeDocumentsMetadata -from .types.purge_config import PurgeDocumentsRequest -from .types.purge_config import PurgeDocumentsResponse -from .types.schema import Schema -from .types.schema_service import CreateSchemaMetadata -from .types.schema_service import CreateSchemaRequest -from .types.schema_service import DeleteSchemaMetadata -from .types.schema_service import DeleteSchemaRequest -from .types.schema_service import GetSchemaRequest -from .types.schema_service import ListSchemasRequest -from .types.schema_service import ListSchemasResponse -from .types.schema_service import UpdateSchemaMetadata -from .types.schema_service import UpdateSchemaRequest -from .types.search_service import SearchRequest -from .types.search_service import SearchResponse -from .types.user_event import CompletionInfo -from .types.user_event import DocumentInfo -from .types.user_event import MediaInfo -from .types.user_event import PageInfo -from .types.user_event import PanelInfo -from .types.user_event import SearchInfo -from .types.user_event import TransactionInfo -from .types.user_event import UserEvent -from .types.user_event_service import CollectUserEventRequest -from .types.user_event_service import WriteUserEventRequest - -__all__ = ( - 'CompletionServiceAsyncClient', - 'ConversationalSearchServiceAsyncClient', - 'DocumentServiceAsyncClient', - 'SchemaServiceAsyncClient', - 'SearchServiceAsyncClient', - 'UserEventServiceAsyncClient', -'BigQuerySource', -'CollectUserEventRequest', -'CompleteQueryRequest', -'CompleteQueryResponse', -'CompletionInfo', -'CompletionServiceClient', -'Conversation', -'ConversationContext', -'ConversationMessage', -'ConversationalSearchServiceClient', -'ConverseConversationRequest', -'ConverseConversationResponse', -'CreateConversationRequest', -'CreateDocumentRequest', -'CreateSchemaMetadata', -'CreateSchemaRequest', -'CustomAttribute', -'DeleteConversationRequest', -'DeleteDocumentRequest', -'DeleteSchemaMetadata', -'DeleteSchemaRequest', -'Document', -'DocumentInfo', -'DocumentServiceClient', -'GcsSource', -'GetConversationRequest', -'GetDocumentRequest', -'GetSchemaRequest', -'ImportDocumentsMetadata', -'ImportDocumentsRequest', -'ImportDocumentsResponse', -'ImportErrorConfig', -'ImportUserEventsMetadata', -'ImportUserEventsRequest', -'ImportUserEventsResponse', -'Interval', -'ListConversationsRequest', -'ListConversationsResponse', -'ListDocumentsRequest', -'ListDocumentsResponse', -'ListSchemasRequest', -'ListSchemasResponse', -'MediaInfo', -'PageInfo', -'PanelInfo', -'PurgeDocumentsMetadata', -'PurgeDocumentsRequest', -'PurgeDocumentsResponse', -'Reply', -'Schema', -'SchemaServiceClient', -'SearchInfo', -'SearchRequest', -'SearchResponse', -'SearchServiceClient', -'TextInput', -'TransactionInfo', -'UpdateConversationRequest', -'UpdateDocumentRequest', -'UpdateSchemaMetadata', -'UpdateSchemaRequest', -'UserEvent', -'UserEventServiceClient', -'UserInfo', -'WriteUserEventRequest', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/gapic_metadata.json deleted file mode 100644 index 40ef7a0de6c2..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/gapic_metadata.json +++ /dev/null @@ -1,468 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.discoveryengine_v1", - "protoPackage": "google.cloud.discoveryengine.v1", - "schema": "1.0", - "services": { - "CompletionService": { - "clients": { - "grpc": { - "libraryClient": "CompletionServiceClient", - "rpcs": { - "CompleteQuery": { - "methods": [ - "complete_query" - ] - } - } - }, - "grpc-async": { - "libraryClient": "CompletionServiceAsyncClient", - "rpcs": { - "CompleteQuery": { - "methods": [ - "complete_query" - ] - } - } - }, - "rest": { - "libraryClient": "CompletionServiceClient", - "rpcs": { - "CompleteQuery": { - "methods": [ - "complete_query" - ] - } - } - } - } - }, - "ConversationalSearchService": { - "clients": { - "grpc": { - "libraryClient": "ConversationalSearchServiceClient", - "rpcs": { - "ConverseConversation": { - "methods": [ - "converse_conversation" - ] - }, - "CreateConversation": { - "methods": [ - "create_conversation" - ] - }, - "DeleteConversation": { - "methods": [ - "delete_conversation" - ] - }, - "GetConversation": { - "methods": [ - "get_conversation" - ] - }, - "ListConversations": { - "methods": [ - "list_conversations" - ] - }, - "UpdateConversation": { - "methods": [ - "update_conversation" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ConversationalSearchServiceAsyncClient", - "rpcs": { - "ConverseConversation": { - "methods": [ - "converse_conversation" - ] - }, - "CreateConversation": { - "methods": [ - "create_conversation" - ] - }, - "DeleteConversation": { - "methods": [ - "delete_conversation" - ] - }, - "GetConversation": { - "methods": [ - "get_conversation" - ] - }, - "ListConversations": { - "methods": [ - "list_conversations" - ] - }, - "UpdateConversation": { - "methods": [ - "update_conversation" - ] - } - } - }, - "rest": { - "libraryClient": "ConversationalSearchServiceClient", - "rpcs": { - "ConverseConversation": { - "methods": [ - "converse_conversation" - ] - }, - "CreateConversation": { - "methods": [ - "create_conversation" - ] - }, - "DeleteConversation": { - "methods": [ - "delete_conversation" - ] - }, - "GetConversation": { - "methods": [ - "get_conversation" - ] - }, - "ListConversations": { - "methods": [ - "list_conversations" - ] - }, - "UpdateConversation": { - "methods": [ - "update_conversation" - ] - } - } - } - } - }, - "DocumentService": { - "clients": { - "grpc": { - "libraryClient": "DocumentServiceClient", - "rpcs": { - "CreateDocument": { - "methods": [ - "create_document" - ] - }, - "DeleteDocument": { - "methods": [ - "delete_document" - ] - }, - "GetDocument": { - "methods": [ - "get_document" - ] - }, - "ImportDocuments": { - "methods": [ - "import_documents" - ] - }, - "ListDocuments": { - "methods": [ - "list_documents" - ] - }, - "PurgeDocuments": { - "methods": [ - "purge_documents" - ] - }, - "UpdateDocument": { - "methods": [ - "update_document" - ] - } - } - }, - "grpc-async": { - "libraryClient": "DocumentServiceAsyncClient", - "rpcs": { - "CreateDocument": { - "methods": [ - "create_document" - ] - }, - "DeleteDocument": { - "methods": [ - "delete_document" - ] - }, - "GetDocument": { - "methods": [ - "get_document" - ] - }, - "ImportDocuments": { - "methods": [ - "import_documents" - ] - }, - "ListDocuments": { - "methods": [ - "list_documents" - ] - }, - "PurgeDocuments": { - "methods": [ - "purge_documents" - ] - }, - "UpdateDocument": { - "methods": [ - "update_document" - ] - } - } - }, - "rest": { - "libraryClient": "DocumentServiceClient", - "rpcs": { - "CreateDocument": { - "methods": [ - "create_document" - ] - }, - "DeleteDocument": { - "methods": [ - "delete_document" - ] - }, - "GetDocument": { - "methods": [ - "get_document" - ] - }, - "ImportDocuments": { - "methods": [ - "import_documents" - ] - }, - "ListDocuments": { - "methods": [ - "list_documents" - ] - }, - "PurgeDocuments": { - "methods": [ - "purge_documents" - ] - }, - "UpdateDocument": { - "methods": [ - "update_document" - ] - } - } - } - } - }, - "SchemaService": { - "clients": { - "grpc": { - "libraryClient": "SchemaServiceClient", - "rpcs": { - "CreateSchema": { - "methods": [ - "create_schema" - ] - }, - "DeleteSchema": { - "methods": [ - "delete_schema" - ] - }, - "GetSchema": { - "methods": [ - "get_schema" - ] - }, - "ListSchemas": { - "methods": [ - "list_schemas" - ] - }, - "UpdateSchema": { - "methods": [ - "update_schema" - ] - } - } - }, - "grpc-async": { - "libraryClient": "SchemaServiceAsyncClient", - "rpcs": { - "CreateSchema": { - "methods": [ - "create_schema" - ] - }, - "DeleteSchema": { - "methods": [ - "delete_schema" - ] - }, - "GetSchema": { - "methods": [ - "get_schema" - ] - }, - "ListSchemas": { - "methods": [ - "list_schemas" - ] - }, - "UpdateSchema": { - "methods": [ - "update_schema" - ] - } - } - }, - "rest": { - "libraryClient": "SchemaServiceClient", - "rpcs": { - "CreateSchema": { - "methods": [ - "create_schema" - ] - }, - "DeleteSchema": { - "methods": [ - "delete_schema" - ] - }, - "GetSchema": { - "methods": [ - "get_schema" - ] - }, - "ListSchemas": { - "methods": [ - "list_schemas" - ] - }, - "UpdateSchema": { - "methods": [ - "update_schema" - ] - } - } - } - } - }, - "SearchService": { - "clients": { - "grpc": { - "libraryClient": "SearchServiceClient", - "rpcs": { - "Search": { - "methods": [ - "search" - ] - } - } - }, - "grpc-async": { - "libraryClient": "SearchServiceAsyncClient", - "rpcs": { - "Search": { - "methods": [ - "search" - ] - } - } - }, - "rest": { - "libraryClient": "SearchServiceClient", - "rpcs": { - "Search": { - "methods": [ - "search" - ] - } - } - } - } - }, - "UserEventService": { - "clients": { - "grpc": { - "libraryClient": "UserEventServiceClient", - "rpcs": { - "CollectUserEvent": { - "methods": [ - "collect_user_event" - ] - }, - "ImportUserEvents": { - "methods": [ - "import_user_events" - ] - }, - "WriteUserEvent": { - "methods": [ - "write_user_event" - ] - } - } - }, - "grpc-async": { - "libraryClient": "UserEventServiceAsyncClient", - "rpcs": { - "CollectUserEvent": { - "methods": [ - "collect_user_event" - ] - }, - "ImportUserEvents": { - "methods": [ - "import_user_events" - ] - }, - "WriteUserEvent": { - "methods": [ - "write_user_event" - ] - } - } - }, - "rest": { - "libraryClient": "UserEventServiceClient", - "rpcs": { - "CollectUserEvent": { - "methods": [ - "collect_user_event" - ] - }, - "ImportUserEvents": { - "methods": [ - "import_user_events" - ] - }, - "WriteUserEvent": { - "methods": [ - "write_user_event" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/gapic_version.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/gapic_version.py deleted file mode 100644 index 360a0d13ebdd..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/py.typed b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/py.typed deleted file mode 100644 index 2ff6437cf473..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-discoveryengine package uses inline types. diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/__init__.py deleted file mode 100644 index 89a37dc92c5a..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/__init__.py deleted file mode 100644 index 440cbfb40963..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import CompletionServiceClient -from .async_client import CompletionServiceAsyncClient - -__all__ = ( - 'CompletionServiceClient', - 'CompletionServiceAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/async_client.py deleted file mode 100644 index 5ddbf499bf7b..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/async_client.py +++ /dev/null @@ -1,386 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.discoveryengine_v1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.discoveryengine_v1.types import completion_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport -from .client import CompletionServiceClient - - -class CompletionServiceAsyncClient: - """Service for Auto-Completion.""" - - _client: CompletionServiceClient - - DEFAULT_ENDPOINT = CompletionServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = CompletionServiceClient.DEFAULT_MTLS_ENDPOINT - - data_store_path = staticmethod(CompletionServiceClient.data_store_path) - parse_data_store_path = staticmethod(CompletionServiceClient.parse_data_store_path) - common_billing_account_path = staticmethod(CompletionServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(CompletionServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(CompletionServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(CompletionServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(CompletionServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(CompletionServiceClient.parse_common_organization_path) - common_project_path = staticmethod(CompletionServiceClient.common_project_path) - parse_common_project_path = staticmethod(CompletionServiceClient.parse_common_project_path) - common_location_path = staticmethod(CompletionServiceClient.common_location_path) - parse_common_location_path = staticmethod(CompletionServiceClient.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: - CompletionServiceAsyncClient: The constructed client. - """ - return CompletionServiceClient.from_service_account_info.__func__(CompletionServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceAsyncClient: The constructed client. - """ - return CompletionServiceClient.from_service_account_file.__func__(CompletionServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return CompletionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> CompletionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CompletionServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(CompletionServiceClient).get_transport_class, type(CompletionServiceClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, CompletionServiceTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the completion 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 (Union[str, ~.CompletionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = CompletionServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def complete_query(self, - request: Optional[Union[completion_service.CompleteQueryRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> completion_service.CompleteQueryResponse: - r"""Completes the specified user input with keyword - suggestions. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - async def sample_complete_query(): - # Create a client - client = discoveryengine_v1.CompletionServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.CompleteQueryRequest( - data_store="data_store_value", - query="query_value", - ) - - # Make the request - response = await client.complete_query(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1.types.CompleteQueryRequest, dict]]): - The request object. Request message for - [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1.CompletionService.CompleteQuery] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1.types.CompleteQueryResponse: - Response message for - [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1.CompletionService.CompleteQuery] - method. - - """ - # Create or coerce a protobuf request object. - request = completion_service.CompleteQueryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.complete_query, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("data_store", request.data_store), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "CompletionServiceAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "CompletionServiceAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/client.py deleted file mode 100644 index 2d3a30a2c1f7..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/client.py +++ /dev/null @@ -1,594 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.discoveryengine_v1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.discoveryengine_v1.types import completion_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import CompletionServiceGrpcTransport -from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport -from .transports.rest import CompletionServiceRestTransport - - -class CompletionServiceClientMeta(type): - """Metaclass for the CompletionService 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[CompletionServiceTransport]] - _transport_registry["grpc"] = CompletionServiceGrpcTransport - _transport_registry["grpc_asyncio"] = CompletionServiceGrpcAsyncIOTransport - _transport_registry["rest"] = CompletionServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[CompletionServiceTransport]: - """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 CompletionServiceClient(metaclass=CompletionServiceClientMeta): - """Service for Auto-Completion.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceClient: 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: - CompletionServiceClient: 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) -> CompletionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CompletionServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def data_store_path(project: str,location: str,data_store: str,) -> str: - """Returns a fully-qualified data_store string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) - - @staticmethod - def parse_data_store_path(path: str) -> Dict[str,str]: - """Parses a data_store path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, CompletionServiceTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the completion 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 (Union[str, CompletionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, CompletionServiceTransport): - # transport is a CompletionServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def complete_query(self, - request: Optional[Union[completion_service.CompleteQueryRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> completion_service.CompleteQueryResponse: - r"""Completes the specified user input with keyword - suggestions. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - def sample_complete_query(): - # Create a client - client = discoveryengine_v1.CompletionServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.CompleteQueryRequest( - data_store="data_store_value", - query="query_value", - ) - - # Make the request - response = client.complete_query(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1.types.CompleteQueryRequest, dict]): - The request object. Request message for - [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1.CompletionService.CompleteQuery] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1.types.CompleteQueryResponse: - Response message for - [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1.CompletionService.CompleteQuery] - method. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a completion_service.CompleteQueryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, completion_service.CompleteQueryRequest): - request = completion_service.CompleteQueryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.complete_query] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("data_store", request.data_store), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "CompletionServiceClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - - - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "CompletionServiceClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/__init__.py deleted file mode 100644 index f32ad4419b13..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import CompletionServiceTransport -from .grpc import CompletionServiceGrpcTransport -from .grpc_asyncio import CompletionServiceGrpcAsyncIOTransport -from .rest import CompletionServiceRestTransport -from .rest import CompletionServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] -_transport_registry['grpc'] = CompletionServiceGrpcTransport -_transport_registry['grpc_asyncio'] = CompletionServiceGrpcAsyncIOTransport -_transport_registry['rest'] = CompletionServiceRestTransport - -__all__ = ( - 'CompletionServiceTransport', - 'CompletionServiceGrpcTransport', - 'CompletionServiceGrpcAsyncIOTransport', - 'CompletionServiceRestTransport', - 'CompletionServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/base.py deleted file mode 100644 index ab8350b556c9..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/base.py +++ /dev/null @@ -1,168 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.discoveryengine_v1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.discoveryengine_v1.types import completion_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class CompletionServiceTransport(abc.ABC): - """Abstract transport class for CompletionService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'discoveryengine.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.complete_query: gapic_v1.method.wrap_method( - self.complete_query, - 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 complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - Union[ - completion_service.CompleteQueryResponse, - Awaitable[completion_service.CompleteQueryResponse] - ]]: - 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 kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'CompletionServiceTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/grpc.py deleted file mode 100644 index 5ce36ba7ca47..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/grpc.py +++ /dev/null @@ -1,303 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.discoveryengine_v1.types import completion_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO - - -class CompletionServiceGrpcTransport(CompletionServiceTransport): - """gRPC backend transport for CompletionService. - - Service for Auto-Completion. - - 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - completion_service.CompleteQueryResponse]: - r"""Return a callable for the complete query method over gRPC. - - Completes the specified user input with keyword - suggestions. - - Returns: - Callable[[~.CompleteQueryRequest], - ~.CompleteQueryResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'complete_query' not in self._stubs: - self._stubs['complete_query'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.CompletionService/CompleteQuery', - request_serializer=completion_service.CompleteQueryRequest.serialize, - response_deserializer=completion_service.CompleteQueryResponse.deserialize, - ) - return self._stubs['complete_query'] - - def close(self): - self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'CompletionServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/grpc_asyncio.py deleted file mode 100644 index 9578fc7444f4..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,302 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.discoveryengine_v1.types import completion_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import CompletionServiceGrpcTransport - - -class CompletionServiceGrpcAsyncIOTransport(CompletionServiceTransport): - """gRPC AsyncIO backend transport for CompletionService. - - Service for Auto-Completion. - - 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - Awaitable[completion_service.CompleteQueryResponse]]: - r"""Return a callable for the complete query method over gRPC. - - Completes the specified user input with keyword - suggestions. - - Returns: - Callable[[~.CompleteQueryRequest], - Awaitable[~.CompleteQueryResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'complete_query' not in self._stubs: - self._stubs['complete_query'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.CompletionService/CompleteQuery', - request_serializer=completion_service.CompleteQueryRequest.serialize, - response_deserializer=completion_service.CompleteQueryResponse.deserialize, - ) - return self._stubs['complete_query'] - - def close(self): - return self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - -__all__ = ( - 'CompletionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/rest.py deleted file mode 100644 index 11075f2905e8..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/completion_service/transports/rest.py +++ /dev/null @@ -1,574 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.cloud.location import locations_pb2 # type: ignore -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.discoveryengine_v1.types import completion_service -from google.longrunning import operations_pb2 # type: ignore - -from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class CompletionServiceRestInterceptor: - """Interceptor for CompletionService. - - 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 CompletionServiceRestTransport. - - .. code-block:: python - class MyCustomCompletionServiceInterceptor(CompletionServiceRestInterceptor): - def pre_complete_query(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_complete_query(self, response): - logging.log(f"Received response: {response}") - return response - - transport = CompletionServiceRestTransport(interceptor=MyCustomCompletionServiceInterceptor()) - client = CompletionServiceClient(transport=transport) - - - """ - def pre_complete_query(self, request: completion_service.CompleteQueryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[completion_service.CompleteQueryRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for complete_query - - Override in a subclass to manipulate the request or metadata - before they are sent to the CompletionService server. - """ - return request, metadata - - def post_complete_query(self, response: completion_service.CompleteQueryResponse) -> completion_service.CompleteQueryResponse: - """Post-rpc interceptor for complete_query - - Override in a subclass to manipulate the response - after it is returned by the CompletionService server but before - it is returned to user code. - """ - return response - - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the CompletionService 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 CompletionService server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the CompletionService 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 CompletionService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class CompletionServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: CompletionServiceRestInterceptor - - -class CompletionServiceRestTransport(CompletionServiceTransport): - """REST backend transport for CompletionService. - - Service for Auto-Completion. - - 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 = 'discoveryengine.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[CompletionServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or CompletionServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _CompleteQuery(CompletionServiceRestStub): - def __hash__(self): - return hash("CompleteQuery") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "query" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: completion_service.CompleteQueryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> completion_service.CompleteQueryResponse: - r"""Call the complete query method over HTTP. - - Args: - request (~.completion_service.CompleteQueryRequest): - The request object. Request message for - [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1.CompletionService.CompleteQuery] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.completion_service.CompleteQueryResponse: - Response message for - [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1.CompletionService.CompleteQuery] - method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{data_store=projects/*/locations/*/dataStores/*}:completeQuery', - }, -{ - 'method': 'get', - 'uri': '/v1/{data_store=projects/*/locations/*/collections/*/dataStores/*}:completeQuery', - }, - ] - request, metadata = self._interceptor.pre_complete_query(request, metadata) - pb_request = completion_service.CompleteQueryRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = completion_service.CompleteQueryResponse() - pb_resp = completion_service.CompleteQueryResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_complete_query(resp) - return resp - - @property - def complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - completion_service.CompleteQueryResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CompleteQuery(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(CompletionServiceRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(CompletionServiceRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/engines/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'CompletionServiceRestTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/__init__.py deleted file mode 100644 index 4bf42b241a8b..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import ConversationalSearchServiceClient -from .async_client import ConversationalSearchServiceAsyncClient - -__all__ = ( - 'ConversationalSearchServiceClient', - 'ConversationalSearchServiceAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/async_client.py deleted file mode 100644 index 82846c2f6824..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/async_client.py +++ /dev/null @@ -1,971 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.discoveryengine_v1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.discoveryengine_v1.services.conversational_search_service import pagers -from google.cloud.discoveryengine_v1.types import conversation -from google.cloud.discoveryengine_v1.types import conversation as gcd_conversation -from google.cloud.discoveryengine_v1.types import conversational_search_service -from google.cloud.discoveryengine_v1.types import search_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import ConversationalSearchServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ConversationalSearchServiceGrpcAsyncIOTransport -from .client import ConversationalSearchServiceClient - - -class ConversationalSearchServiceAsyncClient: - """Service for conversational search.""" - - _client: ConversationalSearchServiceClient - - DEFAULT_ENDPOINT = ConversationalSearchServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ConversationalSearchServiceClient.DEFAULT_MTLS_ENDPOINT - - conversation_path = staticmethod(ConversationalSearchServiceClient.conversation_path) - parse_conversation_path = staticmethod(ConversationalSearchServiceClient.parse_conversation_path) - data_store_path = staticmethod(ConversationalSearchServiceClient.data_store_path) - parse_data_store_path = staticmethod(ConversationalSearchServiceClient.parse_data_store_path) - document_path = staticmethod(ConversationalSearchServiceClient.document_path) - parse_document_path = staticmethod(ConversationalSearchServiceClient.parse_document_path) - serving_config_path = staticmethod(ConversationalSearchServiceClient.serving_config_path) - parse_serving_config_path = staticmethod(ConversationalSearchServiceClient.parse_serving_config_path) - common_billing_account_path = staticmethod(ConversationalSearchServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ConversationalSearchServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ConversationalSearchServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(ConversationalSearchServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(ConversationalSearchServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(ConversationalSearchServiceClient.parse_common_organization_path) - common_project_path = staticmethod(ConversationalSearchServiceClient.common_project_path) - parse_common_project_path = staticmethod(ConversationalSearchServiceClient.parse_common_project_path) - common_location_path = staticmethod(ConversationalSearchServiceClient.common_location_path) - parse_common_location_path = staticmethod(ConversationalSearchServiceClient.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: - ConversationalSearchServiceAsyncClient: The constructed client. - """ - return ConversationalSearchServiceClient.from_service_account_info.__func__(ConversationalSearchServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ConversationalSearchServiceAsyncClient: The constructed client. - """ - return ConversationalSearchServiceClient.from_service_account_file.__func__(ConversationalSearchServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return ConversationalSearchServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ConversationalSearchServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ConversationalSearchServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ConversationalSearchServiceClient).get_transport_class, type(ConversationalSearchServiceClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ConversationalSearchServiceTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the conversational search 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 (Union[str, ~.ConversationalSearchServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = ConversationalSearchServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def converse_conversation(self, - request: Optional[Union[conversational_search_service.ConverseConversationRequest, dict]] = None, - *, - name: Optional[str] = None, - query: Optional[conversation.TextInput] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversational_search_service.ConverseConversationResponse: - r"""Converses 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 discoveryengine_v1 - - async def sample_converse_conversation(): - # Create a client - client = discoveryengine_v1.ConversationalSearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.ConverseConversationRequest( - name="name_value", - ) - - # Make the request - response = await client.converse_conversation(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1.types.ConverseConversationRequest, dict]]): - The request object. Request message for - [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1.ConversationalSearchService.ConverseConversation] - method. - name (:class:`str`): - Required. The resource name of the Conversation to get. - Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}``. - Use - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/-`` - to activate auto session mode, which automatically - creates a new conversation inside a ConverseConversation - session. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - query (:class:`google.cloud.discoveryengine_v1.types.TextInput`): - Required. Current user input. - This corresponds to the ``query`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1.types.ConverseConversationResponse: - Response message for - [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1.ConversationalSearchService.ConverseConversation] - method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, query]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = conversational_search_service.ConverseConversationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if query is not None: - request.query = query - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.converse_conversation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_conversation(self, - request: Optional[Union[conversational_search_service.CreateConversationRequest, dict]] = None, - *, - parent: Optional[str] = None, - conversation: Optional[gcd_conversation.Conversation] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_conversation.Conversation: - r"""Creates a Conversation. - - If the - [Conversation][google.cloud.discoveryengine.v1.Conversation] to - create already exists, an ALREADY_EXISTS error is returned. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - async def sample_create_conversation(): - # Create a client - client = discoveryengine_v1.ConversationalSearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.CreateConversationRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_conversation(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1.types.CreateConversationRequest, dict]]): - The request object. Request for CreateConversation - method. - parent (:class:`str`): - Required. Full resource name of parent data store. - Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - conversation (:class:`google.cloud.discoveryengine_v1.types.Conversation`): - Required. The conversation to create. - This corresponds to the ``conversation`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1.types.Conversation: - External conversation proto - definition. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, conversation]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = conversational_search_service.CreateConversationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if conversation is not None: - request.conversation = conversation - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_conversation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_conversation(self, - request: Optional[Union[conversational_search_service.DeleteConversationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a Conversation. - - If the - [Conversation][google.cloud.discoveryengine.v1.Conversation] to - delete does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - async def sample_delete_conversation(): - # Create a client - client = discoveryengine_v1.ConversationalSearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.DeleteConversationRequest( - name="name_value", - ) - - # Make the request - await client.delete_conversation(request=request) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1.types.DeleteConversationRequest, dict]]): - The request object. Request for DeleteConversation - method. - name (:class:`str`): - Required. The resource name of the Conversation to - delete. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = conversational_search_service.DeleteConversationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_conversation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def update_conversation(self, - request: Optional[Union[conversational_search_service.UpdateConversationRequest, dict]] = None, - *, - conversation: Optional[gcd_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, str]] = (), - ) -> gcd_conversation.Conversation: - r"""Updates a Conversation. - - [Conversation][google.cloud.discoveryengine.v1.Conversation] - action type cannot be changed. If the - [Conversation][google.cloud.discoveryengine.v1.Conversation] to - update does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - async def sample_update_conversation(): - # Create a client - client = discoveryengine_v1.ConversationalSearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.UpdateConversationRequest( - ) - - # Make the request - response = await client.update_conversation(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1.types.UpdateConversationRequest, dict]]): - The request object. Request for UpdateConversation - method. - conversation (:class:`google.cloud.discoveryengine_v1.types.Conversation`): - Required. The Conversation to update. - 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`): - Indicates which fields in the provided - [Conversation][google.cloud.discoveryengine.v1.Conversation] - to update. The following are NOT supported: - - - [conversation.name][] - - If not set or empty, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1.types.Conversation: - External conversation proto - definition. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([conversation, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = conversational_search_service.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 = gapic_v1.method_async.wrap_method( - self._client._transport.update_conversation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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), - )), - ) - - # 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[conversational_search_service.GetConversationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation.Conversation: - r"""Gets 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 discoveryengine_v1 - - async def sample_get_conversation(): - # Create a client - client = discoveryengine_v1.ConversationalSearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.GetConversationRequest( - name="name_value", - ) - - # Make the request - response = await client.get_conversation(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1.types.GetConversationRequest, dict]]): - The request object. Request for GetConversation method. - name (:class:`str`): - Required. The resource name of the Conversation to get. - Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1.types.Conversation: - External conversation proto - definition. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = conversational_search_service.GetConversationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_conversation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_conversations(self, - request: Optional[Union[conversational_search_service.ListConversationsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListConversationsAsyncPager: - r"""Lists all Conversations by their parent - [DataStore][google.cloud.discoveryengine.v1.DataStore]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - async def sample_list_conversations(): - # Create a client - client = discoveryengine_v1.ConversationalSearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.ListConversationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversations(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1.types.ListConversationsRequest, dict]]): - The request object. Request for ListConversations method. - parent (:class:`str`): - Required. The data store resource name. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1.services.conversational_search_service.pagers.ListConversationsAsyncPager: - Response for ListConversations - method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = conversational_search_service.ListConversationsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_conversations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListConversationsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "ConversationalSearchServiceAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "ConversationalSearchServiceAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/client.py deleted file mode 100644 index 4f48e82d6e56..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/client.py +++ /dev/null @@ -1,1205 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.discoveryengine_v1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.discoveryengine_v1.services.conversational_search_service import pagers -from google.cloud.discoveryengine_v1.types import conversation -from google.cloud.discoveryengine_v1.types import conversation as gcd_conversation -from google.cloud.discoveryengine_v1.types import conversational_search_service -from google.cloud.discoveryengine_v1.types import search_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import ConversationalSearchServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ConversationalSearchServiceGrpcTransport -from .transports.grpc_asyncio import ConversationalSearchServiceGrpcAsyncIOTransport -from .transports.rest import ConversationalSearchServiceRestTransport - - -class ConversationalSearchServiceClientMeta(type): - """Metaclass for the ConversationalSearchService 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[ConversationalSearchServiceTransport]] - _transport_registry["grpc"] = ConversationalSearchServiceGrpcTransport - _transport_registry["grpc_asyncio"] = ConversationalSearchServiceGrpcAsyncIOTransport - _transport_registry["rest"] = ConversationalSearchServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[ConversationalSearchServiceTransport]: - """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 ConversationalSearchServiceClient(metaclass=ConversationalSearchServiceClientMeta): - """Service for conversational search.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ConversationalSearchServiceClient: 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: - ConversationalSearchServiceClient: 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) -> ConversationalSearchServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ConversationalSearchServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def conversation_path(project: str,location: str,data_store: str,conversation: str,) -> str: - """Returns a fully-qualified conversation string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}/conversations/{conversation}".format(project=project, location=location, data_store=data_store, conversation=conversation, ) - - @staticmethod - def parse_conversation_path(path: str) -> Dict[str,str]: - """Parses a conversation path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/conversations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def data_store_path(project: str,location: str,data_store: str,) -> str: - """Returns a fully-qualified data_store string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) - - @staticmethod - def parse_data_store_path(path: str) -> Dict[str,str]: - """Parses a data_store path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def document_path(project: str,location: str,data_store: str,branch: str,document: str,) -> str: - """Returns a fully-qualified document string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) - - @staticmethod - def parse_document_path(path: str) -> Dict[str,str]: - """Parses a document path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)/documents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def serving_config_path(project: str,location: str,data_store: str,serving_config: str,) -> str: - """Returns a fully-qualified serving_config string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}/servingConfigs/{serving_config}".format(project=project, location=location, data_store=data_store, serving_config=serving_config, ) - - @staticmethod - def parse_serving_config_path(path: str) -> Dict[str,str]: - """Parses a serving_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/servingConfigs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ConversationalSearchServiceTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the conversational search 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 (Union[str, ConversationalSearchServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ConversationalSearchServiceTransport): - # transport is a ConversationalSearchServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def converse_conversation(self, - request: Optional[Union[conversational_search_service.ConverseConversationRequest, dict]] = None, - *, - name: Optional[str] = None, - query: Optional[conversation.TextInput] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversational_search_service.ConverseConversationResponse: - r"""Converses 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 discoveryengine_v1 - - def sample_converse_conversation(): - # Create a client - client = discoveryengine_v1.ConversationalSearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.ConverseConversationRequest( - name="name_value", - ) - - # Make the request - response = client.converse_conversation(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1.types.ConverseConversationRequest, dict]): - The request object. Request message for - [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1.ConversationalSearchService.ConverseConversation] - method. - name (str): - Required. The resource name of the Conversation to get. - Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}``. - Use - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/-`` - to activate auto session mode, which automatically - creates a new conversation inside a ConverseConversation - session. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - query (google.cloud.discoveryengine_v1.types.TextInput): - Required. Current user input. - This corresponds to the ``query`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1.types.ConverseConversationResponse: - Response message for - [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1.ConversationalSearchService.ConverseConversation] - method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, query]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a conversational_search_service.ConverseConversationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, conversational_search_service.ConverseConversationRequest): - request = conversational_search_service.ConverseConversationRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if query is not None: - request.query = query - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.converse_conversation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_conversation(self, - request: Optional[Union[conversational_search_service.CreateConversationRequest, dict]] = None, - *, - parent: Optional[str] = None, - conversation: Optional[gcd_conversation.Conversation] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_conversation.Conversation: - r"""Creates a Conversation. - - If the - [Conversation][google.cloud.discoveryengine.v1.Conversation] to - create already exists, an ALREADY_EXISTS error is returned. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - def sample_create_conversation(): - # Create a client - client = discoveryengine_v1.ConversationalSearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.CreateConversationRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_conversation(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1.types.CreateConversationRequest, dict]): - The request object. Request for CreateConversation - method. - parent (str): - Required. Full resource name of parent data store. - Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - conversation (google.cloud.discoveryengine_v1.types.Conversation): - Required. The conversation to create. - This corresponds to the ``conversation`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1.types.Conversation: - External conversation proto - definition. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, conversation]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a conversational_search_service.CreateConversationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, conversational_search_service.CreateConversationRequest): - request = conversational_search_service.CreateConversationRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if conversation is not None: - request.conversation = conversation - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_conversation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_conversation(self, - request: Optional[Union[conversational_search_service.DeleteConversationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a Conversation. - - If the - [Conversation][google.cloud.discoveryengine.v1.Conversation] to - delete does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - def sample_delete_conversation(): - # Create a client - client = discoveryengine_v1.ConversationalSearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.DeleteConversationRequest( - name="name_value", - ) - - # Make the request - client.delete_conversation(request=request) - - Args: - request (Union[google.cloud.discoveryengine_v1.types.DeleteConversationRequest, dict]): - The request object. Request for DeleteConversation - method. - name (str): - Required. The resource name of the Conversation to - delete. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a conversational_search_service.DeleteConversationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, conversational_search_service.DeleteConversationRequest): - request = conversational_search_service.DeleteConversationRequest(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_conversation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def update_conversation(self, - request: Optional[Union[conversational_search_service.UpdateConversationRequest, dict]] = None, - *, - conversation: Optional[gcd_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, str]] = (), - ) -> gcd_conversation.Conversation: - r"""Updates a Conversation. - - [Conversation][google.cloud.discoveryengine.v1.Conversation] - action type cannot be changed. If the - [Conversation][google.cloud.discoveryengine.v1.Conversation] to - update does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - def sample_update_conversation(): - # Create a client - client = discoveryengine_v1.ConversationalSearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.UpdateConversationRequest( - ) - - # Make the request - response = client.update_conversation(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1.types.UpdateConversationRequest, dict]): - The request object. Request for UpdateConversation - method. - conversation (google.cloud.discoveryengine_v1.types.Conversation): - Required. The Conversation to update. - 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): - Indicates which fields in the provided - [Conversation][google.cloud.discoveryengine.v1.Conversation] - to update. The following are NOT supported: - - - [conversation.name][] - - If not set or empty, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1.types.Conversation: - External conversation proto - definition. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([conversation, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a conversational_search_service.UpdateConversationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, conversational_search_service.UpdateConversationRequest): - request = conversational_search_service.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), - )), - ) - - # 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[conversational_search_service.GetConversationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation.Conversation: - r"""Gets 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 discoveryengine_v1 - - def sample_get_conversation(): - # Create a client - client = discoveryengine_v1.ConversationalSearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.GetConversationRequest( - name="name_value", - ) - - # Make the request - response = client.get_conversation(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1.types.GetConversationRequest, dict]): - The request object. Request for GetConversation method. - name (str): - Required. The resource name of the Conversation to get. - Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1.types.Conversation: - External conversation proto - definition. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a conversational_search_service.GetConversationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, conversational_search_service.GetConversationRequest): - request = conversational_search_service.GetConversationRequest(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_conversation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_conversations(self, - request: Optional[Union[conversational_search_service.ListConversationsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListConversationsPager: - r"""Lists all Conversations by their parent - [DataStore][google.cloud.discoveryengine.v1.DataStore]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - def sample_list_conversations(): - # Create a client - client = discoveryengine_v1.ConversationalSearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.ListConversationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversations(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1.types.ListConversationsRequest, dict]): - The request object. Request for ListConversations method. - parent (str): - Required. The data store resource name. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1.services.conversational_search_service.pagers.ListConversationsPager: - Response for ListConversations - method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a conversational_search_service.ListConversationsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, conversational_search_service.ListConversationsRequest): - request = conversational_search_service.ListConversationsRequest(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_conversations] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListConversationsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "ConversationalSearchServiceClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - - - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "ConversationalSearchServiceClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/pagers.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/pagers.py deleted file mode 100644 index c2b6b52ec303..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.discoveryengine_v1.types import conversation -from google.cloud.discoveryengine_v1.types import conversational_search_service - - -class ListConversationsPager: - """A pager for iterating through ``list_conversations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.discoveryengine_v1.types.ListConversationsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``conversations`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListConversations`` requests and continue to iterate - through the ``conversations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.discoveryengine_v1.types.ListConversationsResponse` - 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[..., conversational_search_service.ListConversationsResponse], - request: conversational_search_service.ListConversationsRequest, - response: conversational_search_service.ListConversationsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.discoveryengine_v1.types.ListConversationsRequest): - The initial request object. - response (google.cloud.discoveryengine_v1.types.ListConversationsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = conversational_search_service.ListConversationsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[conversational_search_service.ListConversationsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[conversation.Conversation]: - for page in self.pages: - yield from page.conversations - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListConversationsAsyncPager: - """A pager for iterating through ``list_conversations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.discoveryengine_v1.types.ListConversationsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``conversations`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListConversations`` requests and continue to iterate - through the ``conversations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.discoveryengine_v1.types.ListConversationsResponse` - 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[conversational_search_service.ListConversationsResponse]], - request: conversational_search_service.ListConversationsRequest, - response: conversational_search_service.ListConversationsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.discoveryengine_v1.types.ListConversationsRequest): - The initial request object. - response (google.cloud.discoveryengine_v1.types.ListConversationsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = conversational_search_service.ListConversationsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[conversational_search_service.ListConversationsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[conversation.Conversation]: - async def async_generator(): - async for page in self.pages: - for response in page.conversations: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/__init__.py deleted file mode 100644 index f49b63e4b6cd..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import ConversationalSearchServiceTransport -from .grpc import ConversationalSearchServiceGrpcTransport -from .grpc_asyncio import ConversationalSearchServiceGrpcAsyncIOTransport -from .rest import ConversationalSearchServiceRestTransport -from .rest import ConversationalSearchServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ConversationalSearchServiceTransport]] -_transport_registry['grpc'] = ConversationalSearchServiceGrpcTransport -_transport_registry['grpc_asyncio'] = ConversationalSearchServiceGrpcAsyncIOTransport -_transport_registry['rest'] = ConversationalSearchServiceRestTransport - -__all__ = ( - 'ConversationalSearchServiceTransport', - 'ConversationalSearchServiceGrpcTransport', - 'ConversationalSearchServiceGrpcAsyncIOTransport', - 'ConversationalSearchServiceRestTransport', - 'ConversationalSearchServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/base.py deleted file mode 100644 index a37715bd3bad..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/base.py +++ /dev/null @@ -1,241 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.discoveryengine_v1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.discoveryengine_v1.types import conversation -from google.cloud.discoveryengine_v1.types import conversation as gcd_conversation -from google.cloud.discoveryengine_v1.types import conversational_search_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class ConversationalSearchServiceTransport(abc.ABC): - """Abstract transport class for ConversationalSearchService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'discoveryengine.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.converse_conversation: gapic_v1.method.wrap_method( - self.converse_conversation, - default_timeout=None, - client_info=client_info, - ), - self.create_conversation: gapic_v1.method.wrap_method( - self.create_conversation, - default_timeout=None, - client_info=client_info, - ), - self.delete_conversation: gapic_v1.method.wrap_method( - self.delete_conversation, - 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, - client_info=client_info, - ), - self.list_conversations: gapic_v1.method.wrap_method( - self.list_conversations, - 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 converse_conversation(self) -> Callable[ - [conversational_search_service.ConverseConversationRequest], - Union[ - conversational_search_service.ConverseConversationResponse, - Awaitable[conversational_search_service.ConverseConversationResponse] - ]]: - raise NotImplementedError() - - @property - def create_conversation(self) -> Callable[ - [conversational_search_service.CreateConversationRequest], - Union[ - gcd_conversation.Conversation, - Awaitable[gcd_conversation.Conversation] - ]]: - raise NotImplementedError() - - @property - def delete_conversation(self) -> Callable[ - [conversational_search_service.DeleteConversationRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def update_conversation(self) -> Callable[ - [conversational_search_service.UpdateConversationRequest], - Union[ - gcd_conversation.Conversation, - Awaitable[gcd_conversation.Conversation] - ]]: - raise NotImplementedError() - - @property - def get_conversation(self) -> Callable[ - [conversational_search_service.GetConversationRequest], - Union[ - conversation.Conversation, - Awaitable[conversation.Conversation] - ]]: - raise NotImplementedError() - - @property - def list_conversations(self) -> Callable[ - [conversational_search_service.ListConversationsRequest], - Union[ - conversational_search_service.ListConversationsResponse, - Awaitable[conversational_search_service.ListConversationsResponse] - ]]: - 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 kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ConversationalSearchServiceTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/grpc.py deleted file mode 100644 index d3ab8f9f152f..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/grpc.py +++ /dev/null @@ -1,449 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.discoveryengine_v1.types import conversation -from google.cloud.discoveryengine_v1.types import conversation as gcd_conversation -from google.cloud.discoveryengine_v1.types import conversational_search_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import ConversationalSearchServiceTransport, DEFAULT_CLIENT_INFO - - -class ConversationalSearchServiceGrpcTransport(ConversationalSearchServiceTransport): - """gRPC backend transport for ConversationalSearchService. - - Service for conversational search. - - 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def converse_conversation(self) -> Callable[ - [conversational_search_service.ConverseConversationRequest], - conversational_search_service.ConverseConversationResponse]: - r"""Return a callable for the converse conversation method over gRPC. - - Converses a conversation. - - Returns: - Callable[[~.ConverseConversationRequest], - ~.ConverseConversationResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'converse_conversation' not in self._stubs: - self._stubs['converse_conversation'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.ConversationalSearchService/ConverseConversation', - request_serializer=conversational_search_service.ConverseConversationRequest.serialize, - response_deserializer=conversational_search_service.ConverseConversationResponse.deserialize, - ) - return self._stubs['converse_conversation'] - - @property - def create_conversation(self) -> Callable[ - [conversational_search_service.CreateConversationRequest], - gcd_conversation.Conversation]: - r"""Return a callable for the create conversation method over gRPC. - - Creates a Conversation. - - If the - [Conversation][google.cloud.discoveryengine.v1.Conversation] to - create already exists, an ALREADY_EXISTS error is returned. - - Returns: - Callable[[~.CreateConversationRequest], - ~.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 'create_conversation' not in self._stubs: - self._stubs['create_conversation'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.ConversationalSearchService/CreateConversation', - request_serializer=conversational_search_service.CreateConversationRequest.serialize, - response_deserializer=gcd_conversation.Conversation.deserialize, - ) - return self._stubs['create_conversation'] - - @property - def delete_conversation(self) -> Callable[ - [conversational_search_service.DeleteConversationRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete conversation method over gRPC. - - Deletes a Conversation. - - If the - [Conversation][google.cloud.discoveryengine.v1.Conversation] to - delete does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.DeleteConversationRequest], - ~.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_conversation' not in self._stubs: - self._stubs['delete_conversation'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.ConversationalSearchService/DeleteConversation', - request_serializer=conversational_search_service.DeleteConversationRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_conversation'] - - @property - def update_conversation(self) -> Callable[ - [conversational_search_service.UpdateConversationRequest], - gcd_conversation.Conversation]: - r"""Return a callable for the update conversation method over gRPC. - - Updates a Conversation. - - [Conversation][google.cloud.discoveryengine.v1.Conversation] - action type cannot be changed. If the - [Conversation][google.cloud.discoveryengine.v1.Conversation] to - update does not exist, a NOT_FOUND error is returned. - - 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.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.ConversationalSearchService/UpdateConversation', - request_serializer=conversational_search_service.UpdateConversationRequest.serialize, - response_deserializer=gcd_conversation.Conversation.deserialize, - ) - return self._stubs['update_conversation'] - - @property - def get_conversation(self) -> Callable[ - [conversational_search_service.GetConversationRequest], - conversation.Conversation]: - r"""Return a callable for the get conversation method over gRPC. - - Gets a Conversation. - - Returns: - Callable[[~.GetConversationRequest], - ~.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 'get_conversation' not in self._stubs: - self._stubs['get_conversation'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.ConversationalSearchService/GetConversation', - request_serializer=conversational_search_service.GetConversationRequest.serialize, - response_deserializer=conversation.Conversation.deserialize, - ) - return self._stubs['get_conversation'] - - @property - def list_conversations(self) -> Callable[ - [conversational_search_service.ListConversationsRequest], - conversational_search_service.ListConversationsResponse]: - r"""Return a callable for the list conversations method over gRPC. - - Lists all Conversations by their parent - [DataStore][google.cloud.discoveryengine.v1.DataStore]. - - Returns: - Callable[[~.ListConversationsRequest], - ~.ListConversationsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_conversations' not in self._stubs: - self._stubs['list_conversations'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.ConversationalSearchService/ListConversations', - request_serializer=conversational_search_service.ListConversationsRequest.serialize, - response_deserializer=conversational_search_service.ListConversationsResponse.deserialize, - ) - return self._stubs['list_conversations'] - - def close(self): - self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ConversationalSearchServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/grpc_asyncio.py deleted file mode 100644 index c7ca32705683..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,448 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.discoveryengine_v1.types import conversation -from google.cloud.discoveryengine_v1.types import conversation as gcd_conversation -from google.cloud.discoveryengine_v1.types import conversational_search_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import ConversationalSearchServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import ConversationalSearchServiceGrpcTransport - - -class ConversationalSearchServiceGrpcAsyncIOTransport(ConversationalSearchServiceTransport): - """gRPC AsyncIO backend transport for ConversationalSearchService. - - Service for conversational search. - - 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def converse_conversation(self) -> Callable[ - [conversational_search_service.ConverseConversationRequest], - Awaitable[conversational_search_service.ConverseConversationResponse]]: - r"""Return a callable for the converse conversation method over gRPC. - - Converses a conversation. - - Returns: - Callable[[~.ConverseConversationRequest], - Awaitable[~.ConverseConversationResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'converse_conversation' not in self._stubs: - self._stubs['converse_conversation'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.ConversationalSearchService/ConverseConversation', - request_serializer=conversational_search_service.ConverseConversationRequest.serialize, - response_deserializer=conversational_search_service.ConverseConversationResponse.deserialize, - ) - return self._stubs['converse_conversation'] - - @property - def create_conversation(self) -> Callable[ - [conversational_search_service.CreateConversationRequest], - Awaitable[gcd_conversation.Conversation]]: - r"""Return a callable for the create conversation method over gRPC. - - Creates a Conversation. - - If the - [Conversation][google.cloud.discoveryengine.v1.Conversation] to - create already exists, an ALREADY_EXISTS error is returned. - - Returns: - Callable[[~.CreateConversationRequest], - 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 'create_conversation' not in self._stubs: - self._stubs['create_conversation'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.ConversationalSearchService/CreateConversation', - request_serializer=conversational_search_service.CreateConversationRequest.serialize, - response_deserializer=gcd_conversation.Conversation.deserialize, - ) - return self._stubs['create_conversation'] - - @property - def delete_conversation(self) -> Callable[ - [conversational_search_service.DeleteConversationRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete conversation method over gRPC. - - Deletes a Conversation. - - If the - [Conversation][google.cloud.discoveryengine.v1.Conversation] to - delete does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.DeleteConversationRequest], - 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_conversation' not in self._stubs: - self._stubs['delete_conversation'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.ConversationalSearchService/DeleteConversation', - request_serializer=conversational_search_service.DeleteConversationRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_conversation'] - - @property - def update_conversation(self) -> Callable[ - [conversational_search_service.UpdateConversationRequest], - Awaitable[gcd_conversation.Conversation]]: - r"""Return a callable for the update conversation method over gRPC. - - Updates a Conversation. - - [Conversation][google.cloud.discoveryengine.v1.Conversation] - action type cannot be changed. If the - [Conversation][google.cloud.discoveryengine.v1.Conversation] to - update does not exist, a NOT_FOUND error is returned. - - 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.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.ConversationalSearchService/UpdateConversation', - request_serializer=conversational_search_service.UpdateConversationRequest.serialize, - response_deserializer=gcd_conversation.Conversation.deserialize, - ) - return self._stubs['update_conversation'] - - @property - def get_conversation(self) -> Callable[ - [conversational_search_service.GetConversationRequest], - Awaitable[conversation.Conversation]]: - r"""Return a callable for the get conversation method over gRPC. - - Gets a Conversation. - - Returns: - Callable[[~.GetConversationRequest], - 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 'get_conversation' not in self._stubs: - self._stubs['get_conversation'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.ConversationalSearchService/GetConversation', - request_serializer=conversational_search_service.GetConversationRequest.serialize, - response_deserializer=conversation.Conversation.deserialize, - ) - return self._stubs['get_conversation'] - - @property - def list_conversations(self) -> Callable[ - [conversational_search_service.ListConversationsRequest], - Awaitable[conversational_search_service.ListConversationsResponse]]: - r"""Return a callable for the list conversations method over gRPC. - - Lists all Conversations by their parent - [DataStore][google.cloud.discoveryengine.v1.DataStore]. - - Returns: - Callable[[~.ListConversationsRequest], - Awaitable[~.ListConversationsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_conversations' not in self._stubs: - self._stubs['list_conversations'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.ConversationalSearchService/ListConversations', - request_serializer=conversational_search_service.ListConversationsRequest.serialize, - response_deserializer=conversational_search_service.ListConversationsResponse.deserialize, - ) - return self._stubs['list_conversations'] - - def close(self): - return self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - -__all__ = ( - 'ConversationalSearchServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/rest.py deleted file mode 100644 index ba997c667314..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/rest.py +++ /dev/null @@ -1,1164 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.cloud.location import locations_pb2 # type: ignore -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.discoveryengine_v1.types import conversation -from google.cloud.discoveryengine_v1.types import conversation as gcd_conversation -from google.cloud.discoveryengine_v1.types import conversational_search_service -from google.protobuf import empty_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from .base import ConversationalSearchServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class ConversationalSearchServiceRestInterceptor: - """Interceptor for ConversationalSearchService. - - 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 ConversationalSearchServiceRestTransport. - - .. code-block:: python - class MyCustomConversationalSearchServiceInterceptor(ConversationalSearchServiceRestInterceptor): - def pre_converse_conversation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_converse_conversation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_conversation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_conversation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_conversation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_conversation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_conversation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_conversations(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_conversations(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 = ConversationalSearchServiceRestTransport(interceptor=MyCustomConversationalSearchServiceInterceptor()) - client = ConversationalSearchServiceClient(transport=transport) - - - """ - def pre_converse_conversation(self, request: conversational_search_service.ConverseConversationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversational_search_service.ConverseConversationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for converse_conversation - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationalSearchService server. - """ - return request, metadata - - def post_converse_conversation(self, response: conversational_search_service.ConverseConversationResponse) -> conversational_search_service.ConverseConversationResponse: - """Post-rpc interceptor for converse_conversation - - Override in a subclass to manipulate the response - after it is returned by the ConversationalSearchService server but before - it is returned to user code. - """ - return response - def pre_create_conversation(self, request: conversational_search_service.CreateConversationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversational_search_service.CreateConversationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_conversation - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationalSearchService server. - """ - return request, metadata - - def post_create_conversation(self, response: gcd_conversation.Conversation) -> gcd_conversation.Conversation: - """Post-rpc interceptor for create_conversation - - Override in a subclass to manipulate the response - after it is returned by the ConversationalSearchService server but before - it is returned to user code. - """ - return response - def pre_delete_conversation(self, request: conversational_search_service.DeleteConversationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversational_search_service.DeleteConversationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_conversation - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationalSearchService server. - """ - return request, metadata - - def pre_get_conversation(self, request: conversational_search_service.GetConversationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversational_search_service.GetConversationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_conversation - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationalSearchService server. - """ - return request, metadata - - def post_get_conversation(self, response: conversation.Conversation) -> conversation.Conversation: - """Post-rpc interceptor for get_conversation - - Override in a subclass to manipulate the response - after it is returned by the ConversationalSearchService server but before - it is returned to user code. - """ - return response - def pre_list_conversations(self, request: conversational_search_service.ListConversationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversational_search_service.ListConversationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_conversations - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationalSearchService server. - """ - return request, metadata - - def post_list_conversations(self, response: conversational_search_service.ListConversationsResponse) -> conversational_search_service.ListConversationsResponse: - """Post-rpc interceptor for list_conversations - - Override in a subclass to manipulate the response - after it is returned by the ConversationalSearchService server but before - it is returned to user code. - """ - return response - def pre_update_conversation(self, request: conversational_search_service.UpdateConversationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversational_search_service.UpdateConversationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_conversation - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationalSearchService server. - """ - return request, metadata - - def post_update_conversation(self, response: gcd_conversation.Conversation) -> gcd_conversation.Conversation: - """Post-rpc interceptor for update_conversation - - Override in a subclass to manipulate the response - after it is returned by the ConversationalSearchService server but before - it is returned to user code. - """ - return response - - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationalSearchService 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 ConversationalSearchService server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationalSearchService 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 ConversationalSearchService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class ConversationalSearchServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: ConversationalSearchServiceRestInterceptor - - -class ConversationalSearchServiceRestTransport(ConversationalSearchServiceTransport): - """REST backend transport for ConversationalSearchService. - - Service for conversational search. - - 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 = 'discoveryengine.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[ConversationalSearchServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or ConversationalSearchServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _ConverseConversation(ConversationalSearchServiceRestStub): - def __hash__(self): - return hash("ConverseConversation") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversational_search_service.ConverseConversationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> conversational_search_service.ConverseConversationResponse: - r"""Call the converse conversation method over HTTP. - - Args: - request (~.conversational_search_service.ConverseConversationRequest): - The request object. Request message for - [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1.ConversationalSearchService.ConverseConversation] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.conversational_search_service.ConverseConversationResponse: - Response message for - [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1.ConversationalSearchService.ConverseConversation] - method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/conversations/*}:converse', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/conversations/*}:converse', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_converse_conversation(request, metadata) - pb_request = conversational_search_service.ConverseConversationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = conversational_search_service.ConverseConversationResponse() - pb_resp = conversational_search_service.ConverseConversationResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_converse_conversation(resp) - return resp - - class _CreateConversation(ConversationalSearchServiceRestStub): - def __hash__(self): - return hash("CreateConversation") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversational_search_service.CreateConversationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_conversation.Conversation: - r"""Call the create conversation method over HTTP. - - Args: - request (~.conversational_search_service.CreateConversationRequest): - The request object. Request for CreateConversation - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcd_conversation.Conversation: - External conversation proto - definition. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/dataStores/*}/conversations', - 'body': 'conversation', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/collections/*/dataStores/*}/conversations', - 'body': 'conversation', - }, - ] - request, metadata = self._interceptor.pre_create_conversation(request, metadata) - pb_request = conversational_search_service.CreateConversationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_conversation.Conversation() - pb_resp = gcd_conversation.Conversation.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_conversation(resp) - return resp - - class _DeleteConversation(ConversationalSearchServiceRestStub): - def __hash__(self): - return hash("DeleteConversation") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversational_search_service.DeleteConversationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete conversation method over HTTP. - - Args: - request (~.conversational_search_service.DeleteConversationRequest): - The request object. Request for DeleteConversation - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/conversations/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/conversations/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_conversation(request, metadata) - pb_request = conversational_search_service.DeleteConversationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _GetConversation(ConversationalSearchServiceRestStub): - def __hash__(self): - return hash("GetConversation") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversational_search_service.GetConversationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> conversation.Conversation: - r"""Call the get conversation method over HTTP. - - Args: - request (~.conversational_search_service.GetConversationRequest): - The request object. Request for GetConversation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.conversation.Conversation: - External conversation proto - definition. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/conversations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/conversations/*}', - }, - ] - request, metadata = self._interceptor.pre_get_conversation(request, metadata) - pb_request = conversational_search_service.GetConversationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = conversation.Conversation() - pb_resp = conversation.Conversation.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_conversation(resp) - return resp - - class _ListConversations(ConversationalSearchServiceRestStub): - def __hash__(self): - return hash("ListConversations") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversational_search_service.ListConversationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> conversational_search_service.ListConversationsResponse: - r"""Call the list conversations method over HTTP. - - Args: - request (~.conversational_search_service.ListConversationsRequest): - The request object. Request for ListConversations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.conversational_search_service.ListConversationsResponse: - Response for ListConversations - method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/dataStores/*}/conversations', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/collections/*/dataStores/*}/conversations', - }, - ] - request, metadata = self._interceptor.pre_list_conversations(request, metadata) - pb_request = conversational_search_service.ListConversationsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = conversational_search_service.ListConversationsResponse() - pb_resp = conversational_search_service.ListConversationsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_conversations(resp) - return resp - - class _UpdateConversation(ConversationalSearchServiceRestStub): - def __hash__(self): - return hash("UpdateConversation") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversational_search_service.UpdateConversationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_conversation.Conversation: - r"""Call the update conversation method over HTTP. - - Args: - request (~.conversational_search_service.UpdateConversationRequest): - The request object. Request for UpdateConversation - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcd_conversation.Conversation: - External conversation proto - definition. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{conversation.name=projects/*/locations/*/dataStores/*/conversations/*}', - 'body': 'conversation', - }, -{ - 'method': 'patch', - 'uri': '/v1/{conversation.name=projects/*/locations/*/collections/*/dataStores/*/conversations/*}', - 'body': 'conversation', - }, - ] - request, metadata = self._interceptor.pre_update_conversation(request, metadata) - pb_request = conversational_search_service.UpdateConversationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_conversation.Conversation() - pb_resp = gcd_conversation.Conversation.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_conversation(resp) - return resp - - @property - def converse_conversation(self) -> Callable[ - [conversational_search_service.ConverseConversationRequest], - conversational_search_service.ConverseConversationResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ConverseConversation(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_conversation(self) -> Callable[ - [conversational_search_service.CreateConversationRequest], - gcd_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._CreateConversation(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_conversation(self) -> Callable[ - [conversational_search_service.DeleteConversationRequest], - 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._DeleteConversation(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_conversation(self) -> Callable[ - [conversational_search_service.GetConversationRequest], - 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._GetConversation(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_conversations(self) -> Callable[ - [conversational_search_service.ListConversationsRequest], - conversational_search_service.ListConversationsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListConversations(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_conversation(self) -> Callable[ - [conversational_search_service.UpdateConversationRequest], - gcd_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_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(ConversationalSearchServiceRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(ConversationalSearchServiceRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/engines/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'ConversationalSearchServiceRestTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/__init__.py deleted file mode 100644 index e4f0b808a498..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import DocumentServiceClient -from .async_client import DocumentServiceAsyncClient - -__all__ = ( - 'DocumentServiceClient', - 'DocumentServiceAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/async_client.py deleted file mode 100644 index 729c1e2e58bb..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/async_client.py +++ /dev/null @@ -1,1109 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.discoveryengine_v1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.discoveryengine_v1.services.document_service import pagers -from google.cloud.discoveryengine_v1.types import document -from google.cloud.discoveryengine_v1.types import document as gcd_document -from google.cloud.discoveryengine_v1.types import document_service -from google.cloud.discoveryengine_v1.types import import_config -from google.cloud.discoveryengine_v1.types import purge_config -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from .transports.base import DocumentServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import DocumentServiceGrpcAsyncIOTransport -from .client import DocumentServiceClient - - -class DocumentServiceAsyncClient: - """Service for ingesting - [Document][google.cloud.discoveryengine.v1.Document] information of - the customer's website. - """ - - _client: DocumentServiceClient - - DEFAULT_ENDPOINT = DocumentServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = DocumentServiceClient.DEFAULT_MTLS_ENDPOINT - - branch_path = staticmethod(DocumentServiceClient.branch_path) - parse_branch_path = staticmethod(DocumentServiceClient.parse_branch_path) - document_path = staticmethod(DocumentServiceClient.document_path) - parse_document_path = staticmethod(DocumentServiceClient.parse_document_path) - common_billing_account_path = staticmethod(DocumentServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(DocumentServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(DocumentServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(DocumentServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(DocumentServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(DocumentServiceClient.parse_common_organization_path) - common_project_path = staticmethod(DocumentServiceClient.common_project_path) - parse_common_project_path = staticmethod(DocumentServiceClient.parse_common_project_path) - common_location_path = staticmethod(DocumentServiceClient.common_location_path) - parse_common_location_path = staticmethod(DocumentServiceClient.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: - DocumentServiceAsyncClient: The constructed client. - """ - return DocumentServiceClient.from_service_account_info.__func__(DocumentServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DocumentServiceAsyncClient: The constructed client. - """ - return DocumentServiceClient.from_service_account_file.__func__(DocumentServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return DocumentServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> DocumentServiceTransport: - """Returns the transport used by the client instance. - - Returns: - DocumentServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(DocumentServiceClient).get_transport_class, type(DocumentServiceClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, DocumentServiceTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the document 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 (Union[str, ~.DocumentServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = DocumentServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def get_document(self, - request: Optional[Union[document_service.GetDocumentRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document.Document: - r"""Gets a [Document][google.cloud.discoveryengine.v1.Document]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - async def sample_get_document(): - # Create a client - client = discoveryengine_v1.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.GetDocumentRequest( - name="name_value", - ) - - # Make the request - response = await client.get_document(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1.types.GetDocumentRequest, dict]]): - The request object. Request message for - [DocumentService.GetDocument][google.cloud.discoveryengine.v1.DocumentService.GetDocument] - method. - name (:class:`str`): - Required. Full resource name of - [Document][google.cloud.discoveryengine.v1.Document], - such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. - - If the caller does not have permission to access the - [Document][google.cloud.discoveryengine.v1.Document], - regardless of whether or not it exists, a - ``PERMISSION_DENIED`` error is returned. - - If the requested - [Document][google.cloud.discoveryengine.v1.Document] - does not exist, a ``NOT_FOUND`` error is returned. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1.types.Document: - Document captures all raw metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = document_service.GetDocumentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_document, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_documents(self, - request: Optional[Union[document_service.ListDocumentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDocumentsAsyncPager: - r"""Gets a list of - [Document][google.cloud.discoveryengine.v1.Document]s. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - async def sample_list_documents(): - # Create a client - client = discoveryengine_v1.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.ListDocumentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_documents(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1.types.ListDocumentsRequest, dict]]): - The request object. Request message for - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1.DocumentService.ListDocuments] - method. - parent (:class:`str`): - Required. The parent branch resource name, such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. - Use ``default_branch`` as the branch ID, to list - documents under the default branch. - - If the caller does not have permission to list - [Document][google.cloud.discoveryengine.v1.Document]s - under this branch, regardless of whether or not this - branch exists, a ``PERMISSION_DENIED`` error is - returned. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1.services.document_service.pagers.ListDocumentsAsyncPager: - Response message for - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1.DocumentService.ListDocuments] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = document_service.ListDocumentsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_documents, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListDocumentsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_document(self, - request: Optional[Union[document_service.CreateDocumentRequest, dict]] = None, - *, - parent: Optional[str] = None, - document: Optional[gcd_document.Document] = None, - document_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_document.Document: - r"""Creates a [Document][google.cloud.discoveryengine.v1.Document]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - async def sample_create_document(): - # Create a client - client = discoveryengine_v1.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.CreateDocumentRequest( - parent="parent_value", - document_id="document_id_value", - ) - - # Make the request - response = await client.create_document(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1.types.CreateDocumentRequest, dict]]): - The request object. Request message for - [DocumentService.CreateDocument][google.cloud.discoveryengine.v1.DocumentService.CreateDocument] - method. - parent (:class:`str`): - Required. The parent resource name, such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - document (:class:`google.cloud.discoveryengine_v1.types.Document`): - Required. The - [Document][google.cloud.discoveryengine.v1.Document] to - create. - - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - document_id (:class:`str`): - Required. The ID to use for the - [Document][google.cloud.discoveryengine.v1.Document], - which will become the final component of the - [Document.name][google.cloud.discoveryengine.v1.Document.name]. - - If the caller does not have permission to create the - [Document][google.cloud.discoveryengine.v1.Document], - regardless of whether or not it exists, a - ``PERMISSION_DENIED`` error is returned. - - This field must be unique among all - [Document][google.cloud.discoveryengine.v1.Document]s - with the same - [parent][google.cloud.discoveryengine.v1.CreateDocumentRequest.parent]. - Otherwise, an ``ALREADY_EXISTS`` error is returned. - - This field must conform to - `RFC-1034 `__ - standard with a length limit of 63 characters. - Otherwise, an ``INVALID_ARGUMENT`` error is returned. - - This corresponds to the ``document_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1.types.Document: - Document captures all raw metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, document, document_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = document_service.CreateDocumentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if document is not None: - request.document = document - if document_id is not None: - request.document_id = document_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_document, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_document(self, - request: Optional[Union[document_service.UpdateDocumentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document.Document: - r"""Updates a [Document][google.cloud.discoveryengine.v1.Document]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - async def sample_update_document(): - # Create a client - client = discoveryengine_v1.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.UpdateDocumentRequest( - ) - - # Make the request - response = await client.update_document(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1.types.UpdateDocumentRequest, dict]]): - The request object. Request message for - [DocumentService.UpdateDocument][google.cloud.discoveryengine.v1.DocumentService.UpdateDocument] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1.types.Document: - Document captures all raw metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - request = document_service.UpdateDocumentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_document, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("document.name", request.document.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_document(self, - request: Optional[Union[document_service.DeleteDocumentRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a [Document][google.cloud.discoveryengine.v1.Document]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - async def sample_delete_document(): - # Create a client - client = discoveryengine_v1.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.DeleteDocumentRequest( - name="name_value", - ) - - # Make the request - await client.delete_document(request=request) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1.types.DeleteDocumentRequest, dict]]): - The request object. Request message for - [DocumentService.DeleteDocument][google.cloud.discoveryengine.v1.DocumentService.DeleteDocument] - method. - name (:class:`str`): - Required. Full resource name of - [Document][google.cloud.discoveryengine.v1.Document], - such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. - - If the caller does not have permission to delete the - [Document][google.cloud.discoveryengine.v1.Document], - regardless of whether or not it exists, a - ``PERMISSION_DENIED`` error is returned. - - If the - [Document][google.cloud.discoveryengine.v1.Document] to - delete does not exist, a ``NOT_FOUND`` error is - returned. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = document_service.DeleteDocumentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_document, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def import_documents(self, - request: Optional[Union[import_config.ImportDocumentsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Bulk import of multiple - [Document][google.cloud.discoveryengine.v1.Document]s. Request - processing may be synchronous. Non-existing items will be - created. - - Note: It is possible for a subset of the - [Document][google.cloud.discoveryengine.v1.Document]s to be - successfully updated. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - async def sample_import_documents(): - # Create a client - client = discoveryengine_v1.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.ImportDocumentsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.import_documents(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1.types.ImportDocumentsRequest, dict]]): - The request object. Request message for Import methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.discoveryengine_v1.types.ImportDocumentsResponse` Response of the - [ImportDocumentsRequest][google.cloud.discoveryengine.v1.ImportDocumentsRequest]. - If the long running operation is done, then this - message is returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - request = import_config.ImportDocumentsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_documents, - default_retry=retries.Retry( -initial=1.0,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=300.0, - ), - default_timeout=300.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - import_config.ImportDocumentsResponse, - metadata_type=import_config.ImportDocumentsMetadata, - ) - - # Done; return the response. - return response - - async def purge_documents(self, - request: Optional[Union[purge_config.PurgeDocumentsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Permanently deletes all selected - [Document][google.cloud.discoveryengine.v1.Document]s in a - branch. - - This process is asynchronous. Depending on the number of - [Document][google.cloud.discoveryengine.v1.Document]s to be - deleted, this operation can take hours to complete. Before the - delete operation completes, some - [Document][google.cloud.discoveryengine.v1.Document]s might - still be returned by - [DocumentService.GetDocument][google.cloud.discoveryengine.v1.DocumentService.GetDocument] - or - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1.DocumentService.ListDocuments]. - - To get a list of the - [Document][google.cloud.discoveryengine.v1.Document]s to be - deleted, set - [PurgeDocumentsRequest.force][google.cloud.discoveryengine.v1.PurgeDocumentsRequest.force] - to false. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - async def sample_purge_documents(): - # Create a client - client = discoveryengine_v1.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.PurgeDocumentsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_documents(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1.types.PurgeDocumentsRequest, dict]]): - The request object. Request message for - [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1.DocumentService.PurgeDocuments] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.discoveryengine_v1.types.PurgeDocumentsResponse` Response message for - [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1.DocumentService.PurgeDocuments] - method. If the long running operation is successfully - done, then this message is returned by the - google.longrunning.Operations.response field. - - """ - # Create or coerce a protobuf request object. - request = purge_config.PurgeDocumentsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.purge_documents, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - purge_config.PurgeDocumentsResponse, - metadata_type=purge_config.PurgeDocumentsMetadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "DocumentServiceAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "DocumentServiceAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/client.py deleted file mode 100644 index 7cd733b747e9..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/client.py +++ /dev/null @@ -1,1322 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.discoveryengine_v1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.discoveryengine_v1.services.document_service import pagers -from google.cloud.discoveryengine_v1.types import document -from google.cloud.discoveryengine_v1.types import document as gcd_document -from google.cloud.discoveryengine_v1.types import document_service -from google.cloud.discoveryengine_v1.types import import_config -from google.cloud.discoveryengine_v1.types import purge_config -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from .transports.base import DocumentServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import DocumentServiceGrpcTransport -from .transports.grpc_asyncio import DocumentServiceGrpcAsyncIOTransport -from .transports.rest import DocumentServiceRestTransport - - -class DocumentServiceClientMeta(type): - """Metaclass for the DocumentService 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[DocumentServiceTransport]] - _transport_registry["grpc"] = DocumentServiceGrpcTransport - _transport_registry["grpc_asyncio"] = DocumentServiceGrpcAsyncIOTransport - _transport_registry["rest"] = DocumentServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[DocumentServiceTransport]: - """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 DocumentServiceClient(metaclass=DocumentServiceClientMeta): - """Service for ingesting - [Document][google.cloud.discoveryengine.v1.Document] information of - the customer's website. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DocumentServiceClient: 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: - DocumentServiceClient: 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) -> DocumentServiceTransport: - """Returns the transport used by the client instance. - - Returns: - DocumentServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def branch_path(project: str,location: str,data_store: str,branch: str,) -> str: - """Returns a fully-qualified branch string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}".format(project=project, location=location, data_store=data_store, branch=branch, ) - - @staticmethod - def parse_branch_path(path: str) -> Dict[str,str]: - """Parses a branch path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def document_path(project: str,location: str,data_store: str,branch: str,document: str,) -> str: - """Returns a fully-qualified document string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) - - @staticmethod - def parse_document_path(path: str) -> Dict[str,str]: - """Parses a document path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)/documents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, DocumentServiceTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the document 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 (Union[str, DocumentServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, DocumentServiceTransport): - # transport is a DocumentServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def get_document(self, - request: Optional[Union[document_service.GetDocumentRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document.Document: - r"""Gets a [Document][google.cloud.discoveryengine.v1.Document]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - def sample_get_document(): - # Create a client - client = discoveryengine_v1.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.GetDocumentRequest( - name="name_value", - ) - - # Make the request - response = client.get_document(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1.types.GetDocumentRequest, dict]): - The request object. Request message for - [DocumentService.GetDocument][google.cloud.discoveryengine.v1.DocumentService.GetDocument] - method. - name (str): - Required. Full resource name of - [Document][google.cloud.discoveryengine.v1.Document], - such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. - - If the caller does not have permission to access the - [Document][google.cloud.discoveryengine.v1.Document], - regardless of whether or not it exists, a - ``PERMISSION_DENIED`` error is returned. - - If the requested - [Document][google.cloud.discoveryengine.v1.Document] - does not exist, a ``NOT_FOUND`` error is returned. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1.types.Document: - Document captures all raw metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a document_service.GetDocumentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, document_service.GetDocumentRequest): - request = document_service.GetDocumentRequest(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_document] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_documents(self, - request: Optional[Union[document_service.ListDocumentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDocumentsPager: - r"""Gets a list of - [Document][google.cloud.discoveryengine.v1.Document]s. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - def sample_list_documents(): - # Create a client - client = discoveryengine_v1.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.ListDocumentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_documents(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1.types.ListDocumentsRequest, dict]): - The request object. Request message for - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1.DocumentService.ListDocuments] - method. - parent (str): - Required. The parent branch resource name, such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. - Use ``default_branch`` as the branch ID, to list - documents under the default branch. - - If the caller does not have permission to list - [Document][google.cloud.discoveryengine.v1.Document]s - under this branch, regardless of whether or not this - branch exists, a ``PERMISSION_DENIED`` error is - returned. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1.services.document_service.pagers.ListDocumentsPager: - Response message for - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1.DocumentService.ListDocuments] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a document_service.ListDocumentsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, document_service.ListDocumentsRequest): - request = document_service.ListDocumentsRequest(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_documents] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListDocumentsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_document(self, - request: Optional[Union[document_service.CreateDocumentRequest, dict]] = None, - *, - parent: Optional[str] = None, - document: Optional[gcd_document.Document] = None, - document_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_document.Document: - r"""Creates a [Document][google.cloud.discoveryengine.v1.Document]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - def sample_create_document(): - # Create a client - client = discoveryengine_v1.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.CreateDocumentRequest( - parent="parent_value", - document_id="document_id_value", - ) - - # Make the request - response = client.create_document(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1.types.CreateDocumentRequest, dict]): - The request object. Request message for - [DocumentService.CreateDocument][google.cloud.discoveryengine.v1.DocumentService.CreateDocument] - method. - parent (str): - Required. The parent resource name, such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - document (google.cloud.discoveryengine_v1.types.Document): - Required. The - [Document][google.cloud.discoveryengine.v1.Document] to - create. - - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - document_id (str): - Required. The ID to use for the - [Document][google.cloud.discoveryengine.v1.Document], - which will become the final component of the - [Document.name][google.cloud.discoveryengine.v1.Document.name]. - - If the caller does not have permission to create the - [Document][google.cloud.discoveryengine.v1.Document], - regardless of whether or not it exists, a - ``PERMISSION_DENIED`` error is returned. - - This field must be unique among all - [Document][google.cloud.discoveryengine.v1.Document]s - with the same - [parent][google.cloud.discoveryengine.v1.CreateDocumentRequest.parent]. - Otherwise, an ``ALREADY_EXISTS`` error is returned. - - This field must conform to - `RFC-1034 `__ - standard with a length limit of 63 characters. - Otherwise, an ``INVALID_ARGUMENT`` error is returned. - - This corresponds to the ``document_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1.types.Document: - Document captures all raw metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, document, document_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a document_service.CreateDocumentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, document_service.CreateDocumentRequest): - request = document_service.CreateDocumentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if document is not None: - request.document = document - if document_id is not None: - request.document_id = document_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_document] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_document(self, - request: Optional[Union[document_service.UpdateDocumentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document.Document: - r"""Updates a [Document][google.cloud.discoveryengine.v1.Document]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - def sample_update_document(): - # Create a client - client = discoveryengine_v1.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.UpdateDocumentRequest( - ) - - # Make the request - response = client.update_document(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1.types.UpdateDocumentRequest, dict]): - The request object. Request message for - [DocumentService.UpdateDocument][google.cloud.discoveryengine.v1.DocumentService.UpdateDocument] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1.types.Document: - Document captures all raw metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a document_service.UpdateDocumentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, document_service.UpdateDocumentRequest): - request = document_service.UpdateDocumentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_document] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("document.name", request.document.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_document(self, - request: Optional[Union[document_service.DeleteDocumentRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a [Document][google.cloud.discoveryengine.v1.Document]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - def sample_delete_document(): - # Create a client - client = discoveryengine_v1.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.DeleteDocumentRequest( - name="name_value", - ) - - # Make the request - client.delete_document(request=request) - - Args: - request (Union[google.cloud.discoveryengine_v1.types.DeleteDocumentRequest, dict]): - The request object. Request message for - [DocumentService.DeleteDocument][google.cloud.discoveryengine.v1.DocumentService.DeleteDocument] - method. - name (str): - Required. Full resource name of - [Document][google.cloud.discoveryengine.v1.Document], - such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. - - If the caller does not have permission to delete the - [Document][google.cloud.discoveryengine.v1.Document], - regardless of whether or not it exists, a - ``PERMISSION_DENIED`` error is returned. - - If the - [Document][google.cloud.discoveryengine.v1.Document] to - delete does not exist, a ``NOT_FOUND`` error is - returned. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a document_service.DeleteDocumentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, document_service.DeleteDocumentRequest): - request = document_service.DeleteDocumentRequest(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_document] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def import_documents(self, - request: Optional[Union[import_config.ImportDocumentsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Bulk import of multiple - [Document][google.cloud.discoveryengine.v1.Document]s. Request - processing may be synchronous. Non-existing items will be - created. - - Note: It is possible for a subset of the - [Document][google.cloud.discoveryengine.v1.Document]s to be - successfully updated. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - def sample_import_documents(): - # Create a client - client = discoveryengine_v1.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.ImportDocumentsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.import_documents(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1.types.ImportDocumentsRequest, dict]): - The request object. Request message for Import methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.discoveryengine_v1.types.ImportDocumentsResponse` Response of the - [ImportDocumentsRequest][google.cloud.discoveryengine.v1.ImportDocumentsRequest]. - If the long running operation is done, then this - message is returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a import_config.ImportDocumentsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, import_config.ImportDocumentsRequest): - request = import_config.ImportDocumentsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_documents] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - import_config.ImportDocumentsResponse, - metadata_type=import_config.ImportDocumentsMetadata, - ) - - # Done; return the response. - return response - - def purge_documents(self, - request: Optional[Union[purge_config.PurgeDocumentsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Permanently deletes all selected - [Document][google.cloud.discoveryengine.v1.Document]s in a - branch. - - This process is asynchronous. Depending on the number of - [Document][google.cloud.discoveryengine.v1.Document]s to be - deleted, this operation can take hours to complete. Before the - delete operation completes, some - [Document][google.cloud.discoveryengine.v1.Document]s might - still be returned by - [DocumentService.GetDocument][google.cloud.discoveryengine.v1.DocumentService.GetDocument] - or - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1.DocumentService.ListDocuments]. - - To get a list of the - [Document][google.cloud.discoveryengine.v1.Document]s to be - deleted, set - [PurgeDocumentsRequest.force][google.cloud.discoveryengine.v1.PurgeDocumentsRequest.force] - to false. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - def sample_purge_documents(): - # Create a client - client = discoveryengine_v1.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.PurgeDocumentsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_documents(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1.types.PurgeDocumentsRequest, dict]): - The request object. Request message for - [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1.DocumentService.PurgeDocuments] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.discoveryengine_v1.types.PurgeDocumentsResponse` Response message for - [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1.DocumentService.PurgeDocuments] - method. If the long running operation is successfully - done, then this message is returned by the - google.longrunning.Operations.response field. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a purge_config.PurgeDocumentsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, purge_config.PurgeDocumentsRequest): - request = purge_config.PurgeDocumentsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.purge_documents] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - purge_config.PurgeDocumentsResponse, - metadata_type=purge_config.PurgeDocumentsMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "DocumentServiceClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - - - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "DocumentServiceClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/pagers.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/pagers.py deleted file mode 100644 index 30cfb52563dc..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.discoveryengine_v1.types import document -from google.cloud.discoveryengine_v1.types import document_service - - -class ListDocumentsPager: - """A pager for iterating through ``list_documents`` requests. - - This class thinly wraps an initial - :class:`google.cloud.discoveryengine_v1.types.ListDocumentsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``documents`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListDocuments`` requests and continue to iterate - through the ``documents`` field on the - corresponding responses. - - All the usual :class:`google.cloud.discoveryengine_v1.types.ListDocumentsResponse` - 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[..., document_service.ListDocumentsResponse], - request: document_service.ListDocumentsRequest, - response: document_service.ListDocumentsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.discoveryengine_v1.types.ListDocumentsRequest): - The initial request object. - response (google.cloud.discoveryengine_v1.types.ListDocumentsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = document_service.ListDocumentsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[document_service.ListDocumentsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[document.Document]: - for page in self.pages: - yield from page.documents - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListDocumentsAsyncPager: - """A pager for iterating through ``list_documents`` requests. - - This class thinly wraps an initial - :class:`google.cloud.discoveryengine_v1.types.ListDocumentsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``documents`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListDocuments`` requests and continue to iterate - through the ``documents`` field on the - corresponding responses. - - All the usual :class:`google.cloud.discoveryengine_v1.types.ListDocumentsResponse` - 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[document_service.ListDocumentsResponse]], - request: document_service.ListDocumentsRequest, - response: document_service.ListDocumentsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.discoveryengine_v1.types.ListDocumentsRequest): - The initial request object. - response (google.cloud.discoveryengine_v1.types.ListDocumentsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = document_service.ListDocumentsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[document_service.ListDocumentsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[document.Document]: - async def async_generator(): - async for page in self.pages: - for response in page.documents: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/__init__.py deleted file mode 100644 index fb08db02f32c..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import DocumentServiceTransport -from .grpc import DocumentServiceGrpcTransport -from .grpc_asyncio import DocumentServiceGrpcAsyncIOTransport -from .rest import DocumentServiceRestTransport -from .rest import DocumentServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[DocumentServiceTransport]] -_transport_registry['grpc'] = DocumentServiceGrpcTransport -_transport_registry['grpc_asyncio'] = DocumentServiceGrpcAsyncIOTransport -_transport_registry['rest'] = DocumentServiceRestTransport - -__all__ = ( - 'DocumentServiceTransport', - 'DocumentServiceGrpcTransport', - 'DocumentServiceGrpcAsyncIOTransport', - 'DocumentServiceRestTransport', - 'DocumentServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/base.py deleted file mode 100644 index b76cf87be59b..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/base.py +++ /dev/null @@ -1,269 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.discoveryengine_v1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.discoveryengine_v1.types import document -from google.cloud.discoveryengine_v1.types import document as gcd_document -from google.cloud.discoveryengine_v1.types import document_service -from google.cloud.discoveryengine_v1.types import import_config -from google.cloud.discoveryengine_v1.types import purge_config -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class DocumentServiceTransport(abc.ABC): - """Abstract transport class for DocumentService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'discoveryengine.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.get_document: gapic_v1.method.wrap_method( - self.get_document, - default_timeout=None, - client_info=client_info, - ), - self.list_documents: gapic_v1.method.wrap_method( - self.list_documents, - default_timeout=None, - client_info=client_info, - ), - self.create_document: gapic_v1.method.wrap_method( - self.create_document, - default_timeout=None, - client_info=client_info, - ), - self.update_document: gapic_v1.method.wrap_method( - self.update_document, - default_timeout=None, - client_info=client_info, - ), - self.delete_document: gapic_v1.method.wrap_method( - self.delete_document, - default_timeout=None, - client_info=client_info, - ), - self.import_documents: gapic_v1.method.wrap_method( - self.import_documents, - default_retry=retries.Retry( -initial=1.0,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=300.0, - ), - default_timeout=300.0, - client_info=client_info, - ), - self.purge_documents: gapic_v1.method.wrap_method( - self.purge_documents, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def get_document(self) -> Callable[ - [document_service.GetDocumentRequest], - Union[ - document.Document, - Awaitable[document.Document] - ]]: - raise NotImplementedError() - - @property - def list_documents(self) -> Callable[ - [document_service.ListDocumentsRequest], - Union[ - document_service.ListDocumentsResponse, - Awaitable[document_service.ListDocumentsResponse] - ]]: - raise NotImplementedError() - - @property - def create_document(self) -> Callable[ - [document_service.CreateDocumentRequest], - Union[ - gcd_document.Document, - Awaitable[gcd_document.Document] - ]]: - raise NotImplementedError() - - @property - def update_document(self) -> Callable[ - [document_service.UpdateDocumentRequest], - Union[ - document.Document, - Awaitable[document.Document] - ]]: - raise NotImplementedError() - - @property - def delete_document(self) -> Callable[ - [document_service.DeleteDocumentRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def import_documents(self) -> Callable[ - [import_config.ImportDocumentsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def purge_documents(self) -> Callable[ - [purge_config.PurgeDocumentsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'DocumentServiceTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/grpc.py deleted file mode 100644 index 663a4cea7b26..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/grpc.py +++ /dev/null @@ -1,509 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.discoveryengine_v1.types import document -from google.cloud.discoveryengine_v1.types import document as gcd_document -from google.cloud.discoveryengine_v1.types import document_service -from google.cloud.discoveryengine_v1.types import import_config -from google.cloud.discoveryengine_v1.types import purge_config -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import DocumentServiceTransport, DEFAULT_CLIENT_INFO - - -class DocumentServiceGrpcTransport(DocumentServiceTransport): - """gRPC backend transport for DocumentService. - - Service for ingesting - [Document][google.cloud.discoveryengine.v1.Document] information of - the customer's website. - - 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def get_document(self) -> Callable[ - [document_service.GetDocumentRequest], - document.Document]: - r"""Return a callable for the get document method over gRPC. - - Gets a [Document][google.cloud.discoveryengine.v1.Document]. - - Returns: - Callable[[~.GetDocumentRequest], - ~.Document]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_document' not in self._stubs: - self._stubs['get_document'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.DocumentService/GetDocument', - request_serializer=document_service.GetDocumentRequest.serialize, - response_deserializer=document.Document.deserialize, - ) - return self._stubs['get_document'] - - @property - def list_documents(self) -> Callable[ - [document_service.ListDocumentsRequest], - document_service.ListDocumentsResponse]: - r"""Return a callable for the list documents method over gRPC. - - Gets a list of - [Document][google.cloud.discoveryengine.v1.Document]s. - - Returns: - Callable[[~.ListDocumentsRequest], - ~.ListDocumentsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_documents' not in self._stubs: - self._stubs['list_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.DocumentService/ListDocuments', - request_serializer=document_service.ListDocumentsRequest.serialize, - response_deserializer=document_service.ListDocumentsResponse.deserialize, - ) - return self._stubs['list_documents'] - - @property - def create_document(self) -> Callable[ - [document_service.CreateDocumentRequest], - gcd_document.Document]: - r"""Return a callable for the create document method over gRPC. - - Creates a [Document][google.cloud.discoveryengine.v1.Document]. - - Returns: - Callable[[~.CreateDocumentRequest], - ~.Document]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_document' not in self._stubs: - self._stubs['create_document'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.DocumentService/CreateDocument', - request_serializer=document_service.CreateDocumentRequest.serialize, - response_deserializer=gcd_document.Document.deserialize, - ) - return self._stubs['create_document'] - - @property - def update_document(self) -> Callable[ - [document_service.UpdateDocumentRequest], - document.Document]: - r"""Return a callable for the update document method over gRPC. - - Updates a [Document][google.cloud.discoveryengine.v1.Document]. - - Returns: - Callable[[~.UpdateDocumentRequest], - ~.Document]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_document' not in self._stubs: - self._stubs['update_document'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.DocumentService/UpdateDocument', - request_serializer=document_service.UpdateDocumentRequest.serialize, - response_deserializer=document.Document.deserialize, - ) - return self._stubs['update_document'] - - @property - def delete_document(self) -> Callable[ - [document_service.DeleteDocumentRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete document method over gRPC. - - Deletes a [Document][google.cloud.discoveryengine.v1.Document]. - - Returns: - Callable[[~.DeleteDocumentRequest], - ~.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_document' not in self._stubs: - self._stubs['delete_document'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.DocumentService/DeleteDocument', - request_serializer=document_service.DeleteDocumentRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_document'] - - @property - def import_documents(self) -> Callable[ - [import_config.ImportDocumentsRequest], - operations_pb2.Operation]: - r"""Return a callable for the import documents method over gRPC. - - Bulk import of multiple - [Document][google.cloud.discoveryengine.v1.Document]s. Request - processing may be synchronous. Non-existing items will be - created. - - Note: It is possible for a subset of the - [Document][google.cloud.discoveryengine.v1.Document]s to be - successfully updated. - - Returns: - Callable[[~.ImportDocumentsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_documents' not in self._stubs: - self._stubs['import_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.DocumentService/ImportDocuments', - request_serializer=import_config.ImportDocumentsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_documents'] - - @property - def purge_documents(self) -> Callable[ - [purge_config.PurgeDocumentsRequest], - operations_pb2.Operation]: - r"""Return a callable for the purge documents method over gRPC. - - Permanently deletes all selected - [Document][google.cloud.discoveryengine.v1.Document]s in a - branch. - - This process is asynchronous. Depending on the number of - [Document][google.cloud.discoveryengine.v1.Document]s to be - deleted, this operation can take hours to complete. Before the - delete operation completes, some - [Document][google.cloud.discoveryengine.v1.Document]s might - still be returned by - [DocumentService.GetDocument][google.cloud.discoveryengine.v1.DocumentService.GetDocument] - or - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1.DocumentService.ListDocuments]. - - To get a list of the - [Document][google.cloud.discoveryengine.v1.Document]s to be - deleted, set - [PurgeDocumentsRequest.force][google.cloud.discoveryengine.v1.PurgeDocumentsRequest.force] - to false. - - Returns: - Callable[[~.PurgeDocumentsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'purge_documents' not in self._stubs: - self._stubs['purge_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.DocumentService/PurgeDocuments', - request_serializer=purge_config.PurgeDocumentsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['purge_documents'] - - def close(self): - self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'DocumentServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/grpc_asyncio.py deleted file mode 100644 index 1b2e3e1c587d..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,508 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.discoveryengine_v1.types import document -from google.cloud.discoveryengine_v1.types import document as gcd_document -from google.cloud.discoveryengine_v1.types import document_service -from google.cloud.discoveryengine_v1.types import import_config -from google.cloud.discoveryengine_v1.types import purge_config -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import DocumentServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import DocumentServiceGrpcTransport - - -class DocumentServiceGrpcAsyncIOTransport(DocumentServiceTransport): - """gRPC AsyncIO backend transport for DocumentService. - - Service for ingesting - [Document][google.cloud.discoveryengine.v1.Document] information of - the customer's website. - - 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def get_document(self) -> Callable[ - [document_service.GetDocumentRequest], - Awaitable[document.Document]]: - r"""Return a callable for the get document method over gRPC. - - Gets a [Document][google.cloud.discoveryengine.v1.Document]. - - Returns: - Callable[[~.GetDocumentRequest], - Awaitable[~.Document]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_document' not in self._stubs: - self._stubs['get_document'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.DocumentService/GetDocument', - request_serializer=document_service.GetDocumentRequest.serialize, - response_deserializer=document.Document.deserialize, - ) - return self._stubs['get_document'] - - @property - def list_documents(self) -> Callable[ - [document_service.ListDocumentsRequest], - Awaitable[document_service.ListDocumentsResponse]]: - r"""Return a callable for the list documents method over gRPC. - - Gets a list of - [Document][google.cloud.discoveryengine.v1.Document]s. - - Returns: - Callable[[~.ListDocumentsRequest], - Awaitable[~.ListDocumentsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_documents' not in self._stubs: - self._stubs['list_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.DocumentService/ListDocuments', - request_serializer=document_service.ListDocumentsRequest.serialize, - response_deserializer=document_service.ListDocumentsResponse.deserialize, - ) - return self._stubs['list_documents'] - - @property - def create_document(self) -> Callable[ - [document_service.CreateDocumentRequest], - Awaitable[gcd_document.Document]]: - r"""Return a callable for the create document method over gRPC. - - Creates a [Document][google.cloud.discoveryengine.v1.Document]. - - Returns: - Callable[[~.CreateDocumentRequest], - Awaitable[~.Document]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_document' not in self._stubs: - self._stubs['create_document'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.DocumentService/CreateDocument', - request_serializer=document_service.CreateDocumentRequest.serialize, - response_deserializer=gcd_document.Document.deserialize, - ) - return self._stubs['create_document'] - - @property - def update_document(self) -> Callable[ - [document_service.UpdateDocumentRequest], - Awaitable[document.Document]]: - r"""Return a callable for the update document method over gRPC. - - Updates a [Document][google.cloud.discoveryengine.v1.Document]. - - Returns: - Callable[[~.UpdateDocumentRequest], - Awaitable[~.Document]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_document' not in self._stubs: - self._stubs['update_document'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.DocumentService/UpdateDocument', - request_serializer=document_service.UpdateDocumentRequest.serialize, - response_deserializer=document.Document.deserialize, - ) - return self._stubs['update_document'] - - @property - def delete_document(self) -> Callable[ - [document_service.DeleteDocumentRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete document method over gRPC. - - Deletes a [Document][google.cloud.discoveryengine.v1.Document]. - - Returns: - Callable[[~.DeleteDocumentRequest], - 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_document' not in self._stubs: - self._stubs['delete_document'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.DocumentService/DeleteDocument', - request_serializer=document_service.DeleteDocumentRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_document'] - - @property - def import_documents(self) -> Callable[ - [import_config.ImportDocumentsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import documents method over gRPC. - - Bulk import of multiple - [Document][google.cloud.discoveryengine.v1.Document]s. Request - processing may be synchronous. Non-existing items will be - created. - - Note: It is possible for a subset of the - [Document][google.cloud.discoveryengine.v1.Document]s to be - successfully updated. - - Returns: - Callable[[~.ImportDocumentsRequest], - 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 'import_documents' not in self._stubs: - self._stubs['import_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.DocumentService/ImportDocuments', - request_serializer=import_config.ImportDocumentsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_documents'] - - @property - def purge_documents(self) -> Callable[ - [purge_config.PurgeDocumentsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the purge documents method over gRPC. - - Permanently deletes all selected - [Document][google.cloud.discoveryengine.v1.Document]s in a - branch. - - This process is asynchronous. Depending on the number of - [Document][google.cloud.discoveryengine.v1.Document]s to be - deleted, this operation can take hours to complete. Before the - delete operation completes, some - [Document][google.cloud.discoveryengine.v1.Document]s might - still be returned by - [DocumentService.GetDocument][google.cloud.discoveryengine.v1.DocumentService.GetDocument] - or - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1.DocumentService.ListDocuments]. - - To get a list of the - [Document][google.cloud.discoveryengine.v1.Document]s to be - deleted, set - [PurgeDocumentsRequest.force][google.cloud.discoveryengine.v1.PurgeDocumentsRequest.force] - to false. - - Returns: - Callable[[~.PurgeDocumentsRequest], - 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 'purge_documents' not in self._stubs: - self._stubs['purge_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.DocumentService/PurgeDocuments', - request_serializer=purge_config.PurgeDocumentsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['purge_documents'] - - def close(self): - return self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - -__all__ = ( - 'DocumentServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/rest.py deleted file mode 100644 index 737f83b24002..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/document_service/transports/rest.py +++ /dev/null @@ -1,1445 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.cloud.location import locations_pb2 # type: ignore -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.discoveryengine_v1.types import document -from google.cloud.discoveryengine_v1.types import document as gcd_document -from google.cloud.discoveryengine_v1.types import document_service -from google.cloud.discoveryengine_v1.types import import_config -from google.cloud.discoveryengine_v1.types import purge_config -from google.protobuf import empty_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from .base import DocumentServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class DocumentServiceRestInterceptor: - """Interceptor for DocumentService. - - 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 DocumentServiceRestTransport. - - .. code-block:: python - class MyCustomDocumentServiceInterceptor(DocumentServiceRestInterceptor): - def pre_create_document(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_document(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_document(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_document(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_document(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_import_documents(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_import_documents(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_documents(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_documents(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_purge_documents(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_purge_documents(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_document(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_document(self, response): - logging.log(f"Received response: {response}") - return response - - transport = DocumentServiceRestTransport(interceptor=MyCustomDocumentServiceInterceptor()) - client = DocumentServiceClient(transport=transport) - - - """ - def pre_create_document(self, request: document_service.CreateDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_service.CreateDocumentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_document - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService server. - """ - return request, metadata - - def post_create_document(self, response: gcd_document.Document) -> gcd_document.Document: - """Post-rpc interceptor for create_document - - Override in a subclass to manipulate the response - after it is returned by the DocumentService server but before - it is returned to user code. - """ - return response - def pre_delete_document(self, request: document_service.DeleteDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_service.DeleteDocumentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_document - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService server. - """ - return request, metadata - - def pre_get_document(self, request: document_service.GetDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_service.GetDocumentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_document - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService server. - """ - return request, metadata - - def post_get_document(self, response: document.Document) -> document.Document: - """Post-rpc interceptor for get_document - - Override in a subclass to manipulate the response - after it is returned by the DocumentService server but before - it is returned to user code. - """ - return response - def pre_import_documents(self, request: import_config.ImportDocumentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[import_config.ImportDocumentsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for import_documents - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService server. - """ - return request, metadata - - def post_import_documents(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for import_documents - - Override in a subclass to manipulate the response - after it is returned by the DocumentService server but before - it is returned to user code. - """ - return response - def pre_list_documents(self, request: document_service.ListDocumentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_service.ListDocumentsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_documents - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService server. - """ - return request, metadata - - def post_list_documents(self, response: document_service.ListDocumentsResponse) -> document_service.ListDocumentsResponse: - """Post-rpc interceptor for list_documents - - Override in a subclass to manipulate the response - after it is returned by the DocumentService server but before - it is returned to user code. - """ - return response - def pre_purge_documents(self, request: purge_config.PurgeDocumentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[purge_config.PurgeDocumentsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for purge_documents - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService server. - """ - return request, metadata - - def post_purge_documents(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for purge_documents - - Override in a subclass to manipulate the response - after it is returned by the DocumentService server but before - it is returned to user code. - """ - return response - def pre_update_document(self, request: document_service.UpdateDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_service.UpdateDocumentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_document - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService server. - """ - return request, metadata - - def post_update_document(self, response: document.Document) -> document.Document: - """Post-rpc interceptor for update_document - - Override in a subclass to manipulate the response - after it is returned by the DocumentService server but before - it is returned to user code. - """ - return response - - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService 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 DocumentService server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService 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 DocumentService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class DocumentServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: DocumentServiceRestInterceptor - - -class DocumentServiceRestTransport(DocumentServiceTransport): - """REST backend transport for DocumentService. - - Service for ingesting - [Document][google.cloud.discoveryengine.v1.Document] information of - the customer's website. - - 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 = 'discoveryengine.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[DocumentServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or DocumentServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1/{name=projects/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/engines/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/models/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*}/operations', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _CreateDocument(DocumentServiceRestStub): - def __hash__(self): - return hash("CreateDocument") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "documentId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_service.CreateDocumentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_document.Document: - r"""Call the create document method over HTTP. - - Args: - request (~.document_service.CreateDocumentRequest): - The request object. Request message for - [DocumentService.CreateDocument][google.cloud.discoveryengine.v1.DocumentService.CreateDocument] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcd_document.Document: - Document captures all raw metadata - information of items to be recommended - or searched. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/dataStores/*/branches/*}/documents', - 'body': 'document', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/collections/*/dataStores/*/branches/*}/documents', - 'body': 'document', - }, - ] - request, metadata = self._interceptor.pre_create_document(request, metadata) - pb_request = document_service.CreateDocumentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_document.Document() - pb_resp = gcd_document.Document.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_document(resp) - return resp - - class _DeleteDocument(DocumentServiceRestStub): - def __hash__(self): - return hash("DeleteDocument") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_service.DeleteDocumentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete document method over HTTP. - - Args: - request (~.document_service.DeleteDocumentRequest): - The request object. Request message for - [DocumentService.DeleteDocument][google.cloud.discoveryengine.v1.DocumentService.DeleteDocument] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*/documents/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/documents/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_document(request, metadata) - pb_request = document_service.DeleteDocumentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _GetDocument(DocumentServiceRestStub): - def __hash__(self): - return hash("GetDocument") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_service.GetDocumentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document.Document: - r"""Call the get document method over HTTP. - - Args: - request (~.document_service.GetDocumentRequest): - The request object. Request message for - [DocumentService.GetDocument][google.cloud.discoveryengine.v1.DocumentService.GetDocument] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.document.Document: - Document captures all raw metadata - information of items to be recommended - or searched. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*/documents/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/documents/*}', - }, - ] - request, metadata = self._interceptor.pre_get_document(request, metadata) - pb_request = document_service.GetDocumentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document.Document() - pb_resp = document.Document.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_document(resp) - return resp - - class _ImportDocuments(DocumentServiceRestStub): - def __hash__(self): - return hash("ImportDocuments") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: import_config.ImportDocumentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the import documents method over HTTP. - - Args: - request (~.import_config.ImportDocumentsRequest): - The request object. Request message for Import methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/dataStores/*/branches/*}/documents:import', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/collections/*/dataStores/*/branches/*}/documents:import', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_import_documents(request, metadata) - pb_request = import_config.ImportDocumentsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_import_documents(resp) - return resp - - class _ListDocuments(DocumentServiceRestStub): - def __hash__(self): - return hash("ListDocuments") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_service.ListDocumentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document_service.ListDocumentsResponse: - r"""Call the list documents method over HTTP. - - Args: - request (~.document_service.ListDocumentsRequest): - The request object. Request message for - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1.DocumentService.ListDocuments] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.document_service.ListDocumentsResponse: - Response message for - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1.DocumentService.ListDocuments] - method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/dataStores/*/branches/*}/documents', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/collections/*/dataStores/*/branches/*}/documents', - }, - ] - request, metadata = self._interceptor.pre_list_documents(request, metadata) - pb_request = document_service.ListDocumentsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document_service.ListDocumentsResponse() - pb_resp = document_service.ListDocumentsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_documents(resp) - return resp - - class _PurgeDocuments(DocumentServiceRestStub): - def __hash__(self): - return hash("PurgeDocuments") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: purge_config.PurgeDocumentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the purge documents method over HTTP. - - Args: - request (~.purge_config.PurgeDocumentsRequest): - The request object. Request message for - [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1.DocumentService.PurgeDocuments] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/dataStores/*/branches/*}/documents:purge', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/collections/*/dataStores/*/branches/*}/documents:purge', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_purge_documents(request, metadata) - pb_request = purge_config.PurgeDocumentsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_purge_documents(resp) - return resp - - class _UpdateDocument(DocumentServiceRestStub): - def __hash__(self): - return hash("UpdateDocument") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_service.UpdateDocumentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document.Document: - r"""Call the update document method over HTTP. - - Args: - request (~.document_service.UpdateDocumentRequest): - The request object. Request message for - [DocumentService.UpdateDocument][google.cloud.discoveryengine.v1.DocumentService.UpdateDocument] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.document.Document: - Document captures all raw metadata - information of items to be recommended - or searched. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{document.name=projects/*/locations/*/dataStores/*/branches/*/documents/*}', - 'body': 'document', - }, -{ - 'method': 'patch', - 'uri': '/v1/{document.name=projects/*/locations/*/collections/*/dataStores/*/branches/*/documents/*}', - 'body': 'document', - }, - ] - request, metadata = self._interceptor.pre_update_document(request, metadata) - pb_request = document_service.UpdateDocumentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document.Document() - pb_resp = document.Document.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_document(resp) - return resp - - @property - def create_document(self) -> Callable[ - [document_service.CreateDocumentRequest], - gcd_document.Document]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateDocument(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_document(self) -> Callable[ - [document_service.DeleteDocumentRequest], - 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._DeleteDocument(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_document(self) -> Callable[ - [document_service.GetDocumentRequest], - document.Document]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetDocument(self._session, self._host, self._interceptor) # type: ignore - - @property - def import_documents(self) -> Callable[ - [import_config.ImportDocumentsRequest], - 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._ImportDocuments(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_documents(self) -> Callable[ - [document_service.ListDocumentsRequest], - document_service.ListDocumentsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListDocuments(self._session, self._host, self._interceptor) # type: ignore - - @property - def purge_documents(self) -> Callable[ - [purge_config.PurgeDocumentsRequest], - 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._PurgeDocuments(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_document(self) -> Callable[ - [document_service.UpdateDocumentRequest], - document.Document]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateDocument(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(DocumentServiceRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(DocumentServiceRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/engines/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'DocumentServiceRestTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/__init__.py deleted file mode 100644 index 4e9455a921b6..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import SchemaServiceClient -from .async_client import SchemaServiceAsyncClient - -__all__ = ( - 'SchemaServiceClient', - 'SchemaServiceAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/async_client.py deleted file mode 100644 index f26e342d36dc..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/async_client.py +++ /dev/null @@ -1,902 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.discoveryengine_v1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.discoveryengine_v1.services.schema_service import pagers -from google.cloud.discoveryengine_v1.types import schema -from google.cloud.discoveryengine_v1.types import schema as gcd_schema -from google.cloud.discoveryengine_v1.types import schema_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from .transports.base import SchemaServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import SchemaServiceGrpcAsyncIOTransport -from .client import SchemaServiceClient - - -class SchemaServiceAsyncClient: - """Service for managing - [Schema][google.cloud.discoveryengine.v1.Schema]s. - """ - - _client: SchemaServiceClient - - DEFAULT_ENDPOINT = SchemaServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SchemaServiceClient.DEFAULT_MTLS_ENDPOINT - - data_store_path = staticmethod(SchemaServiceClient.data_store_path) - parse_data_store_path = staticmethod(SchemaServiceClient.parse_data_store_path) - schema_path = staticmethod(SchemaServiceClient.schema_path) - parse_schema_path = staticmethod(SchemaServiceClient.parse_schema_path) - common_billing_account_path = staticmethod(SchemaServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(SchemaServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(SchemaServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(SchemaServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(SchemaServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(SchemaServiceClient.parse_common_organization_path) - common_project_path = staticmethod(SchemaServiceClient.common_project_path) - parse_common_project_path = staticmethod(SchemaServiceClient.parse_common_project_path) - common_location_path = staticmethod(SchemaServiceClient.common_location_path) - parse_common_location_path = staticmethod(SchemaServiceClient.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: - SchemaServiceAsyncClient: The constructed client. - """ - return SchemaServiceClient.from_service_account_info.__func__(SchemaServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SchemaServiceAsyncClient: The constructed client. - """ - return SchemaServiceClient.from_service_account_file.__func__(SchemaServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return SchemaServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> SchemaServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SchemaServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(SchemaServiceClient).get_transport_class, type(SchemaServiceClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, SchemaServiceTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the schema 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 (Union[str, ~.SchemaServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = SchemaServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def get_schema(self, - request: Optional[Union[schema_service.GetSchemaRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> schema.Schema: - r"""Gets a [Schema][google.cloud.discoveryengine.v1.Schema]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - async def sample_get_schema(): - # Create a client - client = discoveryengine_v1.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.GetSchemaRequest( - name="name_value", - ) - - # Make the request - response = await client.get_schema(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1.types.GetSchemaRequest, dict]]): - The request object. Request message for - [SchemaService.GetSchema][google.cloud.discoveryengine.v1.SchemaService.GetSchema] - method. - name (:class:`str`): - Required. The full resource name of the schema, in the - format of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1.types.Schema: - Defines the structure and layout of a - type of document data. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = schema_service.GetSchemaRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_schema, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_schemas(self, - request: Optional[Union[schema_service.ListSchemasRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSchemasAsyncPager: - r"""Gets a list of - [Schema][google.cloud.discoveryengine.v1.Schema]s. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - async def sample_list_schemas(): - # Create a client - client = discoveryengine_v1.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.ListSchemasRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_schemas(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1.types.ListSchemasRequest, dict]]): - The request object. Request message for - [SchemaService.ListSchemas][google.cloud.discoveryengine.v1.SchemaService.ListSchemas] - method. - parent (:class:`str`): - Required. The parent data store resource name, in the - format of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1.services.schema_service.pagers.ListSchemasAsyncPager: - Response message for - [SchemaService.ListSchemas][google.cloud.discoveryengine.v1.SchemaService.ListSchemas] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = schema_service.ListSchemasRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_schemas, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListSchemasAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_schema(self, - request: Optional[Union[schema_service.CreateSchemaRequest, dict]] = None, - *, - parent: Optional[str] = None, - schema: Optional[gcd_schema.Schema] = None, - schema_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a [Schema][google.cloud.discoveryengine.v1.Schema]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - async def sample_create_schema(): - # Create a client - client = discoveryengine_v1.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.CreateSchemaRequest( - parent="parent_value", - schema_id="schema_id_value", - ) - - # Make the request - operation = client.create_schema(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1.types.CreateSchemaRequest, dict]]): - The request object. Request message for - [SchemaService.CreateSchema][google.cloud.discoveryengine.v1.SchemaService.CreateSchema] - method. - parent (:class:`str`): - Required. The parent data store resource name, in the - format of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - schema (:class:`google.cloud.discoveryengine_v1.types.Schema`): - Required. The - [Schema][google.cloud.discoveryengine.v1.Schema] to - create. - - This corresponds to the ``schema`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - schema_id (:class:`str`): - Required. The ID to use for the - [Schema][google.cloud.discoveryengine.v1.Schema], which - will become the final component of the - [Schema.name][google.cloud.discoveryengine.v1.Schema.name]. - - This field should conform to - `RFC-1034 `__ - standard with a length limit of 63 characters. - - This corresponds to the ``schema_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.discoveryengine_v1.types.Schema` - Defines the structure and layout of a type of document - data. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, schema, schema_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = schema_service.CreateSchemaRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if schema is not None: - request.schema = schema - if schema_id is not None: - request.schema_id = schema_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_schema, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - gcd_schema.Schema, - metadata_type=schema_service.CreateSchemaMetadata, - ) - - # Done; return the response. - return response - - async def update_schema(self, - request: Optional[Union[schema_service.UpdateSchemaRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates a [Schema][google.cloud.discoveryengine.v1.Schema]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - async def sample_update_schema(): - # Create a client - client = discoveryengine_v1.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.UpdateSchemaRequest( - ) - - # Make the request - operation = client.update_schema(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1.types.UpdateSchemaRequest, dict]]): - The request object. Request message for - [SchemaService.UpdateSchema][google.cloud.discoveryengine.v1.SchemaService.UpdateSchema] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.discoveryengine_v1.types.Schema` - Defines the structure and layout of a type of document - data. - - """ - # Create or coerce a protobuf request object. - request = schema_service.UpdateSchemaRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_schema, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("schema.name", request.schema.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - schema.Schema, - metadata_type=schema_service.UpdateSchemaMetadata, - ) - - # Done; return the response. - return response - - async def delete_schema(self, - request: Optional[Union[schema_service.DeleteSchemaRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a [Schema][google.cloud.discoveryengine.v1.Schema]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - async def sample_delete_schema(): - # Create a client - client = discoveryengine_v1.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.DeleteSchemaRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_schema(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1.types.DeleteSchemaRequest, dict]]): - The request object. Request message for - [SchemaService.DeleteSchema][google.cloud.discoveryengine.v1.SchemaService.DeleteSchema] - method. - name (:class:`str`): - Required. The full resource name of the schema, in the - format of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = schema_service.DeleteSchemaRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_schema, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=schema_service.DeleteSchemaMetadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "SchemaServiceAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "SchemaServiceAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/client.py deleted file mode 100644 index 3a41eac1ffc0..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/client.py +++ /dev/null @@ -1,1119 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.discoveryengine_v1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.discoveryengine_v1.services.schema_service import pagers -from google.cloud.discoveryengine_v1.types import schema -from google.cloud.discoveryengine_v1.types import schema as gcd_schema -from google.cloud.discoveryengine_v1.types import schema_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from .transports.base import SchemaServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SchemaServiceGrpcTransport -from .transports.grpc_asyncio import SchemaServiceGrpcAsyncIOTransport -from .transports.rest import SchemaServiceRestTransport - - -class SchemaServiceClientMeta(type): - """Metaclass for the SchemaService 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[SchemaServiceTransport]] - _transport_registry["grpc"] = SchemaServiceGrpcTransport - _transport_registry["grpc_asyncio"] = SchemaServiceGrpcAsyncIOTransport - _transport_registry["rest"] = SchemaServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[SchemaServiceTransport]: - """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 SchemaServiceClient(metaclass=SchemaServiceClientMeta): - """Service for managing - [Schema][google.cloud.discoveryengine.v1.Schema]s. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SchemaServiceClient: 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: - SchemaServiceClient: 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) -> SchemaServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SchemaServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def data_store_path(project: str,location: str,data_store: str,) -> str: - """Returns a fully-qualified data_store string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) - - @staticmethod - def parse_data_store_path(path: str) -> Dict[str,str]: - """Parses a data_store path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def schema_path(project: str,location: str,data_store: str,schema: str,) -> str: - """Returns a fully-qualified schema string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}/schemas/{schema}".format(project=project, location=location, data_store=data_store, schema=schema, ) - - @staticmethod - def parse_schema_path(path: str) -> Dict[str,str]: - """Parses a schema path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/schemas/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, SchemaServiceTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the schema 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 (Union[str, SchemaServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, SchemaServiceTransport): - # transport is a SchemaServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def get_schema(self, - request: Optional[Union[schema_service.GetSchemaRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> schema.Schema: - r"""Gets a [Schema][google.cloud.discoveryengine.v1.Schema]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - def sample_get_schema(): - # Create a client - client = discoveryengine_v1.SchemaServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.GetSchemaRequest( - name="name_value", - ) - - # Make the request - response = client.get_schema(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1.types.GetSchemaRequest, dict]): - The request object. Request message for - [SchemaService.GetSchema][google.cloud.discoveryengine.v1.SchemaService.GetSchema] - method. - name (str): - Required. The full resource name of the schema, in the - format of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1.types.Schema: - Defines the structure and layout of a - type of document data. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a schema_service.GetSchemaRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, schema_service.GetSchemaRequest): - request = schema_service.GetSchemaRequest(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_schema] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_schemas(self, - request: Optional[Union[schema_service.ListSchemasRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSchemasPager: - r"""Gets a list of - [Schema][google.cloud.discoveryengine.v1.Schema]s. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - def sample_list_schemas(): - # Create a client - client = discoveryengine_v1.SchemaServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.ListSchemasRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_schemas(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1.types.ListSchemasRequest, dict]): - The request object. Request message for - [SchemaService.ListSchemas][google.cloud.discoveryengine.v1.SchemaService.ListSchemas] - method. - parent (str): - Required. The parent data store resource name, in the - format of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1.services.schema_service.pagers.ListSchemasPager: - Response message for - [SchemaService.ListSchemas][google.cloud.discoveryengine.v1.SchemaService.ListSchemas] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a schema_service.ListSchemasRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, schema_service.ListSchemasRequest): - request = schema_service.ListSchemasRequest(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_schemas] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListSchemasPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_schema(self, - request: Optional[Union[schema_service.CreateSchemaRequest, dict]] = None, - *, - parent: Optional[str] = None, - schema: Optional[gcd_schema.Schema] = None, - schema_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a [Schema][google.cloud.discoveryengine.v1.Schema]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - def sample_create_schema(): - # Create a client - client = discoveryengine_v1.SchemaServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.CreateSchemaRequest( - parent="parent_value", - schema_id="schema_id_value", - ) - - # Make the request - operation = client.create_schema(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1.types.CreateSchemaRequest, dict]): - The request object. Request message for - [SchemaService.CreateSchema][google.cloud.discoveryengine.v1.SchemaService.CreateSchema] - method. - parent (str): - Required. The parent data store resource name, in the - format of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - schema (google.cloud.discoveryengine_v1.types.Schema): - Required. The - [Schema][google.cloud.discoveryengine.v1.Schema] to - create. - - This corresponds to the ``schema`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - schema_id (str): - Required. The ID to use for the - [Schema][google.cloud.discoveryengine.v1.Schema], which - will become the final component of the - [Schema.name][google.cloud.discoveryengine.v1.Schema.name]. - - This field should conform to - `RFC-1034 `__ - standard with a length limit of 63 characters. - - This corresponds to the ``schema_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.discoveryengine_v1.types.Schema` - Defines the structure and layout of a type of document - data. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, schema, schema_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a schema_service.CreateSchemaRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, schema_service.CreateSchemaRequest): - request = schema_service.CreateSchemaRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if schema is not None: - request.schema = schema - if schema_id is not None: - request.schema_id = schema_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_schema] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - gcd_schema.Schema, - metadata_type=schema_service.CreateSchemaMetadata, - ) - - # Done; return the response. - return response - - def update_schema(self, - request: Optional[Union[schema_service.UpdateSchemaRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates a [Schema][google.cloud.discoveryengine.v1.Schema]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - def sample_update_schema(): - # Create a client - client = discoveryengine_v1.SchemaServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.UpdateSchemaRequest( - ) - - # Make the request - operation = client.update_schema(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1.types.UpdateSchemaRequest, dict]): - The request object. Request message for - [SchemaService.UpdateSchema][google.cloud.discoveryengine.v1.SchemaService.UpdateSchema] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.discoveryengine_v1.types.Schema` - Defines the structure and layout of a type of document - data. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a schema_service.UpdateSchemaRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, schema_service.UpdateSchemaRequest): - request = schema_service.UpdateSchemaRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_schema] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("schema.name", request.schema.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - schema.Schema, - metadata_type=schema_service.UpdateSchemaMetadata, - ) - - # Done; return the response. - return response - - def delete_schema(self, - request: Optional[Union[schema_service.DeleteSchemaRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes a [Schema][google.cloud.discoveryengine.v1.Schema]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - def sample_delete_schema(): - # Create a client - client = discoveryengine_v1.SchemaServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.DeleteSchemaRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_schema(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1.types.DeleteSchemaRequest, dict]): - The request object. Request message for - [SchemaService.DeleteSchema][google.cloud.discoveryengine.v1.SchemaService.DeleteSchema] - method. - name (str): - Required. The full resource name of the schema, in the - format of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a schema_service.DeleteSchemaRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, schema_service.DeleteSchemaRequest): - request = schema_service.DeleteSchemaRequest(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_schema] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=schema_service.DeleteSchemaMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "SchemaServiceClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - - - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "SchemaServiceClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/pagers.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/pagers.py deleted file mode 100644 index 72fef28d4880..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.discoveryengine_v1.types import schema -from google.cloud.discoveryengine_v1.types import schema_service - - -class ListSchemasPager: - """A pager for iterating through ``list_schemas`` requests. - - This class thinly wraps an initial - :class:`google.cloud.discoveryengine_v1.types.ListSchemasResponse` object, and - provides an ``__iter__`` method to iterate through its - ``schemas`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListSchemas`` requests and continue to iterate - through the ``schemas`` field on the - corresponding responses. - - All the usual :class:`google.cloud.discoveryengine_v1.types.ListSchemasResponse` - 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[..., schema_service.ListSchemasResponse], - request: schema_service.ListSchemasRequest, - response: schema_service.ListSchemasResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.discoveryengine_v1.types.ListSchemasRequest): - The initial request object. - response (google.cloud.discoveryengine_v1.types.ListSchemasResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = schema_service.ListSchemasRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[schema_service.ListSchemasResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[schema.Schema]: - for page in self.pages: - yield from page.schemas - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSchemasAsyncPager: - """A pager for iterating through ``list_schemas`` requests. - - This class thinly wraps an initial - :class:`google.cloud.discoveryengine_v1.types.ListSchemasResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``schemas`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListSchemas`` requests and continue to iterate - through the ``schemas`` field on the - corresponding responses. - - All the usual :class:`google.cloud.discoveryengine_v1.types.ListSchemasResponse` - 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[schema_service.ListSchemasResponse]], - request: schema_service.ListSchemasRequest, - response: schema_service.ListSchemasResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.discoveryengine_v1.types.ListSchemasRequest): - The initial request object. - response (google.cloud.discoveryengine_v1.types.ListSchemasResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = schema_service.ListSchemasRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[schema_service.ListSchemasResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[schema.Schema]: - async def async_generator(): - async for page in self.pages: - for response in page.schemas: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/__init__.py deleted file mode 100644 index d5ebd14e657b..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import SchemaServiceTransport -from .grpc import SchemaServiceGrpcTransport -from .grpc_asyncio import SchemaServiceGrpcAsyncIOTransport -from .rest import SchemaServiceRestTransport -from .rest import SchemaServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SchemaServiceTransport]] -_transport_registry['grpc'] = SchemaServiceGrpcTransport -_transport_registry['grpc_asyncio'] = SchemaServiceGrpcAsyncIOTransport -_transport_registry['rest'] = SchemaServiceRestTransport - -__all__ = ( - 'SchemaServiceTransport', - 'SchemaServiceGrpcTransport', - 'SchemaServiceGrpcAsyncIOTransport', - 'SchemaServiceRestTransport', - 'SchemaServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/base.py deleted file mode 100644 index 5a729d24911c..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/base.py +++ /dev/null @@ -1,231 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.discoveryengine_v1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.discoveryengine_v1.types import schema -from google.cloud.discoveryengine_v1.types import schema_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class SchemaServiceTransport(abc.ABC): - """Abstract transport class for SchemaService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'discoveryengine.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.get_schema: gapic_v1.method.wrap_method( - self.get_schema, - default_timeout=None, - client_info=client_info, - ), - self.list_schemas: gapic_v1.method.wrap_method( - self.list_schemas, - default_timeout=None, - client_info=client_info, - ), - self.create_schema: gapic_v1.method.wrap_method( - self.create_schema, - default_timeout=None, - client_info=client_info, - ), - self.update_schema: gapic_v1.method.wrap_method( - self.update_schema, - default_timeout=None, - client_info=client_info, - ), - self.delete_schema: gapic_v1.method.wrap_method( - self.delete_schema, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def get_schema(self) -> Callable[ - [schema_service.GetSchemaRequest], - Union[ - schema.Schema, - Awaitable[schema.Schema] - ]]: - raise NotImplementedError() - - @property - def list_schemas(self) -> Callable[ - [schema_service.ListSchemasRequest], - Union[ - schema_service.ListSchemasResponse, - Awaitable[schema_service.ListSchemasResponse] - ]]: - raise NotImplementedError() - - @property - def create_schema(self) -> Callable[ - [schema_service.CreateSchemaRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_schema(self) -> Callable[ - [schema_service.UpdateSchemaRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_schema(self) -> Callable[ - [schema_service.DeleteSchemaRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'SchemaServiceTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/grpc.py deleted file mode 100644 index 6eaf4f1a4fb4..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/grpc.py +++ /dev/null @@ -1,427 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.discoveryengine_v1.types import schema -from google.cloud.discoveryengine_v1.types import schema_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import SchemaServiceTransport, DEFAULT_CLIENT_INFO - - -class SchemaServiceGrpcTransport(SchemaServiceTransport): - """gRPC backend transport for SchemaService. - - Service for managing - [Schema][google.cloud.discoveryengine.v1.Schema]s. - - 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def get_schema(self) -> Callable[ - [schema_service.GetSchemaRequest], - schema.Schema]: - r"""Return a callable for the get schema method over gRPC. - - Gets a [Schema][google.cloud.discoveryengine.v1.Schema]. - - Returns: - Callable[[~.GetSchemaRequest], - ~.Schema]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_schema' not in self._stubs: - self._stubs['get_schema'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.SchemaService/GetSchema', - request_serializer=schema_service.GetSchemaRequest.serialize, - response_deserializer=schema.Schema.deserialize, - ) - return self._stubs['get_schema'] - - @property - def list_schemas(self) -> Callable[ - [schema_service.ListSchemasRequest], - schema_service.ListSchemasResponse]: - r"""Return a callable for the list schemas method over gRPC. - - Gets a list of - [Schema][google.cloud.discoveryengine.v1.Schema]s. - - Returns: - Callable[[~.ListSchemasRequest], - ~.ListSchemasResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_schemas' not in self._stubs: - self._stubs['list_schemas'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.SchemaService/ListSchemas', - request_serializer=schema_service.ListSchemasRequest.serialize, - response_deserializer=schema_service.ListSchemasResponse.deserialize, - ) - return self._stubs['list_schemas'] - - @property - def create_schema(self) -> Callable[ - [schema_service.CreateSchemaRequest], - operations_pb2.Operation]: - r"""Return a callable for the create schema method over gRPC. - - Creates a [Schema][google.cloud.discoveryengine.v1.Schema]. - - Returns: - Callable[[~.CreateSchemaRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_schema' not in self._stubs: - self._stubs['create_schema'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.SchemaService/CreateSchema', - request_serializer=schema_service.CreateSchemaRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_schema'] - - @property - def update_schema(self) -> Callable[ - [schema_service.UpdateSchemaRequest], - operations_pb2.Operation]: - r"""Return a callable for the update schema method over gRPC. - - Updates a [Schema][google.cloud.discoveryengine.v1.Schema]. - - Returns: - Callable[[~.UpdateSchemaRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_schema' not in self._stubs: - self._stubs['update_schema'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.SchemaService/UpdateSchema', - request_serializer=schema_service.UpdateSchemaRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_schema'] - - @property - def delete_schema(self) -> Callable[ - [schema_service.DeleteSchemaRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete schema method over gRPC. - - Deletes a [Schema][google.cloud.discoveryengine.v1.Schema]. - - Returns: - Callable[[~.DeleteSchemaRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_schema' not in self._stubs: - self._stubs['delete_schema'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.SchemaService/DeleteSchema', - request_serializer=schema_service.DeleteSchemaRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_schema'] - - def close(self): - self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'SchemaServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/grpc_asyncio.py deleted file mode 100644 index 3b81e8f16872..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,426 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.discoveryengine_v1.types import schema -from google.cloud.discoveryengine_v1.types import schema_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import SchemaServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import SchemaServiceGrpcTransport - - -class SchemaServiceGrpcAsyncIOTransport(SchemaServiceTransport): - """gRPC AsyncIO backend transport for SchemaService. - - Service for managing - [Schema][google.cloud.discoveryengine.v1.Schema]s. - - 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def get_schema(self) -> Callable[ - [schema_service.GetSchemaRequest], - Awaitable[schema.Schema]]: - r"""Return a callable for the get schema method over gRPC. - - Gets a [Schema][google.cloud.discoveryengine.v1.Schema]. - - Returns: - Callable[[~.GetSchemaRequest], - Awaitable[~.Schema]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_schema' not in self._stubs: - self._stubs['get_schema'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.SchemaService/GetSchema', - request_serializer=schema_service.GetSchemaRequest.serialize, - response_deserializer=schema.Schema.deserialize, - ) - return self._stubs['get_schema'] - - @property - def list_schemas(self) -> Callable[ - [schema_service.ListSchemasRequest], - Awaitable[schema_service.ListSchemasResponse]]: - r"""Return a callable for the list schemas method over gRPC. - - Gets a list of - [Schema][google.cloud.discoveryengine.v1.Schema]s. - - Returns: - Callable[[~.ListSchemasRequest], - Awaitable[~.ListSchemasResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_schemas' not in self._stubs: - self._stubs['list_schemas'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.SchemaService/ListSchemas', - request_serializer=schema_service.ListSchemasRequest.serialize, - response_deserializer=schema_service.ListSchemasResponse.deserialize, - ) - return self._stubs['list_schemas'] - - @property - def create_schema(self) -> Callable[ - [schema_service.CreateSchemaRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create schema method over gRPC. - - Creates a [Schema][google.cloud.discoveryengine.v1.Schema]. - - Returns: - Callable[[~.CreateSchemaRequest], - 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_schema' not in self._stubs: - self._stubs['create_schema'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.SchemaService/CreateSchema', - request_serializer=schema_service.CreateSchemaRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_schema'] - - @property - def update_schema(self) -> Callable[ - [schema_service.UpdateSchemaRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update schema method over gRPC. - - Updates a [Schema][google.cloud.discoveryengine.v1.Schema]. - - Returns: - Callable[[~.UpdateSchemaRequest], - 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_schema' not in self._stubs: - self._stubs['update_schema'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.SchemaService/UpdateSchema', - request_serializer=schema_service.UpdateSchemaRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_schema'] - - @property - def delete_schema(self) -> Callable[ - [schema_service.DeleteSchemaRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete schema method over gRPC. - - Deletes a [Schema][google.cloud.discoveryengine.v1.Schema]. - - Returns: - Callable[[~.DeleteSchemaRequest], - 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_schema' not in self._stubs: - self._stubs['delete_schema'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.SchemaService/DeleteSchema', - request_serializer=schema_service.DeleteSchemaRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_schema'] - - def close(self): - return self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - -__all__ = ( - 'SchemaServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/rest.py deleted file mode 100644 index d5003908f820..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/schema_service/transports/rest.py +++ /dev/null @@ -1,1208 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.cloud.location import locations_pb2 # type: ignore -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.discoveryengine_v1.types import schema -from google.cloud.discoveryengine_v1.types import schema_service -from google.longrunning import operations_pb2 # type: ignore - -from .base import SchemaServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class SchemaServiceRestInterceptor: - """Interceptor for SchemaService. - - 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 SchemaServiceRestTransport. - - .. code-block:: python - class MyCustomSchemaServiceInterceptor(SchemaServiceRestInterceptor): - def pre_create_schema(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_schema(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_schema(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_schema(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_schema(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_schema(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_schemas(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_schemas(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_schema(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_schema(self, response): - logging.log(f"Received response: {response}") - return response - - transport = SchemaServiceRestTransport(interceptor=MyCustomSchemaServiceInterceptor()) - client = SchemaServiceClient(transport=transport) - - - """ - def pre_create_schema(self, request: schema_service.CreateSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[schema_service.CreateSchemaRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_schema - - Override in a subclass to manipulate the request or metadata - before they are sent to the SchemaService server. - """ - return request, metadata - - def post_create_schema(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_schema - - Override in a subclass to manipulate the response - after it is returned by the SchemaService server but before - it is returned to user code. - """ - return response - def pre_delete_schema(self, request: schema_service.DeleteSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[schema_service.DeleteSchemaRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_schema - - Override in a subclass to manipulate the request or metadata - before they are sent to the SchemaService server. - """ - return request, metadata - - def post_delete_schema(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_schema - - Override in a subclass to manipulate the response - after it is returned by the SchemaService server but before - it is returned to user code. - """ - return response - def pre_get_schema(self, request: schema_service.GetSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[schema_service.GetSchemaRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_schema - - Override in a subclass to manipulate the request or metadata - before they are sent to the SchemaService server. - """ - return request, metadata - - def post_get_schema(self, response: schema.Schema) -> schema.Schema: - """Post-rpc interceptor for get_schema - - Override in a subclass to manipulate the response - after it is returned by the SchemaService server but before - it is returned to user code. - """ - return response - def pre_list_schemas(self, request: schema_service.ListSchemasRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[schema_service.ListSchemasRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_schemas - - Override in a subclass to manipulate the request or metadata - before they are sent to the SchemaService server. - """ - return request, metadata - - def post_list_schemas(self, response: schema_service.ListSchemasResponse) -> schema_service.ListSchemasResponse: - """Post-rpc interceptor for list_schemas - - Override in a subclass to manipulate the response - after it is returned by the SchemaService server but before - it is returned to user code. - """ - return response - def pre_update_schema(self, request: schema_service.UpdateSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[schema_service.UpdateSchemaRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_schema - - Override in a subclass to manipulate the request or metadata - before they are sent to the SchemaService server. - """ - return request, metadata - - def post_update_schema(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_schema - - Override in a subclass to manipulate the response - after it is returned by the SchemaService server but before - it is returned to user code. - """ - return response - - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the SchemaService 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 SchemaService server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the SchemaService 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 SchemaService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class SchemaServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: SchemaServiceRestInterceptor - - -class SchemaServiceRestTransport(SchemaServiceTransport): - """REST backend transport for SchemaService. - - Service for managing - [Schema][google.cloud.discoveryengine.v1.Schema]s. - - 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 = 'discoveryengine.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[SchemaServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or SchemaServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1/{name=projects/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/engines/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/models/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*}/operations', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _CreateSchema(SchemaServiceRestStub): - def __hash__(self): - return hash("CreateSchema") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "schemaId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: schema_service.CreateSchemaRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create schema method over HTTP. - - Args: - request (~.schema_service.CreateSchemaRequest): - The request object. Request message for - [SchemaService.CreateSchema][google.cloud.discoveryengine.v1.SchemaService.CreateSchema] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/dataStores/*}/schemas', - 'body': 'schema', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/collections/*/dataStores/*}/schemas', - 'body': 'schema', - }, - ] - request, metadata = self._interceptor.pre_create_schema(request, metadata) - pb_request = schema_service.CreateSchemaRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_schema(resp) - return resp - - class _DeleteSchema(SchemaServiceRestStub): - def __hash__(self): - return hash("DeleteSchema") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: schema_service.DeleteSchemaRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete schema method over HTTP. - - Args: - request (~.schema_service.DeleteSchemaRequest): - The request object. Request message for - [SchemaService.DeleteSchema][google.cloud.discoveryengine.v1.SchemaService.DeleteSchema] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/schemas/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_schema(request, metadata) - pb_request = schema_service.DeleteSchemaRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_schema(resp) - return resp - - class _GetSchema(SchemaServiceRestStub): - def __hash__(self): - return hash("GetSchema") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: schema_service.GetSchemaRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> schema.Schema: - r"""Call the get schema method over HTTP. - - Args: - request (~.schema_service.GetSchemaRequest): - The request object. Request message for - [SchemaService.GetSchema][google.cloud.discoveryengine.v1.SchemaService.GetSchema] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.schema.Schema: - Defines the structure and layout of a - type of document data. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/schemas/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}', - }, - ] - request, metadata = self._interceptor.pre_get_schema(request, metadata) - pb_request = schema_service.GetSchemaRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = schema.Schema() - pb_resp = schema.Schema.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_schema(resp) - return resp - - class _ListSchemas(SchemaServiceRestStub): - def __hash__(self): - return hash("ListSchemas") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: schema_service.ListSchemasRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> schema_service.ListSchemasResponse: - r"""Call the list schemas method over HTTP. - - Args: - request (~.schema_service.ListSchemasRequest): - The request object. Request message for - [SchemaService.ListSchemas][google.cloud.discoveryengine.v1.SchemaService.ListSchemas] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.schema_service.ListSchemasResponse: - Response message for - [SchemaService.ListSchemas][google.cloud.discoveryengine.v1.SchemaService.ListSchemas] - method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/dataStores/*}/schemas', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/collections/*/dataStores/*}/schemas', - }, - ] - request, metadata = self._interceptor.pre_list_schemas(request, metadata) - pb_request = schema_service.ListSchemasRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = schema_service.ListSchemasResponse() - pb_resp = schema_service.ListSchemasResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_schemas(resp) - return resp - - class _UpdateSchema(SchemaServiceRestStub): - def __hash__(self): - return hash("UpdateSchema") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: schema_service.UpdateSchemaRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update schema method over HTTP. - - Args: - request (~.schema_service.UpdateSchemaRequest): - The request object. Request message for - [SchemaService.UpdateSchema][google.cloud.discoveryengine.v1.SchemaService.UpdateSchema] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{schema.name=projects/*/locations/*/dataStores/*/schemas/*}', - 'body': 'schema', - }, -{ - 'method': 'patch', - 'uri': '/v1/{schema.name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}', - 'body': 'schema', - }, - ] - request, metadata = self._interceptor.pre_update_schema(request, metadata) - pb_request = schema_service.UpdateSchemaRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_schema(resp) - return resp - - @property - def create_schema(self) -> Callable[ - [schema_service.CreateSchemaRequest], - 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._CreateSchema(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_schema(self) -> Callable[ - [schema_service.DeleteSchemaRequest], - 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._DeleteSchema(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_schema(self) -> Callable[ - [schema_service.GetSchemaRequest], - schema.Schema]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetSchema(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_schemas(self) -> Callable[ - [schema_service.ListSchemasRequest], - schema_service.ListSchemasResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListSchemas(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_schema(self) -> Callable[ - [schema_service.UpdateSchemaRequest], - 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._UpdateSchema(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(SchemaServiceRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(SchemaServiceRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/engines/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'SchemaServiceRestTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/__init__.py deleted file mode 100644 index 0355170e3569..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import SearchServiceClient -from .async_client import SearchServiceAsyncClient - -__all__ = ( - 'SearchServiceClient', - 'SearchServiceAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/async_client.py deleted file mode 100644 index 82217b20b1f8..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/async_client.py +++ /dev/null @@ -1,402 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.discoveryengine_v1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.discoveryengine_v1.services.search_service import pagers -from google.cloud.discoveryengine_v1.types import search_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport -from .client import SearchServiceClient - - -class SearchServiceAsyncClient: - """Service for search.""" - - _client: SearchServiceClient - - DEFAULT_ENDPOINT = SearchServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SearchServiceClient.DEFAULT_MTLS_ENDPOINT - - branch_path = staticmethod(SearchServiceClient.branch_path) - parse_branch_path = staticmethod(SearchServiceClient.parse_branch_path) - document_path = staticmethod(SearchServiceClient.document_path) - parse_document_path = staticmethod(SearchServiceClient.parse_document_path) - serving_config_path = staticmethod(SearchServiceClient.serving_config_path) - parse_serving_config_path = staticmethod(SearchServiceClient.parse_serving_config_path) - common_billing_account_path = staticmethod(SearchServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(SearchServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(SearchServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(SearchServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(SearchServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(SearchServiceClient.parse_common_organization_path) - common_project_path = staticmethod(SearchServiceClient.common_project_path) - parse_common_project_path = staticmethod(SearchServiceClient.parse_common_project_path) - common_location_path = staticmethod(SearchServiceClient.common_location_path) - parse_common_location_path = staticmethod(SearchServiceClient.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: - SearchServiceAsyncClient: The constructed client. - """ - return SearchServiceClient.from_service_account_info.__func__(SearchServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceAsyncClient: The constructed client. - """ - return SearchServiceClient.from_service_account_file.__func__(SearchServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return SearchServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> SearchServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SearchServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(SearchServiceClient).get_transport_class, type(SearchServiceClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, SearchServiceTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the search 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 (Union[str, ~.SearchServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = SearchServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def search(self, - request: Optional[Union[search_service.SearchRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchAsyncPager: - r"""Performs a search. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - async def sample_search(): - # Create a client - client = discoveryengine_v1.SearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.SearchRequest( - serving_config="serving_config_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1.types.SearchRequest, dict]]): - The request object. Request message for - [SearchService.Search][google.cloud.discoveryengine.v1.SearchService.Search] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1.services.search_service.pagers.SearchAsyncPager: - Response message for - [SearchService.Search][google.cloud.discoveryengine.v1.SearchService.Search] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - request = search_service.SearchRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.search, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config", request.serving_config), - )), - ) - - # 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.SearchAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "SearchServiceAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "SearchServiceAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/client.py deleted file mode 100644 index 32942a207220..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/client.py +++ /dev/null @@ -1,628 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.discoveryengine_v1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.discoveryengine_v1.services.search_service import pagers -from google.cloud.discoveryengine_v1.types import search_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SearchServiceGrpcTransport -from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport -from .transports.rest import SearchServiceRestTransport - - -class SearchServiceClientMeta(type): - """Metaclass for the SearchService 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[SearchServiceTransport]] - _transport_registry["grpc"] = SearchServiceGrpcTransport - _transport_registry["grpc_asyncio"] = SearchServiceGrpcAsyncIOTransport - _transport_registry["rest"] = SearchServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[SearchServiceTransport]: - """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 SearchServiceClient(metaclass=SearchServiceClientMeta): - """Service for search.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceClient: 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: - SearchServiceClient: 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) -> SearchServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SearchServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def branch_path(project: str,location: str,data_store: str,branch: str,) -> str: - """Returns a fully-qualified branch string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}".format(project=project, location=location, data_store=data_store, branch=branch, ) - - @staticmethod - def parse_branch_path(path: str) -> Dict[str,str]: - """Parses a branch path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def document_path(project: str,location: str,data_store: str,branch: str,document: str,) -> str: - """Returns a fully-qualified document string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) - - @staticmethod - def parse_document_path(path: str) -> Dict[str,str]: - """Parses a document path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)/documents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def serving_config_path(project: str,location: str,data_store: str,serving_config: str,) -> str: - """Returns a fully-qualified serving_config string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}/servingConfigs/{serving_config}".format(project=project, location=location, data_store=data_store, serving_config=serving_config, ) - - @staticmethod - def parse_serving_config_path(path: str) -> Dict[str,str]: - """Parses a serving_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/servingConfigs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, SearchServiceTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the search 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 (Union[str, SearchServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, SearchServiceTransport): - # transport is a SearchServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def search(self, - request: Optional[Union[search_service.SearchRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchPager: - r"""Performs a search. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - def sample_search(): - # Create a client - client = discoveryengine_v1.SearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.SearchRequest( - serving_config="serving_config_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1.types.SearchRequest, dict]): - The request object. Request message for - [SearchService.Search][google.cloud.discoveryengine.v1.SearchService.Search] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1.services.search_service.pagers.SearchPager: - Response message for - [SearchService.Search][google.cloud.discoveryengine.v1.SearchService.Search] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a search_service.SearchRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, search_service.SearchRequest): - request = search_service.SearchRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.search] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config", request.serving_config), - )), - ) - - # 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.SearchPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "SearchServiceClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - - - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "SearchServiceClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/pagers.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/pagers.py deleted file mode 100644 index 34caebaa5864..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.discoveryengine_v1.types import search_service - - -class SearchPager: - """A pager for iterating through ``search`` requests. - - This class thinly wraps an initial - :class:`google.cloud.discoveryengine_v1.types.SearchResponse` object, and - provides an ``__iter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``Search`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.discoveryengine_v1.types.SearchResponse` - 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[..., search_service.SearchResponse], - request: search_service.SearchRequest, - response: search_service.SearchResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.discoveryengine_v1.types.SearchRequest): - The initial request object. - response (google.cloud.discoveryengine_v1.types.SearchResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = search_service.SearchRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[search_service.SearchResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[search_service.SearchResponse.SearchResult]: - for page in self.pages: - yield from page.results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class SearchAsyncPager: - """A pager for iterating through ``search`` requests. - - This class thinly wraps an initial - :class:`google.cloud.discoveryengine_v1.types.SearchResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``Search`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.discoveryengine_v1.types.SearchResponse` - 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[search_service.SearchResponse]], - request: search_service.SearchRequest, - response: search_service.SearchResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.discoveryengine_v1.types.SearchRequest): - The initial request object. - response (google.cloud.discoveryengine_v1.types.SearchResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = search_service.SearchRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[search_service.SearchResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[search_service.SearchResponse.SearchResult]: - async def async_generator(): - async for page in self.pages: - for response in page.results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/__init__.py deleted file mode 100644 index 4282aef080e3..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import SearchServiceTransport -from .grpc import SearchServiceGrpcTransport -from .grpc_asyncio import SearchServiceGrpcAsyncIOTransport -from .rest import SearchServiceRestTransport -from .rest import SearchServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] -_transport_registry['grpc'] = SearchServiceGrpcTransport -_transport_registry['grpc_asyncio'] = SearchServiceGrpcAsyncIOTransport -_transport_registry['rest'] = SearchServiceRestTransport - -__all__ = ( - 'SearchServiceTransport', - 'SearchServiceGrpcTransport', - 'SearchServiceGrpcAsyncIOTransport', - 'SearchServiceRestTransport', - 'SearchServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/base.py deleted file mode 100644 index 9266e6b82fae..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/base.py +++ /dev/null @@ -1,168 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.discoveryengine_v1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.discoveryengine_v1.types import search_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class SearchServiceTransport(abc.ABC): - """Abstract transport class for SearchService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'discoveryengine.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.search: gapic_v1.method.wrap_method( - self.search, - 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 search(self) -> Callable[ - [search_service.SearchRequest], - Union[ - search_service.SearchResponse, - Awaitable[search_service.SearchResponse] - ]]: - 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 kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'SearchServiceTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/grpc.py deleted file mode 100644 index 804ede46eaa7..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/grpc.py +++ /dev/null @@ -1,302 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.discoveryengine_v1.types import search_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO - - -class SearchServiceGrpcTransport(SearchServiceTransport): - """gRPC backend transport for SearchService. - - Service for search. - - 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def search(self) -> Callable[ - [search_service.SearchRequest], - search_service.SearchResponse]: - r"""Return a callable for the search method over gRPC. - - Performs a search. - - Returns: - Callable[[~.SearchRequest], - ~.SearchResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search' not in self._stubs: - self._stubs['search'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.SearchService/Search', - request_serializer=search_service.SearchRequest.serialize, - response_deserializer=search_service.SearchResponse.deserialize, - ) - return self._stubs['search'] - - def close(self): - self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'SearchServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/grpc_asyncio.py deleted file mode 100644 index a12464fae22f..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,301 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.discoveryengine_v1.types import search_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import SearchServiceGrpcTransport - - -class SearchServiceGrpcAsyncIOTransport(SearchServiceTransport): - """gRPC AsyncIO backend transport for SearchService. - - Service for search. - - 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def search(self) -> Callable[ - [search_service.SearchRequest], - Awaitable[search_service.SearchResponse]]: - r"""Return a callable for the search method over gRPC. - - Performs a search. - - Returns: - Callable[[~.SearchRequest], - Awaitable[~.SearchResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search' not in self._stubs: - self._stubs['search'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.SearchService/Search', - request_serializer=search_service.SearchRequest.serialize, - response_deserializer=search_service.SearchResponse.deserialize, - ) - return self._stubs['search'] - - def close(self): - return self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - -__all__ = ( - 'SearchServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/rest.py deleted file mode 100644 index 255451db805f..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/search_service/transports/rest.py +++ /dev/null @@ -1,584 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.cloud.location import locations_pb2 # type: ignore -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.discoveryengine_v1.types import search_service -from google.longrunning import operations_pb2 # type: ignore - -from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class SearchServiceRestInterceptor: - """Interceptor for SearchService. - - 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 SearchServiceRestTransport. - - .. code-block:: python - class MyCustomSearchServiceInterceptor(SearchServiceRestInterceptor): - def pre_search(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_search(self, response): - logging.log(f"Received response: {response}") - return response - - transport = SearchServiceRestTransport(interceptor=MyCustomSearchServiceInterceptor()) - client = SearchServiceClient(transport=transport) - - - """ - def pre_search(self, request: search_service.SearchRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[search_service.SearchRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for search - - Override in a subclass to manipulate the request or metadata - before they are sent to the SearchService server. - """ - return request, metadata - - def post_search(self, response: search_service.SearchResponse) -> search_service.SearchResponse: - """Post-rpc interceptor for search - - Override in a subclass to manipulate the response - after it is returned by the SearchService server but before - it is returned to user code. - """ - return response - - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the SearchService 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 SearchService server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the SearchService 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 SearchService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class SearchServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: SearchServiceRestInterceptor - - -class SearchServiceRestTransport(SearchServiceTransport): - """REST backend transport for SearchService. - - Service for search. - - 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 = 'discoveryengine.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[SearchServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or SearchServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _Search(SearchServiceRestStub): - def __hash__(self): - return hash("Search") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: search_service.SearchRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> search_service.SearchResponse: - r"""Call the search method over HTTP. - - Args: - request (~.search_service.SearchRequest): - The request object. Request message for - [SearchService.Search][google.cloud.discoveryengine.v1.SearchService.Search] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.search_service.SearchResponse: - Response message for - [SearchService.Search][google.cloud.discoveryengine.v1.SearchService.Search] - method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{serving_config=projects/*/locations/*/dataStores/*/servingConfigs/*}:search', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{serving_config=projects/*/locations/*/collections/*/dataStores/*/servingConfigs/*}:search', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_search(request, metadata) - pb_request = search_service.SearchRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = search_service.SearchResponse() - pb_resp = search_service.SearchResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_search(resp) - return resp - - @property - def search(self) -> Callable[ - [search_service.SearchRequest], - search_service.SearchResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._Search(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(SearchServiceRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(SearchServiceRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/engines/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'SearchServiceRestTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/__init__.py deleted file mode 100644 index 387c002d1701..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import UserEventServiceClient -from .async_client import UserEventServiceAsyncClient - -__all__ = ( - 'UserEventServiceClient', - 'UserEventServiceAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/async_client.py deleted file mode 100644 index 257240b756f1..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/async_client.py +++ /dev/null @@ -1,644 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.discoveryengine_v1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.discoveryengine_v1.types import common -from google.cloud.discoveryengine_v1.types import import_config -from google.cloud.discoveryengine_v1.types import user_event -from google.cloud.discoveryengine_v1.types import user_event_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport -from .client import UserEventServiceClient - - -class UserEventServiceAsyncClient: - """Service for ingesting end user actions on a website to - Discovery Engine API. - """ - - _client: UserEventServiceClient - - DEFAULT_ENDPOINT = UserEventServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = UserEventServiceClient.DEFAULT_MTLS_ENDPOINT - - data_store_path = staticmethod(UserEventServiceClient.data_store_path) - parse_data_store_path = staticmethod(UserEventServiceClient.parse_data_store_path) - document_path = staticmethod(UserEventServiceClient.document_path) - parse_document_path = staticmethod(UserEventServiceClient.parse_document_path) - common_billing_account_path = staticmethod(UserEventServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(UserEventServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(UserEventServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(UserEventServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(UserEventServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(UserEventServiceClient.parse_common_organization_path) - common_project_path = staticmethod(UserEventServiceClient.common_project_path) - parse_common_project_path = staticmethod(UserEventServiceClient.parse_common_project_path) - common_location_path = staticmethod(UserEventServiceClient.common_location_path) - parse_common_location_path = staticmethod(UserEventServiceClient.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: - UserEventServiceAsyncClient: The constructed client. - """ - return UserEventServiceClient.from_service_account_info.__func__(UserEventServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceAsyncClient: The constructed client. - """ - return UserEventServiceClient.from_service_account_file.__func__(UserEventServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return UserEventServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> UserEventServiceTransport: - """Returns the transport used by the client instance. - - Returns: - UserEventServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(UserEventServiceClient).get_transport_class, type(UserEventServiceClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, UserEventServiceTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the user event 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 (Union[str, ~.UserEventServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = UserEventServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def write_user_event(self, - request: Optional[Union[user_event_service.WriteUserEventRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> user_event.UserEvent: - r"""Writes a single user event. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - async def sample_write_user_event(): - # Create a client - client = discoveryengine_v1.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.WriteUserEventRequest( - parent="parent_value", - ) - - # Make the request - response = await client.write_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1.types.WriteUserEventRequest, dict]]): - The request object. Request message for WriteUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1.types.UserEvent: - UserEvent captures all metadata - information Discovery Engine API needs - to know about how end users interact - with customers' website. - - """ - # Create or coerce a protobuf request object. - request = user_event_service.WriteUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.write_user_event, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def collect_user_event(self, - request: Optional[Union[user_event_service.CollectUserEventRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> httpbody_pb2.HttpBody: - r"""Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a third-party domain. - - This method is used only by the Discovery Engine API - JavaScript pixel and Google Tag Manager. Users should - not call this method directly. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - async def sample_collect_user_event(): - # Create a client - client = discoveryengine_v1.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = await client.collect_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1.types.CollectUserEventRequest, dict]]): - The request object. Request message for CollectUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It should only be used for - payload formats that can't be represented as JSON, - such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as - the response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request - fields and also want access to the raw HTTP body. - - Example: - - message GetResourceRequest { - // A unique request id. string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) - returns (google.api.HttpBody); - - rpc UpdateResource(google.api.HttpBody) - returns (google.protobuf.Empty); - - } - - Example with streaming methods: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - # Create or coerce a protobuf request object. - request = user_event_service.CollectUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.collect_user_event, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def import_user_events(self, - request: Optional[Union[import_config.ImportUserEventsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - async def sample_import_user_events(): - # Create a client - client = discoveryengine_v1.UserEventServiceAsyncClient() - - # Initialize request argument(s) - inline_source = discoveryengine_v1.InlineSource() - inline_source.user_events.event_type = "event_type_value" - inline_source.user_events.user_pseudo_id = "user_pseudo_id_value" - - request = discoveryengine_v1.ImportUserEventsRequest( - inline_source=inline_source, - parent="parent_value", - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1.types.ImportUserEventsRequest, dict]]): - The request object. Request message for the - ImportUserEvents request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.discoveryengine_v1.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is - returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - request = import_config.ImportUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_user_events, - default_retry=retries.Retry( -initial=1.0,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=300.0, - ), - default_timeout=300.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - import_config.ImportUserEventsResponse, - metadata_type=import_config.ImportUserEventsMetadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "UserEventServiceAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "UserEventServiceAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/client.py deleted file mode 100644 index 80ca814e4647..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/client.py +++ /dev/null @@ -1,857 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.discoveryengine_v1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.discoveryengine_v1.types import common -from google.cloud.discoveryengine_v1.types import import_config -from google.cloud.discoveryengine_v1.types import user_event -from google.cloud.discoveryengine_v1.types import user_event_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import UserEventServiceGrpcTransport -from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport -from .transports.rest import UserEventServiceRestTransport - - -class UserEventServiceClientMeta(type): - """Metaclass for the UserEventService 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[UserEventServiceTransport]] - _transport_registry["grpc"] = UserEventServiceGrpcTransport - _transport_registry["grpc_asyncio"] = UserEventServiceGrpcAsyncIOTransport - _transport_registry["rest"] = UserEventServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[UserEventServiceTransport]: - """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 UserEventServiceClient(metaclass=UserEventServiceClientMeta): - """Service for ingesting end user actions on a website to - Discovery Engine API. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceClient: 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: - UserEventServiceClient: 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) -> UserEventServiceTransport: - """Returns the transport used by the client instance. - - Returns: - UserEventServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def data_store_path(project: str,location: str,data_store: str,) -> str: - """Returns a fully-qualified data_store string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) - - @staticmethod - def parse_data_store_path(path: str) -> Dict[str,str]: - """Parses a data_store path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def document_path(project: str,location: str,data_store: str,branch: str,document: str,) -> str: - """Returns a fully-qualified document string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) - - @staticmethod - def parse_document_path(path: str) -> Dict[str,str]: - """Parses a document path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)/documents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, UserEventServiceTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the user event 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 (Union[str, UserEventServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, UserEventServiceTransport): - # transport is a UserEventServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def write_user_event(self, - request: Optional[Union[user_event_service.WriteUserEventRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> user_event.UserEvent: - r"""Writes a single user event. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - def sample_write_user_event(): - # Create a client - client = discoveryengine_v1.UserEventServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.WriteUserEventRequest( - parent="parent_value", - ) - - # Make the request - response = client.write_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1.types.WriteUserEventRequest, dict]): - The request object. Request message for WriteUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1.types.UserEvent: - UserEvent captures all metadata - information Discovery Engine API needs - to know about how end users interact - with customers' website. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a user_event_service.WriteUserEventRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, user_event_service.WriteUserEventRequest): - request = user_event_service.WriteUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.write_user_event] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def collect_user_event(self, - request: Optional[Union[user_event_service.CollectUserEventRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> httpbody_pb2.HttpBody: - r"""Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a third-party domain. - - This method is used only by the Discovery Engine API - JavaScript pixel and Google Tag Manager. Users should - not call this method directly. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - def sample_collect_user_event(): - # Create a client - client = discoveryengine_v1.UserEventServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = client.collect_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1.types.CollectUserEventRequest, dict]): - The request object. Request message for CollectUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It should only be used for - payload formats that can't be represented as JSON, - such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as - the response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request - fields and also want access to the raw HTTP body. - - Example: - - message GetResourceRequest { - // A unique request id. string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) - returns (google.api.HttpBody); - - rpc UpdateResource(google.api.HttpBody) - returns (google.protobuf.Empty); - - } - - Example with streaming methods: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a user_event_service.CollectUserEventRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, user_event_service.CollectUserEventRequest): - request = user_event_service.CollectUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.collect_user_event] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def import_user_events(self, - request: Optional[Union[import_config.ImportUserEventsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1 - - def sample_import_user_events(): - # Create a client - client = discoveryengine_v1.UserEventServiceClient() - - # Initialize request argument(s) - inline_source = discoveryengine_v1.InlineSource() - inline_source.user_events.event_type = "event_type_value" - inline_source.user_events.user_pseudo_id = "user_pseudo_id_value" - - request = discoveryengine_v1.ImportUserEventsRequest( - inline_source=inline_source, - parent="parent_value", - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1.types.ImportUserEventsRequest, dict]): - The request object. Request message for the - ImportUserEvents request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.discoveryengine_v1.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is - returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a import_config.ImportUserEventsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, import_config.ImportUserEventsRequest): - request = import_config.ImportUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_user_events] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - import_config.ImportUserEventsResponse, - metadata_type=import_config.ImportUserEventsMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "UserEventServiceClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - - - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "UserEventServiceClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/__init__.py deleted file mode 100644 index bea95d5a9d94..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import UserEventServiceTransport -from .grpc import UserEventServiceGrpcTransport -from .grpc_asyncio import UserEventServiceGrpcAsyncIOTransport -from .rest import UserEventServiceRestTransport -from .rest import UserEventServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] -_transport_registry['grpc'] = UserEventServiceGrpcTransport -_transport_registry['grpc_asyncio'] = UserEventServiceGrpcAsyncIOTransport -_transport_registry['rest'] = UserEventServiceRestTransport - -__all__ = ( - 'UserEventServiceTransport', - 'UserEventServiceGrpcTransport', - 'UserEventServiceGrpcAsyncIOTransport', - 'UserEventServiceRestTransport', - 'UserEventServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/base.py deleted file mode 100644 index ecbf50a999fd..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/base.py +++ /dev/null @@ -1,211 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.discoveryengine_v1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.discoveryengine_v1.types import import_config -from google.cloud.discoveryengine_v1.types import user_event -from google.cloud.discoveryengine_v1.types import user_event_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class UserEventServiceTransport(abc.ABC): - """Abstract transport class for UserEventService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'discoveryengine.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.write_user_event: gapic_v1.method.wrap_method( - self.write_user_event, - default_timeout=None, - client_info=client_info, - ), - self.collect_user_event: gapic_v1.method.wrap_method( - self.collect_user_event, - default_timeout=None, - client_info=client_info, - ), - self.import_user_events: gapic_v1.method.wrap_method( - self.import_user_events, - default_retry=retries.Retry( -initial=1.0,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=300.0, - ), - default_timeout=300.0, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - Union[ - user_event.UserEvent, - Awaitable[user_event.UserEvent] - ]]: - raise NotImplementedError() - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - Union[ - httpbody_pb2.HttpBody, - Awaitable[httpbody_pb2.HttpBody] - ]]: - raise NotImplementedError() - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'UserEventServiceTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/grpc.py deleted file mode 100644 index a8947aaaf1de..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/grpc.py +++ /dev/null @@ -1,389 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.discoveryengine_v1.types import import_config -from google.cloud.discoveryengine_v1.types import user_event -from google.cloud.discoveryengine_v1.types import user_event_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO - - -class UserEventServiceGrpcTransport(UserEventServiceTransport): - """gRPC backend transport for UserEventService. - - Service for ingesting end user actions on a website to - Discovery Engine 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 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - user_event.UserEvent]: - r"""Return a callable for the write user event method over gRPC. - - Writes a single user event. - - Returns: - Callable[[~.WriteUserEventRequest], - ~.UserEvent]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'write_user_event' not in self._stubs: - self._stubs['write_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.UserEventService/WriteUserEvent', - request_serializer=user_event_service.WriteUserEventRequest.serialize, - response_deserializer=user_event.UserEvent.deserialize, - ) - return self._stubs['write_user_event'] - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - httpbody_pb2.HttpBody]: - r"""Return a callable for the collect user event method over gRPC. - - Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a third-party domain. - - This method is used only by the Discovery Engine API - JavaScript pixel and Google Tag Manager. Users should - not call this method directly. - - Returns: - Callable[[~.CollectUserEventRequest], - ~.HttpBody]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'collect_user_event' not in self._stubs: - self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.UserEventService/CollectUserEvent', - request_serializer=user_event_service.CollectUserEventRequest.serialize, - response_deserializer=httpbody_pb2.HttpBody.FromString, - ) - return self._stubs['collect_user_event'] - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - operations_pb2.Operation]: - r"""Return a callable for the import user events method over gRPC. - - Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - Returns: - Callable[[~.ImportUserEventsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_user_events' not in self._stubs: - self._stubs['import_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.UserEventService/ImportUserEvents', - request_serializer=import_config.ImportUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_user_events'] - - def close(self): - self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'UserEventServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/grpc_asyncio.py deleted file mode 100644 index 2053f8993009..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,388 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.discoveryengine_v1.types import import_config -from google.cloud.discoveryengine_v1.types import user_event -from google.cloud.discoveryengine_v1.types import user_event_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import UserEventServiceGrpcTransport - - -class UserEventServiceGrpcAsyncIOTransport(UserEventServiceTransport): - """gRPC AsyncIO backend transport for UserEventService. - - Service for ingesting end user actions on a website to - Discovery Engine 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 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - Awaitable[user_event.UserEvent]]: - r"""Return a callable for the write user event method over gRPC. - - Writes a single user event. - - Returns: - Callable[[~.WriteUserEventRequest], - Awaitable[~.UserEvent]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'write_user_event' not in self._stubs: - self._stubs['write_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.UserEventService/WriteUserEvent', - request_serializer=user_event_service.WriteUserEventRequest.serialize, - response_deserializer=user_event.UserEvent.deserialize, - ) - return self._stubs['write_user_event'] - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - Awaitable[httpbody_pb2.HttpBody]]: - r"""Return a callable for the collect user event method over gRPC. - - Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a third-party domain. - - This method is used only by the Discovery Engine API - JavaScript pixel and Google Tag Manager. Users should - not call this method directly. - - Returns: - Callable[[~.CollectUserEventRequest], - Awaitable[~.HttpBody]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'collect_user_event' not in self._stubs: - self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.UserEventService/CollectUserEvent', - request_serializer=user_event_service.CollectUserEventRequest.serialize, - response_deserializer=httpbody_pb2.HttpBody.FromString, - ) - return self._stubs['collect_user_event'] - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import user events method over gRPC. - - Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - Returns: - Callable[[~.ImportUserEventsRequest], - 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 'import_user_events' not in self._stubs: - self._stubs['import_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1.UserEventService/ImportUserEvents', - request_serializer=import_config.ImportUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_user_events'] - - def close(self): - return self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - -__all__ = ( - 'UserEventServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/rest.py deleted file mode 100644 index 9b065bb735a0..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/services/user_event_service/transports/rest.py +++ /dev/null @@ -1,1021 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.cloud.location import locations_pb2 # type: ignore -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.discoveryengine_v1.types import import_config -from google.cloud.discoveryengine_v1.types import user_event -from google.cloud.discoveryengine_v1.types import user_event_service -from google.longrunning import operations_pb2 # type: ignore - -from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class UserEventServiceRestInterceptor: - """Interceptor for UserEventService. - - 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 UserEventServiceRestTransport. - - .. code-block:: python - class MyCustomUserEventServiceInterceptor(UserEventServiceRestInterceptor): - def pre_collect_user_event(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_collect_user_event(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_import_user_events(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_import_user_events(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_write_user_event(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_write_user_event(self, response): - logging.log(f"Received response: {response}") - return response - - transport = UserEventServiceRestTransport(interceptor=MyCustomUserEventServiceInterceptor()) - client = UserEventServiceClient(transport=transport) - - - """ - def pre_collect_user_event(self, request: user_event_service.CollectUserEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[user_event_service.CollectUserEventRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for collect_user_event - - Override in a subclass to manipulate the request or metadata - before they are sent to the UserEventService server. - """ - return request, metadata - - def post_collect_user_event(self, response: httpbody_pb2.HttpBody) -> httpbody_pb2.HttpBody: - """Post-rpc interceptor for collect_user_event - - Override in a subclass to manipulate the response - after it is returned by the UserEventService server but before - it is returned to user code. - """ - return response - def pre_import_user_events(self, request: import_config.ImportUserEventsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[import_config.ImportUserEventsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for import_user_events - - Override in a subclass to manipulate the request or metadata - before they are sent to the UserEventService server. - """ - return request, metadata - - def post_import_user_events(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for import_user_events - - Override in a subclass to manipulate the response - after it is returned by the UserEventService server but before - it is returned to user code. - """ - return response - def pre_write_user_event(self, request: user_event_service.WriteUserEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[user_event_service.WriteUserEventRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for write_user_event - - Override in a subclass to manipulate the request or metadata - before they are sent to the UserEventService server. - """ - return request, metadata - - def post_write_user_event(self, response: user_event.UserEvent) -> user_event.UserEvent: - """Post-rpc interceptor for write_user_event - - Override in a subclass to manipulate the response - after it is returned by the UserEventService server but before - it is returned to user code. - """ - return response - - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the UserEventService 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 UserEventService server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the UserEventService 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 UserEventService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class UserEventServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: UserEventServiceRestInterceptor - - -class UserEventServiceRestTransport(UserEventServiceTransport): - """REST backend transport for UserEventService. - - Service for ingesting end user actions on a website to - Discovery Engine 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 = 'discoveryengine.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[UserEventServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or UserEventServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1/{name=projects/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/engines/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/models/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1/{name=projects/*}/operations', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _CollectUserEvent(UserEventServiceRestStub): - def __hash__(self): - return hash("CollectUserEvent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "userEvent" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: user_event_service.CollectUserEventRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> httpbody_pb2.HttpBody: - r"""Call the collect user event method over HTTP. - - Args: - request (~.user_event_service.CollectUserEventRequest): - The request object. Request message for CollectUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It - should only be used for payload formats that can't be - represented as JSON, such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as the - response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request fields - and also want access to the raw HTTP body. - - Example: - - :: - - message GetResourceRequest { - // A unique request id. - string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) - returns (google.api.HttpBody); - rpc UpdateResource(google.api.HttpBody) - returns (google.protobuf.Empty); - - } - - Example with streaming methods: - - :: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/dataStores/*}/userEvents:collect', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/collections/*/dataStores/*}/userEvents:collect', - }, - ] - request, metadata = self._interceptor.pre_collect_user_event(request, metadata) - pb_request = user_event_service.CollectUserEventRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = httpbody_pb2.HttpBody() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_collect_user_event(resp) - return resp - - class _ImportUserEvents(UserEventServiceRestStub): - def __hash__(self): - return hash("ImportUserEvents") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: import_config.ImportUserEventsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the import user events method over HTTP. - - Args: - request (~.import_config.ImportUserEventsRequest): - The request object. Request message for the - ImportUserEvents request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/dataStores/*}/userEvents:import', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/collections/*/dataStores/*}/userEvents:import', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_import_user_events(request, metadata) - pb_request = import_config.ImportUserEventsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_import_user_events(resp) - return resp - - class _WriteUserEvent(UserEventServiceRestStub): - def __hash__(self): - return hash("WriteUserEvent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: user_event_service.WriteUserEventRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> user_event.UserEvent: - r"""Call the write user event method over HTTP. - - Args: - request (~.user_event_service.WriteUserEventRequest): - The request object. Request message for WriteUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.user_event.UserEvent: - UserEvent captures all metadata - information Discovery Engine API needs - to know about how end users interact - with customers' website. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/dataStores/*}/userEvents:write', - 'body': 'user_event', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/collections/*/dataStores/*}/userEvents:write', - 'body': 'user_event', - }, - ] - request, metadata = self._interceptor.pre_write_user_event(request, metadata) - pb_request = user_event_service.WriteUserEventRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = user_event.UserEvent() - pb_resp = user_event.UserEvent.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_write_user_event(resp) - return resp - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - httpbody_pb2.HttpBody]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CollectUserEvent(self._session, self._host, self._interceptor) # type: ignore - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - 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._ImportUserEvents(self._session, self._host, self._interceptor) # type: ignore - - @property - def write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - user_event.UserEvent]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._WriteUserEvent(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(UserEventServiceRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(UserEventServiceRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*/engines/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/collections/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'UserEventServiceRestTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/__init__.py deleted file mode 100644 index 146eeae9f7dc..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/__init__.py +++ /dev/null @@ -1,162 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .common import ( - CustomAttribute, - Interval, - UserInfo, -) -from .completion_service import ( - CompleteQueryRequest, - CompleteQueryResponse, -) -from .conversation import ( - Conversation, - ConversationContext, - ConversationMessage, - Reply, - TextInput, -) -from .conversational_search_service import ( - ConverseConversationRequest, - ConverseConversationResponse, - CreateConversationRequest, - DeleteConversationRequest, - GetConversationRequest, - ListConversationsRequest, - ListConversationsResponse, - UpdateConversationRequest, -) -from .document import ( - Document, -) -from .document_service import ( - CreateDocumentRequest, - DeleteDocumentRequest, - GetDocumentRequest, - ListDocumentsRequest, - ListDocumentsResponse, - UpdateDocumentRequest, -) -from .import_config import ( - BigQuerySource, - GcsSource, - ImportDocumentsMetadata, - ImportDocumentsRequest, - ImportDocumentsResponse, - ImportErrorConfig, - ImportUserEventsMetadata, - ImportUserEventsRequest, - ImportUserEventsResponse, -) -from .purge_config import ( - PurgeDocumentsMetadata, - PurgeDocumentsRequest, - PurgeDocumentsResponse, -) -from .schema import ( - Schema, -) -from .schema_service import ( - CreateSchemaMetadata, - CreateSchemaRequest, - DeleteSchemaMetadata, - DeleteSchemaRequest, - GetSchemaRequest, - ListSchemasRequest, - ListSchemasResponse, - UpdateSchemaMetadata, - UpdateSchemaRequest, -) -from .search_service import ( - SearchRequest, - SearchResponse, -) -from .user_event import ( - CompletionInfo, - DocumentInfo, - MediaInfo, - PageInfo, - PanelInfo, - SearchInfo, - TransactionInfo, - UserEvent, -) -from .user_event_service import ( - CollectUserEventRequest, - WriteUserEventRequest, -) - -__all__ = ( - 'CustomAttribute', - 'Interval', - 'UserInfo', - 'CompleteQueryRequest', - 'CompleteQueryResponse', - 'Conversation', - 'ConversationContext', - 'ConversationMessage', - 'Reply', - 'TextInput', - 'ConverseConversationRequest', - 'ConverseConversationResponse', - 'CreateConversationRequest', - 'DeleteConversationRequest', - 'GetConversationRequest', - 'ListConversationsRequest', - 'ListConversationsResponse', - 'UpdateConversationRequest', - 'Document', - 'CreateDocumentRequest', - 'DeleteDocumentRequest', - 'GetDocumentRequest', - 'ListDocumentsRequest', - 'ListDocumentsResponse', - 'UpdateDocumentRequest', - 'BigQuerySource', - 'GcsSource', - 'ImportDocumentsMetadata', - 'ImportDocumentsRequest', - 'ImportDocumentsResponse', - 'ImportErrorConfig', - 'ImportUserEventsMetadata', - 'ImportUserEventsRequest', - 'ImportUserEventsResponse', - 'PurgeDocumentsMetadata', - 'PurgeDocumentsRequest', - 'PurgeDocumentsResponse', - 'Schema', - 'CreateSchemaMetadata', - 'CreateSchemaRequest', - 'DeleteSchemaMetadata', - 'DeleteSchemaRequest', - 'GetSchemaRequest', - 'ListSchemasRequest', - 'ListSchemasResponse', - 'UpdateSchemaMetadata', - 'UpdateSchemaRequest', - 'SearchRequest', - 'SearchResponse', - 'CompletionInfo', - 'DocumentInfo', - 'MediaInfo', - 'PageInfo', - 'PanelInfo', - 'SearchInfo', - 'TransactionInfo', - 'UserEvent', - 'CollectUserEventRequest', - 'WriteUserEventRequest', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/common.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/common.py deleted file mode 100644 index 724d1429b4a0..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/common.py +++ /dev/null @@ -1,167 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1', - manifest={ - 'Interval', - 'CustomAttribute', - 'UserInfo', - }, -) - - -class Interval(proto.Message): - r"""A floating point interval. - - 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: - minimum (float): - Inclusive lower bound. - - This field is a member of `oneof`_ ``min``. - exclusive_minimum (float): - Exclusive lower bound. - - This field is a member of `oneof`_ ``min``. - maximum (float): - Inclusive upper bound. - - This field is a member of `oneof`_ ``max``. - exclusive_maximum (float): - Exclusive upper bound. - - This field is a member of `oneof`_ ``max``. - """ - - minimum: float = proto.Field( - proto.DOUBLE, - number=1, - oneof='min', - ) - exclusive_minimum: float = proto.Field( - proto.DOUBLE, - number=2, - oneof='min', - ) - maximum: float = proto.Field( - proto.DOUBLE, - number=3, - oneof='max', - ) - exclusive_maximum: float = proto.Field( - proto.DOUBLE, - number=4, - oneof='max', - ) - - -class CustomAttribute(proto.Message): - r"""A custom attribute that is not explicitly modeled in a resource, - e.g. [UserEvent][google.cloud.discoveryengine.v1.UserEvent]. - - Attributes: - text (MutableSequence[str]): - The textual values of this custom attribute. For example, - ``["yellow", "green"]`` when the key is "color". - - Empty string is not allowed. Otherwise, an - ``INVALID_ARGUMENT`` error is returned. - - Exactly one of - [CustomAttribute.text][google.cloud.discoveryengine.v1.CustomAttribute.text] - or - [CustomAttribute.numbers][google.cloud.discoveryengine.v1.CustomAttribute.numbers] - should be set. Otherwise, an ``INVALID_ARGUMENT`` error is - returned. - numbers (MutableSequence[float]): - The numerical values of this custom attribute. For example, - ``[2.3, 15.4]`` when the key is "lengths_cm". - - Exactly one of - [CustomAttribute.text][google.cloud.discoveryengine.v1.CustomAttribute.text] - or - [CustomAttribute.numbers][google.cloud.discoveryengine.v1.CustomAttribute.numbers] - should be set. Otherwise, an ``INVALID_ARGUMENT`` error is - returned. - """ - - text: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - numbers: MutableSequence[float] = proto.RepeatedField( - proto.DOUBLE, - number=2, - ) - - -class UserInfo(proto.Message): - r"""Information of an end user. - - Attributes: - user_id (str): - Highly recommended for logged-in users. Unique identifier - for logged-in user, such as a user name. Don't set for - anonymous users. - - Always use a hashed value for this ID. - - Don't set the field to the same fixed ID for different - users. This mixes the event history of those users together, - which results in degraded model quality. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an ``INVALID_ARGUMENT`` error - is returned. - user_agent (str): - User agent as included in the HTTP header. - - The field must be a UTF-8 encoded string with a length limit - of 1,000 characters. Otherwise, an ``INVALID_ARGUMENT`` - error is returned. - - This should not be set when using the client side event - reporting with GTM or JavaScript tag in - [UserEventService.CollectUserEvent][google.cloud.discoveryengine.v1.UserEventService.CollectUserEvent] - or if - [UserEvent.direct_user_request][google.cloud.discoveryengine.v1.UserEvent.direct_user_request] - is set. - """ - - user_id: str = proto.Field( - proto.STRING, - number=1, - ) - user_agent: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/completion_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/completion_service.py deleted file mode 100644 index 5a956b2a746b..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/completion_service.py +++ /dev/null @@ -1,158 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1', - manifest={ - 'CompleteQueryRequest', - 'CompleteQueryResponse', - }, -) - - -class CompleteQueryRequest(proto.Message): - r"""Request message for - [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1.CompletionService.CompleteQuery] - method. - - Attributes: - data_store (str): - Required. The parent data store resource name for which the - completion is performed, such as - ``projects/*/locations/global/collections/default_collection/dataStores/default_data_store``. - query (str): - Required. The typeahead input used to fetch - suggestions. Maximum length is 128 characters. - query_model (str): - Selects data model of query suggestions for serving. - Currently supported values: - - - ``document`` - Using suggestions generated from - user-imported documents. - - ``search-history`` - Using suggestions generated from the - past history of - [SearchService.Search][google.cloud.discoveryengine.v1.SearchService.Search] - API calls. Do not use it when there is no traffic for - Search API. - - ``user-event`` - Using suggestions generated from - user-imported search events. - - ``document-completable`` - Using suggestions taken - directly from user-imported document fields marked as - completable. - - Default values: - - - ``document`` is the default model for regular dataStores. - - ``search-history`` is the default model for - [IndustryVertical.SITE_SEARCH][] dataStores. - user_pseudo_id (str): - A unique identifier for tracking visitors. For example, this - could be implemented with an HTTP cookie, which should be - able to uniquely identify a visitor on a single device. This - unique identifier should not change if the visitor logs in - or out of the website. - - This field should NOT have a fixed value such as - ``unknown_visitor``. - - This should be the same identifier as - [UserEvent.user_pseudo_id][google.cloud.discoveryengine.v1.UserEvent.user_pseudo_id] - and - [SearchRequest.user_pseudo_id][google.cloud.discoveryengine.v1.SearchRequest.user_pseudo_id]. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an ``INVALID_ARGUMENT`` error - is returned. - include_tail_suggestions (bool): - Indicates if tail suggestions should be - returned if there are no suggestions that match - the full query. Even if set to true, if there - are suggestions that match the full query, those - are returned and no tail suggestions are - returned. - """ - - data_store: str = proto.Field( - proto.STRING, - number=1, - ) - query: str = proto.Field( - proto.STRING, - number=2, - ) - query_model: str = proto.Field( - proto.STRING, - number=3, - ) - user_pseudo_id: str = proto.Field( - proto.STRING, - number=4, - ) - include_tail_suggestions: bool = proto.Field( - proto.BOOL, - number=5, - ) - - -class CompleteQueryResponse(proto.Message): - r"""Response message for - [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1.CompletionService.CompleteQuery] - method. - - Attributes: - query_suggestions (MutableSequence[google.cloud.discoveryengine_v1.types.CompleteQueryResponse.QuerySuggestion]): - Results of the matched query suggestions. The - result list is ordered and the first result is a - top suggestion. - tail_match_triggered (bool): - True if the returned suggestions are all tail suggestions. - - For tail matching to be triggered, include_tail_suggestions - in the request must be true and there must be no suggestions - that match the full query. - """ - - class QuerySuggestion(proto.Message): - r"""Suggestions as search queries. - - Attributes: - suggestion (str): - The suggestion for the query. - """ - - suggestion: str = proto.Field( - proto.STRING, - number=1, - ) - - query_suggestions: MutableSequence[QuerySuggestion] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=QuerySuggestion, - ) - tail_match_triggered: bool = proto.Field( - proto.BOOL, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/conversation.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/conversation.py deleted file mode 100644 index 9f24e918cc42..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/conversation.py +++ /dev/null @@ -1,204 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.discoveryengine_v1.types import search_service -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1', - manifest={ - 'Conversation', - 'Reply', - 'ConversationContext', - 'TextInput', - 'ConversationMessage', - }, -) - - -class Conversation(proto.Message): - r"""External conversation proto definition. - - Attributes: - name (str): - Immutable. Fully qualified name - ``project/*/locations/global/collections/{collection}/dataStore/*/conversations/*`` - state (google.cloud.discoveryengine_v1.types.Conversation.State): - The state of the Conversation. - user_pseudo_id (str): - A unique identifier for tracking users. - messages (MutableSequence[google.cloud.discoveryengine_v1.types.ConversationMessage]): - Conversation messages. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time the conversation - started. - end_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time the conversation - finished. - """ - class State(proto.Enum): - r"""Enumeration of the state of the conversation. - - Values: - STATE_UNSPECIFIED (0): - Unknown. - IN_PROGRESS (1): - Conversation is currently open. - COMPLETED (2): - Conversation has been completed. - """ - STATE_UNSPECIFIED = 0 - IN_PROGRESS = 1 - COMPLETED = 2 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - state: State = proto.Field( - proto.ENUM, - number=2, - enum=State, - ) - user_pseudo_id: str = proto.Field( - proto.STRING, - number=3, - ) - messages: MutableSequence['ConversationMessage'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='ConversationMessage', - ) - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - - -class Reply(proto.Message): - r"""Defines a reply message to user. - - Attributes: - summary (google.cloud.discoveryengine_v1.types.SearchResponse.Summary): - Summary based on search results. - """ - - summary: search_service.SearchResponse.Summary = proto.Field( - proto.MESSAGE, - number=3, - message=search_service.SearchResponse.Summary, - ) - - -class ConversationContext(proto.Message): - r"""Defines context of the conversation - - Attributes: - context_documents (MutableSequence[str]): - The current list of documents the user is - seeing. It contains the document resource - references. - active_document (str): - The current active document the user opened. - It contains the document resource reference. - """ - - context_documents: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - active_document: str = proto.Field( - proto.STRING, - number=2, - ) - - -class TextInput(proto.Message): - r"""Defines text input. - - Attributes: - input (str): - Text input. - context (google.cloud.discoveryengine_v1.types.ConversationContext): - Conversation context of the input. - """ - - input: str = proto.Field( - proto.STRING, - number=1, - ) - context: 'ConversationContext' = proto.Field( - proto.MESSAGE, - number=2, - message='ConversationContext', - ) - - -class ConversationMessage(proto.Message): - r"""Defines a conversation 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: - user_input (google.cloud.discoveryengine_v1.types.TextInput): - User text input. - - This field is a member of `oneof`_ ``message``. - reply (google.cloud.discoveryengine_v1.types.Reply): - Search reply. - - This field is a member of `oneof`_ ``message``. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Message creation timestamp. - """ - - user_input: 'TextInput' = proto.Field( - proto.MESSAGE, - number=1, - oneof='message', - message='TextInput', - ) - reply: 'Reply' = proto.Field( - proto.MESSAGE, - number=2, - oneof='message', - message='Reply', - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/conversational_search_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/conversational_search_service.py deleted file mode 100644 index 8666504225a4..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/conversational_search_service.py +++ /dev/null @@ -1,322 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.discoveryengine_v1.types import conversation as gcd_conversation -from google.cloud.discoveryengine_v1.types import search_service -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1', - manifest={ - 'ConverseConversationRequest', - 'ConverseConversationResponse', - 'CreateConversationRequest', - 'UpdateConversationRequest', - 'DeleteConversationRequest', - 'GetConversationRequest', - 'ListConversationsRequest', - 'ListConversationsResponse', - }, -) - - -class ConverseConversationRequest(proto.Message): - r"""Request message for - [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1.ConversationalSearchService.ConverseConversation] - method. - - Attributes: - name (str): - Required. The resource name of the Conversation to get. - Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}``. - Use - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/-`` - to activate auto session mode, which automatically creates a - new conversation inside a ConverseConversation session. - query (google.cloud.discoveryengine_v1.types.TextInput): - Required. Current user input. - serving_config (str): - The resource name of the Serving Config to use. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/servingConfigs/{serving_config_id}`` - If this is not set, the default serving config will be used. - conversation (google.cloud.discoveryengine_v1.types.Conversation): - The conversation to be used by auto session - only. The name field will be ignored as we - automatically assign new name for the - conversation in auto session. - safe_search (bool): - Whether to turn on safe search. - user_labels (MutableMapping[str, str]): - The user labels applied to a resource must meet the - following requirements: - - - Each resource can have multiple labels, up to a maximum - of 64. - - Each label must be a key-value pair. - - Keys have a minimum length of 1 character and a maximum - length of 63 characters and cannot be empty. Values can - be empty and have a maximum length of 63 characters. - - Keys and values can contain only lowercase letters, - numeric characters, underscores, and dashes. All - characters must use UTF-8 encoding, and international - characters are allowed. - - The key portion of a label must be unique. However, you - can use the same key with multiple resources. - - Keys must start with a lowercase letter or international - character. - - See `Google Cloud - Document `__ - for more details. - summary_spec (google.cloud.discoveryengine_v1.types.SearchRequest.ContentSearchSpec.SummarySpec): - A specification for configuring the summary - returned in the response. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - query: gcd_conversation.TextInput = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_conversation.TextInput, - ) - serving_config: str = proto.Field( - proto.STRING, - number=3, - ) - conversation: gcd_conversation.Conversation = proto.Field( - proto.MESSAGE, - number=5, - message=gcd_conversation.Conversation, - ) - safe_search: bool = proto.Field( - proto.BOOL, - number=6, - ) - user_labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=7, - ) - summary_spec: search_service.SearchRequest.ContentSearchSpec.SummarySpec = proto.Field( - proto.MESSAGE, - number=8, - message=search_service.SearchRequest.ContentSearchSpec.SummarySpec, - ) - - -class ConverseConversationResponse(proto.Message): - r"""Response message for - [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1.ConversationalSearchService.ConverseConversation] - method. - - Attributes: - reply (google.cloud.discoveryengine_v1.types.Reply): - Answer to the current query. - conversation (google.cloud.discoveryengine_v1.types.Conversation): - Updated conversation including the answer. - search_results (MutableSequence[google.cloud.discoveryengine_v1.types.SearchResponse.SearchResult]): - Search Results. - """ - - reply: gcd_conversation.Reply = proto.Field( - proto.MESSAGE, - number=1, - message=gcd_conversation.Reply, - ) - conversation: gcd_conversation.Conversation = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_conversation.Conversation, - ) - search_results: MutableSequence[search_service.SearchResponse.SearchResult] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=search_service.SearchResponse.SearchResult, - ) - - -class CreateConversationRequest(proto.Message): - r"""Request for CreateConversation method. - - Attributes: - parent (str): - Required. Full resource name of parent data store. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` - conversation (google.cloud.discoveryengine_v1.types.Conversation): - Required. The conversation to create. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - conversation: gcd_conversation.Conversation = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_conversation.Conversation, - ) - - -class UpdateConversationRequest(proto.Message): - r"""Request for UpdateConversation method. - - Attributes: - conversation (google.cloud.discoveryengine_v1.types.Conversation): - Required. The Conversation to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - [Conversation][google.cloud.discoveryengine.v1.Conversation] - to update. The following are NOT supported: - - - [conversation.name][] - - If not set or empty, all supported fields are updated. - """ - - conversation: gcd_conversation.Conversation = proto.Field( - proto.MESSAGE, - number=1, - message=gcd_conversation.Conversation, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteConversationRequest(proto.Message): - r"""Request for DeleteConversation method. - - Attributes: - name (str): - Required. The resource name of the Conversation to delete. - Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetConversationRequest(proto.Message): - r"""Request for GetConversation method. - - Attributes: - name (str): - Required. The resource name of the Conversation to get. - Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListConversationsRequest(proto.Message): - r"""Request for ListConversations method. - - Attributes: - parent (str): - Required. The data store resource name. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` - page_size (int): - Maximum number of results to return. If - unspecified, defaults to 50. Max allowed value - is 1000. - page_token (str): - A page token, received from a previous ``ListConversations`` - call. Provide this to retrieve the subsequent page. - filter (str): - A filter to apply on the list results. The supported - features are: user_pseudo_id, state. - - Example: "user_pseudo_id = some_id". - order_by (str): - A comma-separated list of fields to order by, sorted in - ascending order. Use "desc" after a field name for - descending. Supported fields: - - - ``update_time`` - - ``create_time`` - - ``conversation_name`` - - Example: "update_time desc" "create_time". - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - order_by: str = proto.Field( - proto.STRING, - number=5, - ) - - -class ListConversationsResponse(proto.Message): - r"""Response for ListConversations method. - - Attributes: - conversations (MutableSequence[google.cloud.discoveryengine_v1.types.Conversation]): - All the Conversations for a given data store. - next_page_token (str): - Pagination token, if not returned indicates - the last page. - """ - - @property - def raw_page(self): - return self - - conversations: MutableSequence[gcd_conversation.Conversation] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcd_conversation.Conversation, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/document.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/document.py deleted file mode 100644 index a53c978fb7b8..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/document.py +++ /dev/null @@ -1,189 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1', - manifest={ - 'Document', - }, -) - - -class Document(proto.Message): - r"""Document captures all raw metadata information of items to be - recommended or searched. - - 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: - struct_data (google.protobuf.struct_pb2.Struct): - The structured JSON data for the document. It should conform - to the registered - [Schema][google.cloud.discoveryengine.v1.Schema] or an - ``INVALID_ARGUMENT`` error is thrown. - - This field is a member of `oneof`_ ``data``. - json_data (str): - The JSON string representation of the document. It should - conform to the registered - [Schema][google.cloud.discoveryengine.v1.Schema] or an - ``INVALID_ARGUMENT`` error is thrown. - - This field is a member of `oneof`_ ``data``. - name (str): - Immutable. The full resource name of the document. Format: - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document_id}``. - - This field must be a UTF-8 encoded string with a length - limit of 1024 characters. - id (str): - Immutable. The identifier of the document. - - Id should conform to - `RFC-1034 `__ standard - with a length limit of 63 characters. - schema_id (str): - The identifier of the schema located in the - same data store. - content (google.cloud.discoveryengine_v1.types.Document.Content): - The unstructured data linked to this document. Content must - be set if this document is under a ``CONTENT_REQUIRED`` data - store. - parent_document_id (str): - The identifier of the parent document. Currently supports at - most two level document hierarchy. - - Id should conform to - `RFC-1034 `__ standard - with a length limit of 63 characters. - derived_struct_data (google.protobuf.struct_pb2.Struct): - Output only. This field is OUTPUT_ONLY. It contains derived - data that are not in the original input document. - """ - - class Content(proto.Message): - r"""Unstructured data linked to this document. - - 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: - raw_bytes (bytes): - The content represented as a stream of bytes. The maximum - length is 1,000,000 bytes (1 MB / ~0.95 MiB). - - Note: As with all ``bytes`` fields, this field is - represented as pure binary in Protocol Buffers and - base64-encoded string in JSON. For example, - ``abc123!?$*&()'-=@~`` should be represented as - ``YWJjMTIzIT8kKiYoKSctPUB+`` in JSON. See - https://developers.google.com/protocol-buffers/docs/proto3#json. - - This field is a member of `oneof`_ ``content``. - uri (str): - The URI of the content. Only Cloud Storage URIs (e.g. - ``gs://bucket-name/path/to/file``) are supported. The - maximum file size is 100 MB. - - This field is a member of `oneof`_ ``content``. - mime_type (str): - The MIME type of the content. Supported types: - - - ``application/pdf`` (PDF, only native PDFs are supported - for now) - - ``text/html`` (HTML) - - ``application/vnd.openxmlformats-officedocument.wordprocessingml.document`` - (DOCX) - - ``application/vnd.openxmlformats-officedocument.presentationml.presentation`` - (PPTX) - - ``text/plain`` (TXT) - - See - https://www.iana.org/assignments/media-types/media-types.xhtml. - """ - - raw_bytes: bytes = proto.Field( - proto.BYTES, - number=2, - oneof='content', - ) - uri: str = proto.Field( - proto.STRING, - number=3, - oneof='content', - ) - mime_type: str = proto.Field( - proto.STRING, - number=1, - ) - - struct_data: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=4, - oneof='data', - message=struct_pb2.Struct, - ) - json_data: str = proto.Field( - proto.STRING, - number=5, - oneof='data', - ) - name: str = proto.Field( - proto.STRING, - number=1, - ) - id: str = proto.Field( - proto.STRING, - number=2, - ) - schema_id: str = proto.Field( - proto.STRING, - number=3, - ) - content: Content = proto.Field( - proto.MESSAGE, - number=10, - message=Content, - ) - parent_document_id: str = proto.Field( - proto.STRING, - number=7, - ) - derived_struct_data: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=6, - message=struct_pb2.Struct, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/document_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/document_service.py deleted file mode 100644 index f998f8bef4c3..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/document_service.py +++ /dev/null @@ -1,262 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.discoveryengine_v1.types import document as gcd_document - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1', - manifest={ - 'GetDocumentRequest', - 'ListDocumentsRequest', - 'ListDocumentsResponse', - 'CreateDocumentRequest', - 'UpdateDocumentRequest', - 'DeleteDocumentRequest', - }, -) - - -class GetDocumentRequest(proto.Message): - r"""Request message for - [DocumentService.GetDocument][google.cloud.discoveryengine.v1.DocumentService.GetDocument] - method. - - Attributes: - name (str): - Required. Full resource name of - [Document][google.cloud.discoveryengine.v1.Document], such - as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. - - If the caller does not have permission to access the - [Document][google.cloud.discoveryengine.v1.Document], - regardless of whether or not it exists, a - ``PERMISSION_DENIED`` error is returned. - - If the requested - [Document][google.cloud.discoveryengine.v1.Document] does - not exist, a ``NOT_FOUND`` error is returned. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListDocumentsRequest(proto.Message): - r"""Request message for - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1.DocumentService.ListDocuments] - method. - - Attributes: - parent (str): - Required. The parent branch resource name, such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. - Use ``default_branch`` as the branch ID, to list documents - under the default branch. - - If the caller does not have permission to list - [Document][google.cloud.discoveryengine.v1.Document]s under - this branch, regardless of whether or not this branch - exists, a ``PERMISSION_DENIED`` error is returned. - page_size (int): - Maximum number of - [Document][google.cloud.discoveryengine.v1.Document]s to - return. If unspecified, defaults to 100. The maximum allowed - value is 1000. Values above 1000 will be coerced to 1000. - - If this field is negative, an ``INVALID_ARGUMENT`` error is - returned. - page_token (str): - A page token - [ListDocumentsResponse.next_page_token][google.cloud.discoveryengine.v1.ListDocumentsResponse.next_page_token], - received from a previous - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1.DocumentService.ListDocuments] - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1.DocumentService.ListDocuments] - must match the call that provided the page token. Otherwise, - an ``INVALID_ARGUMENT`` error is returned. - """ - - 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 ListDocumentsResponse(proto.Message): - r"""Response message for - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1.DocumentService.ListDocuments] - method. - - Attributes: - documents (MutableSequence[google.cloud.discoveryengine_v1.types.Document]): - The [Document][google.cloud.discoveryengine.v1.Document]s. - next_page_token (str): - A token that can be sent as - [ListDocumentsRequest.page_token][google.cloud.discoveryengine.v1.ListDocumentsRequest.page_token] - to retrieve the next page. If this field is omitted, there - are no subsequent pages. - """ - - @property - def raw_page(self): - return self - - documents: MutableSequence[gcd_document.Document] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcd_document.Document, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class CreateDocumentRequest(proto.Message): - r"""Request message for - [DocumentService.CreateDocument][google.cloud.discoveryengine.v1.DocumentService.CreateDocument] - method. - - Attributes: - parent (str): - Required. The parent resource name, such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. - document (google.cloud.discoveryengine_v1.types.Document): - Required. The - [Document][google.cloud.discoveryengine.v1.Document] to - create. - document_id (str): - Required. The ID to use for the - [Document][google.cloud.discoveryengine.v1.Document], which - will become the final component of the - [Document.name][google.cloud.discoveryengine.v1.Document.name]. - - If the caller does not have permission to create the - [Document][google.cloud.discoveryengine.v1.Document], - regardless of whether or not it exists, a - ``PERMISSION_DENIED`` error is returned. - - This field must be unique among all - [Document][google.cloud.discoveryengine.v1.Document]s with - the same - [parent][google.cloud.discoveryengine.v1.CreateDocumentRequest.parent]. - Otherwise, an ``ALREADY_EXISTS`` error is returned. - - This field must conform to - `RFC-1034 `__ standard - with a length limit of 63 characters. Otherwise, an - ``INVALID_ARGUMENT`` error is returned. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - document: gcd_document.Document = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_document.Document, - ) - document_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class UpdateDocumentRequest(proto.Message): - r"""Request message for - [DocumentService.UpdateDocument][google.cloud.discoveryengine.v1.DocumentService.UpdateDocument] - method. - - Attributes: - document (google.cloud.discoveryengine_v1.types.Document): - Required. The document to update/create. - - If the caller does not have permission to update the - [Document][google.cloud.discoveryengine.v1.Document], - regardless of whether or not it exists, a - ``PERMISSION_DENIED`` error is returned. - - If the [Document][google.cloud.discoveryengine.v1.Document] - to update does not exist and - [allow_missing][google.cloud.discoveryengine.v1.UpdateDocumentRequest.allow_missing] - is not set, a ``NOT_FOUND`` error is returned. - allow_missing (bool): - If set to true, and the - [Document][google.cloud.discoveryengine.v1.Document] is not - found, a new - [Document][google.cloud.discoveryengine.v1.Document] will be - created. - """ - - document: gcd_document.Document = proto.Field( - proto.MESSAGE, - number=1, - message=gcd_document.Document, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=2, - ) - - -class DeleteDocumentRequest(proto.Message): - r"""Request message for - [DocumentService.DeleteDocument][google.cloud.discoveryengine.v1.DocumentService.DeleteDocument] - method. - - Attributes: - name (str): - Required. Full resource name of - [Document][google.cloud.discoveryengine.v1.Document], such - as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. - - If the caller does not have permission to delete the - [Document][google.cloud.discoveryengine.v1.Document], - regardless of whether or not it exists, a - ``PERMISSION_DENIED`` error is returned. - - If the [Document][google.cloud.discoveryengine.v1.Document] - to delete does not exist, a ``NOT_FOUND`` error is returned. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/import_config.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/import_config.py deleted file mode 100644 index b5a383b3d8ad..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/import_config.py +++ /dev/null @@ -1,604 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.discoveryengine_v1.types import document -from google.cloud.discoveryengine_v1.types import user_event -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from google.type import date_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1', - manifest={ - 'GcsSource', - 'BigQuerySource', - 'ImportErrorConfig', - 'ImportUserEventsRequest', - 'ImportUserEventsResponse', - 'ImportUserEventsMetadata', - 'ImportDocumentsMetadata', - 'ImportDocumentsRequest', - 'ImportDocumentsResponse', - }, -) - - -class GcsSource(proto.Message): - r"""Cloud Storage location for input content. - - Attributes: - input_uris (MutableSequence[str]): - Required. Cloud Storage URIs to input files. URI can be up - to 2000 characters long. URIs can match the full object path - (for example, ``gs://bucket/directory/object.json``) or a - pattern matching one or more files, such as - ``gs://bucket/directory/*.json``. - - A request can contain at most 100 files (or 100,000 files if - ``data_schema`` is ``content``). Each file can be up to 2 GB - (or 100 MB if ``data_schema`` is ``content``). - data_schema (str): - The schema to use when parsing the data from the source. - - Supported values for document imports: - - - ``document`` (default): One JSON - [Document][google.cloud.discoveryengine.v1.Document] per - line. Each document must have a valid - [Document.id][google.cloud.discoveryengine.v1.Document.id]. - - ``content``: Unstructured data (e.g. PDF, HTML). Each - file matched by ``input_uris`` becomes a document, with - the ID set to the first 128 bits of SHA256(URI) encoded - as a hex string. - - ``custom``: One custom data JSON per row in arbitrary - format that conforms to the defined - [Schema][google.cloud.discoveryengine.v1.Schema] of the - data store. This can only be used by Gen App Builder. - - ``csv``: A CSV file with header conforming to the defined - [Schema][google.cloud.discoveryengine.v1.Schema] of the - data store. Each entry after the header is imported as a - Document. This can only be used by Gen App Builder. - - Supported values for user even imports: - - - ``user_event`` (default): One JSON - [UserEvent][google.cloud.discoveryengine.v1.UserEvent] - per line. - """ - - input_uris: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - data_schema: str = proto.Field( - proto.STRING, - number=2, - ) - - -class BigQuerySource(proto.Message): - r"""BigQuery source import data from. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - partition_date (google.type.date_pb2.Date): - BigQuery time partitioned table's \_PARTITIONDATE in - YYYY-MM-DD format. - - This field is a member of `oneof`_ ``partition``. - project_id (str): - The project ID (can be project # or ID) that - the BigQuery source is in with a length limit of - 128 characters. If not specified, inherits the - project ID from the parent request. - dataset_id (str): - Required. The BigQuery data set to copy the - data from with a length limit of 1,024 - characters. - table_id (str): - Required. The BigQuery table to copy the data - from with a length limit of 1,024 characters. - gcs_staging_dir (str): - Intermediate Cloud Storage directory used for - the import with a length limit of 2,000 - characters. Can be specified if one wants to - have the BigQuery export to a specific Cloud - Storage directory. - data_schema (str): - The schema to use when parsing the data from the source. - - Supported values for user event imports: - - - ``user_event`` (default): One - [UserEvent][google.cloud.discoveryengine.v1.UserEvent] - per row. - - Supported values for document imports: - - - ``document`` (default): One - [Document][google.cloud.discoveryengine.v1.Document] - format per row. Each document must have a valid - [Document.id][google.cloud.discoveryengine.v1.Document.id] - and one of - [Document.json_data][google.cloud.discoveryengine.v1.Document.json_data] - or - [Document.struct_data][google.cloud.discoveryengine.v1.Document.struct_data]. - - ``custom``: One custom data per row in arbitrary format - that conforms to the defined - [Schema][google.cloud.discoveryengine.v1.Schema] of the - data store. This can only be used by Gen App Builder. - """ - - partition_date: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=5, - oneof='partition', - message=date_pb2.Date, - ) - project_id: str = proto.Field( - proto.STRING, - number=1, - ) - dataset_id: str = proto.Field( - proto.STRING, - number=2, - ) - table_id: str = proto.Field( - proto.STRING, - number=3, - ) - gcs_staging_dir: str = proto.Field( - proto.STRING, - number=4, - ) - data_schema: str = proto.Field( - proto.STRING, - number=6, - ) - - -class ImportErrorConfig(proto.Message): - r"""Configuration of destination for Import related errors. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_prefix (str): - Cloud Storage prefix for import errors. This must be an - empty, existing Cloud Storage directory. Import errors are - written to sharded files in this directory, one per line, as - a JSON-encoded ``google.rpc.Status`` message. - - This field is a member of `oneof`_ ``destination``. - """ - - gcs_prefix: str = proto.Field( - proto.STRING, - number=1, - oneof='destination', - ) - - -class ImportUserEventsRequest(proto.Message): - r"""Request message for the ImportUserEvents request. - - 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: - inline_source (google.cloud.discoveryengine_v1.types.ImportUserEventsRequest.InlineSource): - The Inline source for the input content for - UserEvents. - - This field is a member of `oneof`_ ``source``. - gcs_source (google.cloud.discoveryengine_v1.types.GcsSource): - Cloud Storage location for the input content. - - This field is a member of `oneof`_ ``source``. - bigquery_source (google.cloud.discoveryengine_v1.types.BigQuerySource): - BigQuery input source. - - This field is a member of `oneof`_ ``source``. - parent (str): - Required. Parent DataStore resource name, of the form - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}`` - error_config (google.cloud.discoveryengine_v1.types.ImportErrorConfig): - The desired location of errors incurred - during the Import. Cannot be set for inline user - event imports. - """ - - class InlineSource(proto.Message): - r"""The inline source for the input config for ImportUserEvents - method. - - Attributes: - user_events (MutableSequence[google.cloud.discoveryengine_v1.types.UserEvent]): - Required. A list of user events to import. - Recommended max of 10k items. - """ - - user_events: MutableSequence[user_event.UserEvent] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=user_event.UserEvent, - ) - - inline_source: InlineSource = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message=InlineSource, - ) - gcs_source: 'GcsSource' = proto.Field( - proto.MESSAGE, - number=3, - oneof='source', - message='GcsSource', - ) - bigquery_source: 'BigQuerySource' = proto.Field( - proto.MESSAGE, - number=4, - oneof='source', - message='BigQuerySource', - ) - parent: str = proto.Field( - proto.STRING, - number=1, - ) - error_config: 'ImportErrorConfig' = proto.Field( - proto.MESSAGE, - number=5, - message='ImportErrorConfig', - ) - - -class ImportUserEventsResponse(proto.Message): - r"""Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is returned by the - google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (MutableSequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - error_config (google.cloud.discoveryengine_v1.types.ImportErrorConfig): - Echoes the destination for the complete - errors if this field was set in the request. - joined_events_count (int): - Count of user events imported with complete - existing Documents. - unjoined_events_count (int): - Count of user events imported, but with - Document information not found in the existing - Branch. - """ - - error_samples: MutableSequence[status_pb2.Status] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - error_config: 'ImportErrorConfig' = proto.Field( - proto.MESSAGE, - number=2, - message='ImportErrorConfig', - ) - joined_events_count: int = proto.Field( - proto.INT64, - number=3, - ) - unjoined_events_count: int = proto.Field( - proto.INT64, - number=4, - ) - - -class ImportUserEventsMetadata(proto.Message): - r"""Metadata related to the progress of the Import operation. - This is returned by the google.longrunning.Operation.metadata - field. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - success_count (int): - Count of entries that were processed - successfully. - failure_count (int): - Count of entries that encountered errors - while processing. - """ - - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - success_count: int = proto.Field( - proto.INT64, - number=3, - ) - failure_count: int = proto.Field( - proto.INT64, - number=4, - ) - - -class ImportDocumentsMetadata(proto.Message): - r"""Metadata related to the progress of the ImportDocuments - operation. This is returned by the - google.longrunning.Operation.metadata field. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - success_count (int): - Count of entries that were processed - successfully. - failure_count (int): - Count of entries that encountered errors - while processing. - """ - - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - success_count: int = proto.Field( - proto.INT64, - number=3, - ) - failure_count: int = proto.Field( - proto.INT64, - number=4, - ) - - -class ImportDocumentsRequest(proto.Message): - r"""Request message for Import methods. - - 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: - inline_source (google.cloud.discoveryengine_v1.types.ImportDocumentsRequest.InlineSource): - The Inline source for the input content for - documents. - - This field is a member of `oneof`_ ``source``. - gcs_source (google.cloud.discoveryengine_v1.types.GcsSource): - Cloud Storage location for the input content. - - This field is a member of `oneof`_ ``source``. - bigquery_source (google.cloud.discoveryengine_v1.types.BigQuerySource): - BigQuery input source. - - This field is a member of `oneof`_ ``source``. - parent (str): - Required. The parent branch resource name, such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. - Requires create/update permission. - error_config (google.cloud.discoveryengine_v1.types.ImportErrorConfig): - The desired location of errors incurred - during the Import. - reconciliation_mode (google.cloud.discoveryengine_v1.types.ImportDocumentsRequest.ReconciliationMode): - The mode of reconciliation between existing documents and - the documents to be imported. Defaults to - [ReconciliationMode.INCREMENTAL][google.cloud.discoveryengine.v1.ImportDocumentsRequest.ReconciliationMode.INCREMENTAL]. - auto_generate_ids (bool): - Whether to automatically generate IDs for the documents if - absent. - - If set to ``true``, - [Document.id][google.cloud.discoveryengine.v1.Document.id]s - are automatically generated based on the hash of the - payload, where IDs may not be consistent during multiple - imports. In which case - [ReconciliationMode.FULL][google.cloud.discoveryengine.v1.ImportDocumentsRequest.ReconciliationMode.FULL] - is highly recommended to avoid duplicate contents. If unset - or set to ``false``, - [Document.id][google.cloud.discoveryengine.v1.Document.id]s - have to be specified using - [id_field][google.cloud.discoveryengine.v1.ImportDocumentsRequest.id_field], - otherwise, documents without IDs fail to be imported. - - Only set this field when using - [GcsSource][google.cloud.discoveryengine.v1.GcsSource] or - [BigQuerySource][google.cloud.discoveryengine.v1.BigQuerySource], - and when - [GcsSource.data_schema][google.cloud.discoveryengine.v1.GcsSource.data_schema] - or - [BigQuerySource.data_schema][google.cloud.discoveryengine.v1.BigQuerySource.data_schema] - is ``custom`` or ``csv``. Otherwise, an INVALID_ARGUMENT - error is thrown. - id_field (str): - The field in the Cloud Storage and BigQuery sources that - indicates the unique IDs of the documents. - - For [GcsSource][google.cloud.discoveryengine.v1.GcsSource] - it is the key of the JSON field. For instance, ``my_id`` for - JSON ``{"my_id": "some_uuid"}``. For - [BigQuerySource][google.cloud.discoveryengine.v1.BigQuerySource] - it is the column name of the BigQuery table where the unique - ids are stored. - - The values of the JSON field or the BigQuery column are used - as the - [Document.id][google.cloud.discoveryengine.v1.Document.id]s. - The JSON field or the BigQuery column must be of string - type, and the values must be set as valid strings conform to - `RFC-1034 `__ with 1-63 - characters. Otherwise, documents without valid IDs fail to - be imported. - - Only set this field when using - [GcsSource][google.cloud.discoveryengine.v1.GcsSource] or - [BigQuerySource][google.cloud.discoveryengine.v1.BigQuerySource], - and when - [GcsSource.data_schema][google.cloud.discoveryengine.v1.GcsSource.data_schema] - or - [BigQuerySource.data_schema][google.cloud.discoveryengine.v1.BigQuerySource.data_schema] - is ``custom``. And only set this field when - [auto_generate_ids][google.cloud.discoveryengine.v1.ImportDocumentsRequest.auto_generate_ids] - is unset or set as ``false``. Otherwise, an INVALID_ARGUMENT - error is thrown. - - If it is unset, a default value ``_id`` is used when - importing from the allowed data sources. - """ - class ReconciliationMode(proto.Enum): - r"""Indicates how imported documents are reconciled with the - existing documents created or imported before. - - Values: - RECONCILIATION_MODE_UNSPECIFIED (0): - Defaults to ``INCREMENTAL``. - INCREMENTAL (1): - Inserts new documents or updates existing - documents. - FULL (2): - Calculates diff and replaces the entire - document dataset. Existing documents may be - deleted if they are not present in the source - location. - """ - RECONCILIATION_MODE_UNSPECIFIED = 0 - INCREMENTAL = 1 - FULL = 2 - - class InlineSource(proto.Message): - r"""The inline source for the input config for ImportDocuments - method. - - Attributes: - documents (MutableSequence[google.cloud.discoveryengine_v1.types.Document]): - Required. A list of documents to update/create. Each - document must have a valid - [Document.id][google.cloud.discoveryengine.v1.Document.id]. - Recommended max of 100 items. - """ - - documents: MutableSequence[document.Document] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=document.Document, - ) - - inline_source: InlineSource = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message=InlineSource, - ) - gcs_source: 'GcsSource' = proto.Field( - proto.MESSAGE, - number=3, - oneof='source', - message='GcsSource', - ) - bigquery_source: 'BigQuerySource' = proto.Field( - proto.MESSAGE, - number=4, - oneof='source', - message='BigQuerySource', - ) - parent: str = proto.Field( - proto.STRING, - number=1, - ) - error_config: 'ImportErrorConfig' = proto.Field( - proto.MESSAGE, - number=5, - message='ImportErrorConfig', - ) - reconciliation_mode: ReconciliationMode = proto.Field( - proto.ENUM, - number=6, - enum=ReconciliationMode, - ) - auto_generate_ids: bool = proto.Field( - proto.BOOL, - number=8, - ) - id_field: str = proto.Field( - proto.STRING, - number=9, - ) - - -class ImportDocumentsResponse(proto.Message): - r"""Response of the - [ImportDocumentsRequest][google.cloud.discoveryengine.v1.ImportDocumentsRequest]. - If the long running operation is done, then this message is returned - by the google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (MutableSequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - error_config (google.cloud.discoveryengine_v1.types.ImportErrorConfig): - Echoes the destination for the complete - errors in the request if set. - """ - - error_samples: MutableSequence[status_pb2.Status] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - error_config: 'ImportErrorConfig' = proto.Field( - proto.MESSAGE, - number=2, - message='ImportErrorConfig', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/purge_config.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/purge_config.py deleted file mode 100644 index 0a2d90e89a28..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/purge_config.py +++ /dev/null @@ -1,133 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1', - manifest={ - 'PurgeDocumentsRequest', - 'PurgeDocumentsResponse', - 'PurgeDocumentsMetadata', - }, -) - - -class PurgeDocumentsRequest(proto.Message): - r"""Request message for - [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1.DocumentService.PurgeDocuments] - method. - - Attributes: - parent (str): - Required. The parent resource name, such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. - filter (str): - Required. Filter matching documents to purge. Only currently - supported value is ``*`` (all items). - force (bool): - Actually performs the purge. If ``force`` is set to false, - return the expected purge count without deleting any - documents. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - force: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class PurgeDocumentsResponse(proto.Message): - r"""Response message for - [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1.DocumentService.PurgeDocuments] - method. If the long running operation is successfully done, then - this message is returned by the - google.longrunning.Operations.response field. - - Attributes: - purge_count (int): - The total count of documents purged as a - result of the operation. - purge_sample (MutableSequence[str]): - A sample of document names that will be deleted. Only - populated if ``force`` is set to false. A max of 100 names - will be returned and the names are chosen at random. - """ - - purge_count: int = proto.Field( - proto.INT64, - number=1, - ) - purge_sample: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class PurgeDocumentsMetadata(proto.Message): - r"""Metadata related to the progress of the PurgeDocuments - operation. This will be returned by the - google.longrunning.Operation.metadata field. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - success_count (int): - Count of entries that were deleted - successfully. - failure_count (int): - Count of entries that encountered errors - while processing. - """ - - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - success_count: int = proto.Field( - proto.INT64, - number=3, - ) - failure_count: int = proto.Field( - proto.INT64, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/schema.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/schema.py deleted file mode 100644 index a2ca29c61266..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/schema.py +++ /dev/null @@ -1,78 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1', - manifest={ - 'Schema', - }, -) - - -class Schema(proto.Message): - r"""Defines the structure and layout of a type of document data. - - 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: - struct_schema (google.protobuf.struct_pb2.Struct): - The structured representation of the schema. - - This field is a member of `oneof`_ ``schema``. - json_schema (str): - The JSON representation of the schema. - - This field is a member of `oneof`_ ``schema``. - name (str): - Immutable. The full resource name of the schema, in the - format of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. - - This field must be a UTF-8 encoded string with a length - limit of 1024 characters. - """ - - struct_schema: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=2, - oneof='schema', - message=struct_pb2.Struct, - ) - json_schema: str = proto.Field( - proto.STRING, - number=3, - oneof='schema', - ) - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/schema_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/schema_service.py deleted file mode 100644 index c5d4330960b1..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/schema_service.py +++ /dev/null @@ -1,289 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.discoveryengine_v1.types import schema as gcd_schema -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1', - manifest={ - 'GetSchemaRequest', - 'ListSchemasRequest', - 'ListSchemasResponse', - 'CreateSchemaRequest', - 'UpdateSchemaRequest', - 'DeleteSchemaRequest', - 'CreateSchemaMetadata', - 'UpdateSchemaMetadata', - 'DeleteSchemaMetadata', - }, -) - - -class GetSchemaRequest(proto.Message): - r"""Request message for - [SchemaService.GetSchema][google.cloud.discoveryengine.v1.SchemaService.GetSchema] - method. - - Attributes: - name (str): - Required. The full resource name of the schema, in the - format of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListSchemasRequest(proto.Message): - r"""Request message for - [SchemaService.ListSchemas][google.cloud.discoveryengine.v1.SchemaService.ListSchemas] - method. - - Attributes: - parent (str): - Required. The parent data store resource name, in the format - of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. - page_size (int): - The maximum number of - [Schema][google.cloud.discoveryengine.v1.Schema]s to return. - The service may return fewer than this value. - - If unspecified, at most 100 - [Schema][google.cloud.discoveryengine.v1.Schema]s will be - returned. - - The maximum value is 1000; values above 1000 will be coerced - to 1000. - page_token (str): - A page token, received from a previous - [SchemaService.ListSchemas][google.cloud.discoveryengine.v1.SchemaService.ListSchemas] - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - [SchemaService.ListSchemas][google.cloud.discoveryengine.v1.SchemaService.ListSchemas] - 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 ListSchemasResponse(proto.Message): - r"""Response message for - [SchemaService.ListSchemas][google.cloud.discoveryengine.v1.SchemaService.ListSchemas] - method. - - Attributes: - schemas (MutableSequence[google.cloud.discoveryengine_v1.types.Schema]): - The [Schema][google.cloud.discoveryengine.v1.Schema]s. - next_page_token (str): - A token that can be sent as - [ListSchemasRequest.page_token][google.cloud.discoveryengine.v1.ListSchemasRequest.page_token] - to retrieve the next page. If this field is omitted, there - are no subsequent pages. - """ - - @property - def raw_page(self): - return self - - schemas: MutableSequence[gcd_schema.Schema] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcd_schema.Schema, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class CreateSchemaRequest(proto.Message): - r"""Request message for - [SchemaService.CreateSchema][google.cloud.discoveryengine.v1.SchemaService.CreateSchema] - method. - - Attributes: - parent (str): - Required. The parent data store resource name, in the format - of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. - schema (google.cloud.discoveryengine_v1.types.Schema): - Required. The - [Schema][google.cloud.discoveryengine.v1.Schema] to create. - schema_id (str): - Required. The ID to use for the - [Schema][google.cloud.discoveryengine.v1.Schema], which will - become the final component of the - [Schema.name][google.cloud.discoveryengine.v1.Schema.name]. - - This field should conform to - `RFC-1034 `__ standard - with a length limit of 63 characters. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - schema: gcd_schema.Schema = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_schema.Schema, - ) - schema_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class UpdateSchemaRequest(proto.Message): - r"""Request message for - [SchemaService.UpdateSchema][google.cloud.discoveryengine.v1.SchemaService.UpdateSchema] - method. - - Attributes: - schema (google.cloud.discoveryengine_v1.types.Schema): - Required. The - [Schema][google.cloud.discoveryengine.v1.Schema] to update. - allow_missing (bool): - If set to true, and the - [Schema][google.cloud.discoveryengine.v1.Schema] is not - found, a new - [Schema][google.cloud.discoveryengine.v1.Schema] will be - created. In this situation, ``update_mask`` is ignored. - """ - - schema: gcd_schema.Schema = proto.Field( - proto.MESSAGE, - number=1, - message=gcd_schema.Schema, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class DeleteSchemaRequest(proto.Message): - r"""Request message for - [SchemaService.DeleteSchema][google.cloud.discoveryengine.v1.SchemaService.DeleteSchema] - method. - - Attributes: - name (str): - Required. The full resource name of the schema, in the - format of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateSchemaMetadata(proto.Message): - r"""Metadata for Create Schema LRO. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - """ - - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - -class UpdateSchemaMetadata(proto.Message): - r"""Metadata for UpdateSchema LRO. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - """ - - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - -class DeleteSchemaMetadata(proto.Message): - r"""Metadata for DeleteSchema LRO. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - """ - - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/search_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/search_service.py deleted file mode 100644 index b1189fdf4dc5..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/search_service.py +++ /dev/null @@ -1,1089 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.discoveryengine_v1.types import common -from google.cloud.discoveryengine_v1.types import document as gcd_document -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1', - manifest={ - 'SearchRequest', - 'SearchResponse', - }, -) - - -class SearchRequest(proto.Message): - r"""Request message for - [SearchService.Search][google.cloud.discoveryengine.v1.SearchService.Search] - method. - - Attributes: - serving_config (str): - Required. The resource name of the Search serving config, - such as - ``projects/*/locations/global/collections/default_collection/dataStores/default_data_store/servingConfigs/default_serving_config``. - This field is used to identify the serving configuration - name, set of models used to make the search. - branch (str): - The branch resource name, such as - ``projects/*/locations/global/collections/default_collection/dataStores/default_data_store/branches/0``. - - Use ``default_branch`` as the branch ID or leave this field - empty, to search documents under the default branch. - query (str): - Raw search query. - image_query (google.cloud.discoveryengine_v1.types.SearchRequest.ImageQuery): - Raw image query. - page_size (int): - Maximum number of - [Document][google.cloud.discoveryengine.v1.Document]s to - return. If unspecified, defaults to a reasonable value. The - maximum allowed value is 100. Values above 100 are coerced - to 100. - - If this field is negative, an ``INVALID_ARGUMENT`` is - returned. - page_token (str): - A page token received from a previous - [SearchService.Search][google.cloud.discoveryengine.v1.SearchService.Search] - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - [SearchService.Search][google.cloud.discoveryengine.v1.SearchService.Search] - must match the call that provided the page token. Otherwise, - an ``INVALID_ARGUMENT`` error is returned. - offset (int): - A 0-indexed integer that specifies the current offset (that - is, starting result location, amongst the - [Document][google.cloud.discoveryengine.v1.Document]s deemed - by the API as relevant) in search results. This field is - only considered if - [page_token][google.cloud.discoveryengine.v1.SearchRequest.page_token] - is unset. - - If this field is negative, an ``INVALID_ARGUMENT`` is - returned. - filter (str): - The filter syntax consists of an expression language for - constructing a predicate from one or more fields of the - documents being filtered. Filter expression is - case-sensitive. - - If this field is unrecognizable, an ``INVALID_ARGUMENT`` is - returned. - order_by (str): - The order in which documents are returned. Documents can be - ordered by a field in an - [Document][google.cloud.discoveryengine.v1.Document] object. - Leave it unset if ordered by relevance. ``order_by`` - expression is case-sensitive. - - If this field is unrecognizable, an ``INVALID_ARGUMENT`` is - returned. - user_info (google.cloud.discoveryengine_v1.types.UserInfo): - Information about the end user. Highly recommended for - analytics. - [UserInfo.user_agent][google.cloud.discoveryengine.v1.UserInfo.user_agent] - is used to deduce ``device_type`` for analytics. - facet_specs (MutableSequence[google.cloud.discoveryengine_v1.types.SearchRequest.FacetSpec]): - Facet specifications for faceted search. If empty, no facets - are returned. - - A maximum of 100 values are allowed. Otherwise, an - ``INVALID_ARGUMENT`` error is returned. - boost_spec (google.cloud.discoveryengine_v1.types.SearchRequest.BoostSpec): - Boost specification to boost certain - documents. - params (MutableMapping[str, google.protobuf.struct_pb2.Value]): - Additional search parameters. - - For public website search only, supported values are: - - - ``user_country_code``: string. Default empty. If set to - non-empty, results are restricted or boosted based on the - location provided. - - ``search_type``: double. Default empty. Enables - non-webpage searching depending on the value. The only - valid non-default value is 1, which enables image - searching. - query_expansion_spec (google.cloud.discoveryengine_v1.types.SearchRequest.QueryExpansionSpec): - The query expansion specification that - specifies the conditions under which query - expansion occurs. - spell_correction_spec (google.cloud.discoveryengine_v1.types.SearchRequest.SpellCorrectionSpec): - The spell correction specification that - specifies the mode under which spell correction - takes effect. - user_pseudo_id (str): - A unique identifier for tracking visitors. For example, this - could be implemented with an HTTP cookie, which should be - able to uniquely identify a visitor on a single device. This - unique identifier should not change if the visitor logs in - or out of the website. - - This field should NOT have a fixed value such as - ``unknown_visitor``. - - This should be the same identifier as - [UserEvent.user_pseudo_id][google.cloud.discoveryengine.v1.UserEvent.user_pseudo_id] - and - [CompleteQueryRequest.user_pseudo_id][google.cloud.discoveryengine.v1.CompleteQueryRequest.user_pseudo_id] - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an ``INVALID_ARGUMENT`` error - is returned. - content_search_spec (google.cloud.discoveryengine_v1.types.SearchRequest.ContentSearchSpec): - A specification for configuring the behavior - of content search. - safe_search (bool): - Whether to turn on safe search. This is only - supported for website search. - user_labels (MutableMapping[str, str]): - The user labels applied to a resource must meet the - following requirements: - - - Each resource can have multiple labels, up to a maximum - of 64. - - Each label must be a key-value pair. - - Keys have a minimum length of 1 character and a maximum - length of 63 characters and cannot be empty. Values can - be empty and have a maximum length of 63 characters. - - Keys and values can contain only lowercase letters, - numeric characters, underscores, and dashes. All - characters must use UTF-8 encoding, and international - characters are allowed. - - The key portion of a label must be unique. However, you - can use the same key with multiple resources. - - Keys must start with a lowercase letter or international - character. - - See `Google Cloud - Document `__ - for more details. - """ - - class ImageQuery(proto.Message): - r"""Specifies the image query input. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - image_bytes (str): - Base64 encoded image bytes. Supported image - formats: JPEG, PNG, and BMP. - - This field is a member of `oneof`_ ``image``. - """ - - image_bytes: str = proto.Field( - proto.STRING, - number=1, - oneof='image', - ) - - class FacetSpec(proto.Message): - r"""A facet specification to perform faceted search. - - Attributes: - facet_key (google.cloud.discoveryengine_v1.types.SearchRequest.FacetSpec.FacetKey): - Required. The facet key specification. - limit (int): - Maximum of facet values that should be returned for this - facet. If unspecified, defaults to 20. The maximum allowed - value is 300. Values above 300 are coerced to 300. - - If this field is negative, an ``INVALID_ARGUMENT`` is - returned. - excluded_filter_keys (MutableSequence[str]): - List of keys to exclude when faceting. - - By default, - [FacetKey.key][google.cloud.discoveryengine.v1.SearchRequest.FacetSpec.FacetKey.key] - is not excluded from the filter unless it is listed in this - field. - - Listing a facet key in this field allows its values to - appear as facet results, even when they are filtered out of - search results. Using this field does not affect what search - results are returned. - - For example, suppose there are 100 documents with the color - facet "Red" and 200 documents with the color facet "Blue". A - query containing the filter "color:ANY("Red")" and having - "color" as - [FacetKey.key][google.cloud.discoveryengine.v1.SearchRequest.FacetSpec.FacetKey.key] - would by default return only "Red" documents in the search - results, and also return "Red" with count 100 as the only - color facet. Although there are also blue documents - available, "Blue" would not be shown as an available facet - value. - - If "color" is listed in "excludedFilterKeys", then the query - returns the facet values "Red" with count 100 and "Blue" - with count 200, because the "color" key is now excluded from - the filter. Because this field doesn't affect search - results, the search results are still correctly filtered to - return only "Red" documents. - - A maximum of 100 values are allowed. Otherwise, an - ``INVALID_ARGUMENT`` error is returned. - enable_dynamic_position (bool): - Enables dynamic position for this facet. If set to true, the - position of this facet among all facets in the response is - determined automatically. If dynamic facets are enabled, it - is ordered together. If set to false, the position of this - facet in the response is the same as in the request, and it - is ranked before the facets with dynamic position enable and - all dynamic facets. - - For example, you may always want to have rating facet - returned in the response, but it's not necessarily to always - display the rating facet at the top. In that case, you can - set enable_dynamic_position to true so that the position of - rating facet in response is determined automatically. - - Another example, assuming you have the following facets in - the request: - - - "rating", enable_dynamic_position = true - - - "price", enable_dynamic_position = false - - - "brands", enable_dynamic_position = false - - And also you have a dynamic facets enabled, which generates - a facet ``gender``. Then the final order of the facets in - the response can be ("price", "brands", "rating", "gender") - or ("price", "brands", "gender", "rating") depends on how - API orders "gender" and "rating" facets. However, notice - that "price" and "brands" are always ranked at first and - second position because their enable_dynamic_position is - false. - """ - - class FacetKey(proto.Message): - r"""Specifies how a facet is computed. - - Attributes: - key (str): - Required. Supported textual and numerical facet keys in - [Document][google.cloud.discoveryengine.v1.Document] object, - over which the facet values are computed. Facet key is - case-sensitive. - intervals (MutableSequence[google.cloud.discoveryengine_v1.types.Interval]): - Set only if values should be bucketed into - intervals. Must be set for facets with numerical - values. Must not be set for facet with text - values. Maximum number of intervals is 30. - restricted_values (MutableSequence[str]): - Only get facet for the given restricted values. Only - supported on textual fields. For example, suppose "category" - has three values "Action > 2022", "Action > 2021" and - "Sci-Fi > 2022". If set "restricted_values" to "Action > - 2022", the "category" facet only contains "Action > 2022". - Only supported on textual fields. Maximum is 10. - prefixes (MutableSequence[str]): - Only get facet values that start with the - given string prefix. For example, suppose - "category" has three values "Action > 2022", - "Action > 2021" and "Sci-Fi > 2022". If set - "prefixes" to "Action", the "category" facet - only contains "Action > 2022" and "Action > - 2021". Only supported on textual fields. Maximum - is 10. - contains (MutableSequence[str]): - Only get facet values that contains the given - strings. For example, suppose "category" has - three values "Action > 2022", "Action > 2021" - and "Sci-Fi > 2022". If set "contains" to - "2022", the "category" facet only contains - "Action > 2022" and "Sci-Fi > 2022". Only - supported on textual fields. Maximum is 10. - case_insensitive (bool): - True to make facet keys case insensitive when - getting faceting values with prefixes or - contains; false otherwise. - order_by (str): - The order in which documents are returned. - - Allowed values are: - - - "count desc", which means order by - [SearchResponse.Facet.values.count][google.cloud.discoveryengine.v1.SearchResponse.Facet.FacetValue.count] - descending. - - - "value desc", which means order by - [SearchResponse.Facet.values.value][google.cloud.discoveryengine.v1.SearchResponse.Facet.FacetValue.value] - descending. Only applies to textual facets. - - If not set, textual values are sorted in `natural - order `__; - numerical intervals are sorted in the order given by - [FacetSpec.FacetKey.intervals][google.cloud.discoveryengine.v1.SearchRequest.FacetSpec.FacetKey.intervals]. - """ - - key: str = proto.Field( - proto.STRING, - number=1, - ) - intervals: MutableSequence[common.Interval] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=common.Interval, - ) - restricted_values: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - prefixes: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - contains: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - case_insensitive: bool = proto.Field( - proto.BOOL, - number=6, - ) - order_by: str = proto.Field( - proto.STRING, - number=7, - ) - - facet_key: 'SearchRequest.FacetSpec.FacetKey' = proto.Field( - proto.MESSAGE, - number=1, - message='SearchRequest.FacetSpec.FacetKey', - ) - limit: int = proto.Field( - proto.INT32, - number=2, - ) - excluded_filter_keys: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - enable_dynamic_position: bool = proto.Field( - proto.BOOL, - number=4, - ) - - class BoostSpec(proto.Message): - r"""Boost specification to boost certain documents. - - Attributes: - condition_boost_specs (MutableSequence[google.cloud.discoveryengine_v1.types.SearchRequest.BoostSpec.ConditionBoostSpec]): - Condition boost specifications. If a document - matches multiple conditions in the - specifictions, boost scores from these - specifications are all applied and combined in a - non-linear way. Maximum number of specifications - is 20. - """ - - class ConditionBoostSpec(proto.Message): - r"""Boost applies to documents which match a condition. - - Attributes: - condition (str): - An expression which specifies a boost condition. The syntax - and supported fields are the same as a filter expression. - See - [SearchRequest.filter][google.cloud.discoveryengine.v1.SearchRequest.filter] - for detail syntax and limitations. - - Examples: - - - To boost documents with document ID "doc_1" or "doc_2", - and color "Red" or "Blue": - - - (id: ANY("doc_1", "doc_2")) AND (color: - ANY("Red","Blue")) - boost (float): - Strength of the condition boost, which should be in [-1, 1]. - Negative boost means demotion. Default is 0.0. - - Setting to 1.0 gives the document a big promotion. However, - it does not necessarily mean that the boosted document will - be the top result at all times, nor that other documents - will be excluded. Results could still be shown even when - none of them matches the condition. And results that are - significantly more relevant to the search query can still - trump your heavily favored but irrelevant documents. - - Setting to -1.0 gives the document a big demotion. However, - results that are deeply relevant might still be shown. The - document will have an upstream battle to get a fairly high - ranking, but it is not blocked out completely. - - Setting to 0.0 means no boost applied. The boosting - condition is ignored. - """ - - condition: str = proto.Field( - proto.STRING, - number=1, - ) - boost: float = proto.Field( - proto.FLOAT, - number=2, - ) - - condition_boost_specs: MutableSequence['SearchRequest.BoostSpec.ConditionBoostSpec'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SearchRequest.BoostSpec.ConditionBoostSpec', - ) - - class QueryExpansionSpec(proto.Message): - r"""Specification to determine under which conditions query - expansion should occur. - - Attributes: - condition (google.cloud.discoveryengine_v1.types.SearchRequest.QueryExpansionSpec.Condition): - The condition under which query expansion should occur. - Default to - [Condition.DISABLED][google.cloud.discoveryengine.v1.SearchRequest.QueryExpansionSpec.Condition.DISABLED]. - pin_unexpanded_results (bool): - Whether to pin unexpanded results. If this - field is set to true, unexpanded products are - always at the top of the search results, - followed by the expanded results. - """ - class Condition(proto.Enum): - r"""Enum describing under which condition query expansion should - occur. - - Values: - CONDITION_UNSPECIFIED (0): - Unspecified query expansion condition. In this case, server - behavior defaults to - [Condition.DISABLED][google.cloud.discoveryengine.v1.SearchRequest.QueryExpansionSpec.Condition.DISABLED]. - DISABLED (1): - Disabled query expansion. Only the exact search query is - used, even if - [SearchResponse.total_size][google.cloud.discoveryengine.v1.SearchResponse.total_size] - is zero. - AUTO (2): - Automatic query expansion built by the Search - API. - """ - CONDITION_UNSPECIFIED = 0 - DISABLED = 1 - AUTO = 2 - - condition: 'SearchRequest.QueryExpansionSpec.Condition' = proto.Field( - proto.ENUM, - number=1, - enum='SearchRequest.QueryExpansionSpec.Condition', - ) - pin_unexpanded_results: bool = proto.Field( - proto.BOOL, - number=2, - ) - - class SpellCorrectionSpec(proto.Message): - r"""The specification for query spell correction. - - Attributes: - mode (google.cloud.discoveryengine_v1.types.SearchRequest.SpellCorrectionSpec.Mode): - The mode under which spell correction should take effect to - replace the original search query. Default to - [Mode.AUTO][google.cloud.discoveryengine.v1.SearchRequest.SpellCorrectionSpec.Mode.AUTO]. - """ - class Mode(proto.Enum): - r"""Enum describing under which mode spell correction should - occur. - - Values: - MODE_UNSPECIFIED (0): - Unspecified spell correction mode. In this case, server - behavior defaults to - [Mode.AUTO][google.cloud.discoveryengine.v1.SearchRequest.SpellCorrectionSpec.Mode.AUTO]. - SUGGESTION_ONLY (1): - Search API will try to find a spell suggestion if there is - any and put in the - [SearchResponse.corrected_query][google.cloud.discoveryengine.v1.SearchResponse.corrected_query]. - The spell suggestion will not be used as the search query. - AUTO (2): - Automatic spell correction built by the - Search API. Search will be based on the - corrected query if found. - """ - MODE_UNSPECIFIED = 0 - SUGGESTION_ONLY = 1 - AUTO = 2 - - mode: 'SearchRequest.SpellCorrectionSpec.Mode' = proto.Field( - proto.ENUM, - number=1, - enum='SearchRequest.SpellCorrectionSpec.Mode', - ) - - class ContentSearchSpec(proto.Message): - r"""A specification for configuring the behavior of content - search. - - Attributes: - snippet_spec (google.cloud.discoveryengine_v1.types.SearchRequest.ContentSearchSpec.SnippetSpec): - If ``snippetSpec`` is not specified, snippets are not - included in the search response. - summary_spec (google.cloud.discoveryengine_v1.types.SearchRequest.ContentSearchSpec.SummarySpec): - If ``summarySpec`` is not specified, summaries are not - included in the search response. - """ - - class SnippetSpec(proto.Message): - r"""A specification for configuring snippets in a search - response. - - Attributes: - max_snippet_count (int): - [DEPRECATED] This field is deprecated. To control snippet - return, use ``return_snippet`` field. For backwards - compatibility, we will return snippet if max_snippet_count > - 0. - reference_only (bool): - [DEPRECATED] This field is deprecated and will have no - affect on the snippet. - return_snippet (bool): - If ``true``, then return snippet. If no snippet can be - generated, we return "No snippet is available for this - page." A ``snippet_status`` with ``SUCCESS`` or - ``NO_SNIPPET_AVAILABLE`` will also be returned. - """ - - max_snippet_count: int = proto.Field( - proto.INT32, - number=1, - ) - reference_only: bool = proto.Field( - proto.BOOL, - number=2, - ) - return_snippet: bool = proto.Field( - proto.BOOL, - number=3, - ) - - class SummarySpec(proto.Message): - r"""A specification for configuring a summary returned in a - search response. - - Attributes: - summary_result_count (int): - The number of top results to generate the summary from. If - the number of results returned is less than - ``summaryResultCount``, the summary is generated from all of - the results. - - At most five results can be used to generate a summary. - include_citations (bool): - Specifies whether to include citations in the summary. The - default value is ``false``. - - When this field is set to ``true``, summaries include - in-line citation numbers. - - Example summary including citations: - - BigQuery is Google Cloud's fully managed and completely - serverless enterprise data warehouse [1]. BigQuery supports - all data types, works across clouds, and has built-in - machine learning and business intelligence, all within a - unified platform [2, 3]. - - The citation numbers refer to the returned search results - and are 1-indexed. For example, [1] means that the sentence - is attributed to the first search result. [2, 3] means that - the sentence is attributed to both the second and third - search results. - ignore_adversarial_query (bool): - Specifies whether to filter out adversarial queries. The - default value is ``false``. - - Google employs search-query classification to detect - adversarial queries. No summary is returned if the search - query is classified as an adversarial query. For example, a - user might ask a question regarding negative comments about - the company or submit a query designed to generate unsafe, - policy-violating output. If this field is set to ``true``, - we skip generating summaries for adversarial queries and - return fallback messages instead. - ignore_non_summary_seeking_query (bool): - Specifies whether to filter out queries that are not - summary-seeking. The default value is ``false``. - - Google employs search-query classification to detect - summary-seeking queries. No summary is returned if the - search query is classified as a non-summary seeking query. - For example, ``why is the sky blue`` and - ``Who is the best soccer player in the world?`` are - summary-seeking queries, but ``SFO airport`` and - ``world cup 2026`` are not. They are most likely - navigational queries. If this field is set to ``true``, we - skip generating summaries for non-summary seeking queries - and return fallback messages instead. - language_code (str): - Language code for Summary. Use language tags defined by - [BCP47][https://www.rfc-editor.org/rfc/bcp/bcp47.txt]. - """ - - summary_result_count: int = proto.Field( - proto.INT32, - number=1, - ) - include_citations: bool = proto.Field( - proto.BOOL, - number=2, - ) - ignore_adversarial_query: bool = proto.Field( - proto.BOOL, - number=3, - ) - ignore_non_summary_seeking_query: bool = proto.Field( - proto.BOOL, - number=4, - ) - language_code: str = proto.Field( - proto.STRING, - number=6, - ) - - snippet_spec: 'SearchRequest.ContentSearchSpec.SnippetSpec' = proto.Field( - proto.MESSAGE, - number=1, - message='SearchRequest.ContentSearchSpec.SnippetSpec', - ) - summary_spec: 'SearchRequest.ContentSearchSpec.SummarySpec' = proto.Field( - proto.MESSAGE, - number=2, - message='SearchRequest.ContentSearchSpec.SummarySpec', - ) - - serving_config: str = proto.Field( - proto.STRING, - number=1, - ) - branch: str = proto.Field( - proto.STRING, - number=2, - ) - query: str = proto.Field( - proto.STRING, - number=3, - ) - image_query: ImageQuery = proto.Field( - proto.MESSAGE, - number=19, - message=ImageQuery, - ) - page_size: int = proto.Field( - proto.INT32, - number=4, - ) - page_token: str = proto.Field( - proto.STRING, - number=5, - ) - offset: int = proto.Field( - proto.INT32, - number=6, - ) - filter: str = proto.Field( - proto.STRING, - number=7, - ) - order_by: str = proto.Field( - proto.STRING, - number=8, - ) - user_info: common.UserInfo = proto.Field( - proto.MESSAGE, - number=21, - message=common.UserInfo, - ) - facet_specs: MutableSequence[FacetSpec] = proto.RepeatedField( - proto.MESSAGE, - number=9, - message=FacetSpec, - ) - boost_spec: BoostSpec = proto.Field( - proto.MESSAGE, - number=10, - message=BoostSpec, - ) - params: MutableMapping[str, struct_pb2.Value] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=11, - message=struct_pb2.Value, - ) - query_expansion_spec: QueryExpansionSpec = proto.Field( - proto.MESSAGE, - number=13, - message=QueryExpansionSpec, - ) - spell_correction_spec: SpellCorrectionSpec = proto.Field( - proto.MESSAGE, - number=14, - message=SpellCorrectionSpec, - ) - user_pseudo_id: str = proto.Field( - proto.STRING, - number=15, - ) - content_search_spec: ContentSearchSpec = proto.Field( - proto.MESSAGE, - number=24, - message=ContentSearchSpec, - ) - safe_search: bool = proto.Field( - proto.BOOL, - number=20, - ) - user_labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=22, - ) - - -class SearchResponse(proto.Message): - r"""Response message for - [SearchService.Search][google.cloud.discoveryengine.v1.SearchService.Search] - method. - - Attributes: - results (MutableSequence[google.cloud.discoveryengine_v1.types.SearchResponse.SearchResult]): - A list of matched documents. The order - represents the ranking. - facets (MutableSequence[google.cloud.discoveryengine_v1.types.SearchResponse.Facet]): - Results of facets requested by user. - total_size (int): - The estimated total count of matched items irrespective of - pagination. The count of - [results][google.cloud.discoveryengine.v1.SearchResponse.results] - returned by pagination may be less than the - [total_size][google.cloud.discoveryengine.v1.SearchResponse.total_size] - that matches. - attribution_token (str): - A unique search token. This should be included in the - [UserEvent][google.cloud.discoveryengine.v1.UserEvent] logs - resulting from this search, which enables accurate - attribution of search model performance. - redirect_uri (str): - The URI of a customer-defined redirect page. If redirect - action is triggered, no search is performed, and only - [redirect_uri][google.cloud.discoveryengine.v1.SearchResponse.redirect_uri] - and - [attribution_token][google.cloud.discoveryengine.v1.SearchResponse.attribution_token] - are set in the response. - next_page_token (str): - A token that can be sent as - [SearchRequest.page_token][google.cloud.discoveryengine.v1.SearchRequest.page_token] - to retrieve the next page. If this field is omitted, there - are no subsequent pages. - corrected_query (str): - Contains the spell corrected query, if found. If the spell - correction type is AUTOMATIC, then the search results are - based on corrected_query. Otherwise the original query is - used for search. - summary (google.cloud.discoveryengine_v1.types.SearchResponse.Summary): - A summary as part of the search results. This field is only - returned if - [SearchRequest.ContentSearchSpec.summary_spec][google.cloud.discoveryengine.v1.SearchRequest.ContentSearchSpec.summary_spec] - is set. - query_expansion_info (google.cloud.discoveryengine_v1.types.SearchResponse.QueryExpansionInfo): - Query expansion information for the returned - results. - """ - - class SearchResult(proto.Message): - r"""Represents the search results. - - Attributes: - id (str): - [Document.id][google.cloud.discoveryengine.v1.Document.id] - of the searched - [Document][google.cloud.discoveryengine.v1.Document]. - document (google.cloud.discoveryengine_v1.types.Document): - The document data snippet in the search - response. Only fields that are marked as - retrievable are populated. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - document: gcd_document.Document = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_document.Document, - ) - - class Facet(proto.Message): - r"""A facet result. - - Attributes: - key (str): - The key for this facet. E.g., "colors" or "price". It - matches - [SearchRequest.FacetSpec.FacetKey.key][google.cloud.discoveryengine.v1.SearchRequest.FacetSpec.FacetKey.key]. - values (MutableSequence[google.cloud.discoveryengine_v1.types.SearchResponse.Facet.FacetValue]): - The facet values for this field. - dynamic_facet (bool): - Whether the facet is dynamically generated. - """ - - class FacetValue(proto.Message): - r"""A facet value which contains value names and their count. - - 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: - value (str): - Text value of a facet, such as "Black" for - facet "colors". - - This field is a member of `oneof`_ ``facet_value``. - interval (google.cloud.discoveryengine_v1.types.Interval): - Interval value for a facet, such as [10, 20) for facet - "price". It matches - [SearchRequest.FacetSpec.FacetKey.intervals][google.cloud.discoveryengine.v1.SearchRequest.FacetSpec.FacetKey.intervals]. - - This field is a member of `oneof`_ ``facet_value``. - count (int): - Number of items that have this facet value. - """ - - value: str = proto.Field( - proto.STRING, - number=1, - oneof='facet_value', - ) - interval: common.Interval = proto.Field( - proto.MESSAGE, - number=2, - oneof='facet_value', - message=common.Interval, - ) - count: int = proto.Field( - proto.INT64, - number=3, - ) - - key: str = proto.Field( - proto.STRING, - number=1, - ) - values: MutableSequence['SearchResponse.Facet.FacetValue'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='SearchResponse.Facet.FacetValue', - ) - dynamic_facet: bool = proto.Field( - proto.BOOL, - number=3, - ) - - class Summary(proto.Message): - r"""Summary of the top N search result specified by the summary - spec. - - Attributes: - summary_text (str): - The summary content. - summary_skipped_reasons (MutableSequence[google.cloud.discoveryengine_v1.types.SearchResponse.Summary.SummarySkippedReason]): - Additional summary-skipped reasons. This - provides the reason for ignored cases. If - nothing is skipped, this field is not set. - safety_attributes (google.cloud.discoveryengine_v1.types.SearchResponse.Summary.SafetyAttributes): - A collection of Safety Attribute categories - and their associated confidence scores. - """ - class SummarySkippedReason(proto.Enum): - r"""An Enum for summary-skipped reasons. - - Values: - SUMMARY_SKIPPED_REASON_UNSPECIFIED (0): - Default value. The summary skipped reason is - not specified. - ADVERSARIAL_QUERY_IGNORED (1): - The adversarial query ignored case. - - Only populated when - [SummarySpec.ignore_adversarial_query][google.cloud.discoveryengine.v1.SearchRequest.ContentSearchSpec.SummarySpec.ignore_adversarial_query] - is set to ``true``. - NON_SUMMARY_SEEKING_QUERY_IGNORED (2): - The non-summary seeking query ignored case. - - Only populated when - [SummarySpec.ignore_non_summary_seeking_query][google.cloud.discoveryengine.v1.SearchRequest.ContentSearchSpec.SummarySpec.ignore_non_summary_seeking_query] - is set to ``true``. - OUT_OF_DOMAIN_QUERY_IGNORED (3): - The out-of-domain query ignored case. - - Google skips the summary if there are no - high-relevance search results. For example, the - data store contains facts about company A but - the user query is asking questions about company - B. - POTENTIAL_POLICY_VIOLATION (4): - The potential policy violation case. - - Google skips the summary if there is a potential - policy violation detected. This includes content - that may be violent or toxic. - LLM_ADDON_NOT_ENABLED (5): - The LLM addon not enabled case. - - Google skips the summary if the LLM addon is not - enabled. - """ - SUMMARY_SKIPPED_REASON_UNSPECIFIED = 0 - ADVERSARIAL_QUERY_IGNORED = 1 - NON_SUMMARY_SEEKING_QUERY_IGNORED = 2 - OUT_OF_DOMAIN_QUERY_IGNORED = 3 - POTENTIAL_POLICY_VIOLATION = 4 - LLM_ADDON_NOT_ENABLED = 5 - - class SafetyAttributes(proto.Message): - r"""Safety Attribute categories and their associated confidence - scores. - - Attributes: - categories (MutableSequence[str]): - The display names of Safety Attribute - categories associated with the generated - content. Order matches the Scores. - scores (MutableSequence[float]): - The confidence scores of the each category, - higher value means higher confidence. Order - matches the Categories. - """ - - categories: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - scores: MutableSequence[float] = proto.RepeatedField( - proto.FLOAT, - number=2, - ) - - summary_text: str = proto.Field( - proto.STRING, - number=1, - ) - summary_skipped_reasons: MutableSequence['SearchResponse.Summary.SummarySkippedReason'] = proto.RepeatedField( - proto.ENUM, - number=2, - enum='SearchResponse.Summary.SummarySkippedReason', - ) - safety_attributes: 'SearchResponse.Summary.SafetyAttributes' = proto.Field( - proto.MESSAGE, - number=3, - message='SearchResponse.Summary.SafetyAttributes', - ) - - class QueryExpansionInfo(proto.Message): - r"""Information describing query expansion including whether - expansion has occurred. - - Attributes: - expanded_query (bool): - Bool describing whether query expansion has - occurred. - pinned_result_count (int): - Number of pinned results. This field will only be set when - expansion happens and - [SearchRequest.QueryExpansionSpec.pin_unexpanded_results][google.cloud.discoveryengine.v1.SearchRequest.QueryExpansionSpec.pin_unexpanded_results] - is set to true. - """ - - expanded_query: bool = proto.Field( - proto.BOOL, - number=1, - ) - pinned_result_count: int = proto.Field( - proto.INT64, - number=2, - ) - - @property - def raw_page(self): - return self - - results: MutableSequence[SearchResult] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=SearchResult, - ) - facets: MutableSequence[Facet] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=Facet, - ) - total_size: int = proto.Field( - proto.INT32, - number=3, - ) - attribution_token: str = proto.Field( - proto.STRING, - number=4, - ) - redirect_uri: str = proto.Field( - proto.STRING, - number=12, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=5, - ) - corrected_query: str = proto.Field( - proto.STRING, - number=7, - ) - summary: Summary = proto.Field( - proto.MESSAGE, - number=9, - message=Summary, - ) - query_expansion_info: QueryExpansionInfo = proto.Field( - proto.MESSAGE, - number=14, - message=QueryExpansionInfo, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/user_event.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/user_event.py deleted file mode 100644 index 2b309b8f2f08..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/user_event.py +++ /dev/null @@ -1,754 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.discoveryengine_v1.types import common -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1', - manifest={ - 'UserEvent', - 'PageInfo', - 'SearchInfo', - 'CompletionInfo', - 'TransactionInfo', - 'DocumentInfo', - 'PanelInfo', - 'MediaInfo', - }, -) - - -class UserEvent(proto.Message): - r"""UserEvent captures all metadata information Discovery Engine - API needs to know about how end users interact with customers' - website. - - Attributes: - event_type (str): - Required. User event type. Allowed values are: - - Generic values: - - - ``search``: Search for Documents. - - ``view-item``: Detailed page view of a Document. - - ``view-item-list``: View of a panel or ordered list of - Documents. - - ``view-home-page``: View of the home page. - - ``view-category-page``: View of a category page, e.g. - Home > Men > Jeans - - Retail-related values: - - - ``add-to-cart``: Add an item(s) to cart, e.g. in Retail - online shopping - - ``purchase``: Purchase an item(s) - - Media-related values: - - - ``media-play``: Start/resume watching a video, playing a - song, etc. - - ``media-complete``: Finished or stopped midway through a - video, song, etc. - user_pseudo_id (str): - Required. A unique identifier for tracking visitors. - - For example, this could be implemented with an HTTP cookie, - which should be able to uniquely identify a visitor on a - single device. This unique identifier should not change if - the visitor log in/out of the website. - - Do not set the field to the same fixed ID for different - users. This mixes the event history of those users together, - which results in degraded model quality. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an ``INVALID_ARGUMENT`` error - is returned. - - The field should not contain PII or user-data. We recommend - to use Google Analytics `Client - ID `__ - for this field. - event_time (google.protobuf.timestamp_pb2.Timestamp): - Only required for - [UserEventService.ImportUserEvents][google.cloud.discoveryengine.v1.UserEventService.ImportUserEvents] - method. Timestamp of when the user event happened. - user_info (google.cloud.discoveryengine_v1.types.UserInfo): - Information about the end user. - direct_user_request (bool): - Should set to true if the request is made directly from the - end user, in which case the - [UserEvent.user_info.user_agent][google.cloud.discoveryengine.v1.UserInfo.user_agent] - can be populated from the HTTP request. - - This flag should be set only if the API request is made - directly from the end user such as a mobile app (and not if - a gateway or a server is processing and pushing the user - events). - - This should not be set when using the JavaScript tag in - [UserEventService.CollectUserEvent][google.cloud.discoveryengine.v1.UserEventService.CollectUserEvent]. - session_id (str): - A unique identifier for tracking a visitor session with a - length limit of 128 bytes. A session is an aggregation of an - end user behavior in a time span. - - A general guideline to populate the session_id: - - 1. If user has no activity for 30 min, a new session_id - should be assigned. - 2. The session_id should be unique across users, suggest use - uuid or add - [UserEvent.user_pseudo_id][google.cloud.discoveryengine.v1.UserEvent.user_pseudo_id] - as prefix. - page_info (google.cloud.discoveryengine_v1.types.PageInfo): - Page metadata such as categories and other critical - information for certain event types such as - ``view-category-page``. - attribution_token (str): - Token to attribute an API response to user action(s) to - trigger the event. - - Highly recommended for user events that are the result of - [RecommendationService.Recommend][]. This field enables - accurate attribution of recommendation model performance. - - The value must be one of: - - - [RecommendResponse.attribution_token][] for events that - are the result of [RecommendationService.Recommend][]. - - [SearchResponse.attribution_token][google.cloud.discoveryengine.v1.SearchResponse.attribution_token] - for events that are the result of - [SearchService.Search][google.cloud.discoveryengine.v1.SearchService.Search]. - - This token enables us to accurately attribute page view or - conversion completion back to the event and the particular - predict response containing this clicked/purchased product. - If user clicks on product K in the recommendation results, - pass [RecommendResponse.attribution_token][] as a URL - parameter to product K's page. When recording events on - product K's page, log the - [RecommendResponse.attribution_token][] to this field. - filter (str): - The filter syntax consists of an expression language for - constructing a predicate from one or more fields of the - documents being filtered. - - One example is for ``search`` events, the associated - [SearchRequest][google.cloud.discoveryengine.v1.SearchRequest] - may contain a filter expression in - [SearchRequest.filter][google.cloud.discoveryengine.v1.SearchRequest.filter] - conforming to https://google.aip.dev/160#filtering. - - Similarly, for ``view-item-list`` events that are generated - from a [RecommendationService.RecommendRequest][], this - field may be populated directly from - [RecommendationService.RecommendRequest.filter][] conforming - to https://google.aip.dev/160#filtering. - - The value must be a UTF-8 encoded string with a length limit - of 1,000 characters. Otherwise, an ``INVALID_ARGUMENT`` - error is returned. - documents (MutableSequence[google.cloud.discoveryengine_v1.types.DocumentInfo]): - List of - [Document][google.cloud.discoveryengine.v1.Document]s - associated with this user event. - - This field is optional except for the following event types: - - - ``view-item`` - - ``add-to-cart`` - - ``purchase`` - - ``media-play`` - - ``media-complete`` - - In a ``search`` event, this field represents the documents - returned to the end user on the current page (the end user - may have not finished browsing the whole page yet). When a - new page is returned to the end user, after - pagination/filtering/ordering even for the same query, a new - ``search`` event with different - [UserEvent.documents][google.cloud.discoveryengine.v1.UserEvent.documents] - is desired. - panel (google.cloud.discoveryengine_v1.types.PanelInfo): - Panel metadata associated with this user - event. - search_info (google.cloud.discoveryengine_v1.types.SearchInfo): - [SearchService.Search][google.cloud.discoveryengine.v1.SearchService.Search] - details related to the event. - - This field should be set for ``search`` event. - completion_info (google.cloud.discoveryengine_v1.types.CompletionInfo): - [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1.CompletionService.CompleteQuery] - details related to the event. - - This field should be set for ``search`` event when - autocomplete function is enabled and the user clicks a - suggestion for search. - transaction_info (google.cloud.discoveryengine_v1.types.TransactionInfo): - The transaction metadata (if any) associated - with this user event. - tag_ids (MutableSequence[str]): - A list of identifiers for the independent - experiment groups this user event belongs to. - This is used to distinguish between user events - associated with different experiment setups on - the customer end. - promotion_ids (MutableSequence[str]): - The promotion IDs if this is an event - associated with promotions. Currently, this - field is restricted to at most one ID. - attributes (MutableMapping[str, google.cloud.discoveryengine_v1.types.CustomAttribute]): - Extra user event features to include in the recommendation - model. These attributes must NOT contain data that needs to - be parsed or processed further, e.g. JSON or other - encodings. - - If you provide custom attributes for ingested user events, - also include them in the user events that you associate with - prediction requests. Custom attribute formatting must be - consistent between imported events and events provided with - prediction requests. This lets the Discovery Engine API use - those custom attributes when training models and serving - predictions, which helps improve recommendation quality. - - This field needs to pass all below criteria, otherwise an - ``INVALID_ARGUMENT`` error is returned: - - - The key must be a UTF-8 encoded string with a length - limit of 5,000 characters. - - For text attributes, at most 400 values are allowed. - Empty values are not allowed. Each value must be a UTF-8 - encoded string with a length limit of 256 characters. - - For number attributes, at most 400 values are allowed. - - For product recommendations, an example of extra user - information is ``traffic_channel``, which is how a user - arrives at the site. Users can arrive at the site by coming - to the site directly, coming through Google search, or in - other ways. - media_info (google.cloud.discoveryengine_v1.types.MediaInfo): - Media-specific info. - """ - - event_type: str = proto.Field( - proto.STRING, - number=1, - ) - user_pseudo_id: str = proto.Field( - proto.STRING, - number=2, - ) - event_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - user_info: common.UserInfo = proto.Field( - proto.MESSAGE, - number=4, - message=common.UserInfo, - ) - direct_user_request: bool = proto.Field( - proto.BOOL, - number=5, - ) - session_id: str = proto.Field( - proto.STRING, - number=6, - ) - page_info: 'PageInfo' = proto.Field( - proto.MESSAGE, - number=7, - message='PageInfo', - ) - attribution_token: str = proto.Field( - proto.STRING, - number=8, - ) - filter: str = proto.Field( - proto.STRING, - number=9, - ) - documents: MutableSequence['DocumentInfo'] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message='DocumentInfo', - ) - panel: 'PanelInfo' = proto.Field( - proto.MESSAGE, - number=11, - message='PanelInfo', - ) - search_info: 'SearchInfo' = proto.Field( - proto.MESSAGE, - number=12, - message='SearchInfo', - ) - completion_info: 'CompletionInfo' = proto.Field( - proto.MESSAGE, - number=13, - message='CompletionInfo', - ) - transaction_info: 'TransactionInfo' = proto.Field( - proto.MESSAGE, - number=14, - message='TransactionInfo', - ) - tag_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=15, - ) - promotion_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=16, - ) - attributes: MutableMapping[str, common.CustomAttribute] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=17, - message=common.CustomAttribute, - ) - media_info: 'MediaInfo' = proto.Field( - proto.MESSAGE, - number=18, - message='MediaInfo', - ) - - -class PageInfo(proto.Message): - r"""Detailed page information. - - Attributes: - pageview_id (str): - A unique ID of a web page view. - - This should be kept the same for all user events triggered - from the same pageview. For example, an item detail page - view could trigger multiple events as the user is browsing - the page. The ``pageview_id`` property should be kept the - same for all these events so that they can be grouped - together properly. - - When using the client side event reporting with JavaScript - pixel and Google Tag Manager, this value is filled in - automatically. - page_category (str): - The most specific category associated with a category page. - - To represent full path of category, use '>' sign to separate - different hierarchies. If '>' is part of the category name, - please replace it with other character(s). - - Category pages include special pages such as sales or - promotions. For instance, a special sale page may have the - category hierarchy: - ``"pageCategory" : "Sales > 2017 Black Friday Deals"``. - - Required for ``view-category-page`` events. Other event - types should not set this field. Otherwise, an - ``INVALID_ARGUMENT`` error is returned. - uri (str): - Complete URL (window.location.href) of the - user's current page. - When using the client side event reporting with - JavaScript pixel and Google Tag Manager, this - value is filled in automatically. Maximum length - 5,000 characters. - referrer_uri (str): - The referrer URL of the current page. - - When using the client side event reporting with - JavaScript pixel and Google Tag Manager, this - value is filled in automatically. However, some - browser privacy restrictions may cause this - field to be empty. - """ - - pageview_id: str = proto.Field( - proto.STRING, - number=1, - ) - page_category: str = proto.Field( - proto.STRING, - number=2, - ) - uri: str = proto.Field( - proto.STRING, - number=3, - ) - referrer_uri: str = proto.Field( - proto.STRING, - number=4, - ) - - -class SearchInfo(proto.Message): - r"""Detailed search information. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - search_query (str): - The user's search query. - - See - [SearchRequest.query][google.cloud.discoveryengine.v1.SearchRequest.query] - for definition. - - The value must be a UTF-8 encoded string with a length limit - of 5,000 characters. Otherwise, an ``INVALID_ARGUMENT`` - error is returned. - - At least one of - [search_query][google.cloud.discoveryengine.v1.SearchInfo.search_query] - or - [PageInfo.page_category][google.cloud.discoveryengine.v1.PageInfo.page_category] - is required for ``search`` events. Other event types should - not set this field. Otherwise, an ``INVALID_ARGUMENT`` error - is returned. - order_by (str): - The order in which products are returned, if applicable. - - See - [SearchRequest.order_by][google.cloud.discoveryengine.v1.SearchRequest.order_by] - for definition and syntax. - - The value must be a UTF-8 encoded string with a length limit - of 1,000 characters. Otherwise, an ``INVALID_ARGUMENT`` - error is returned. - - This can only be set for ``search`` events. Other event - types should not set this field. Otherwise, an - ``INVALID_ARGUMENT`` error is returned. - offset (int): - An integer that specifies the current offset for pagination - (the 0-indexed starting location, amongst the products - deemed by the API as relevant). - - See - [SearchRequest.offset][google.cloud.discoveryengine.v1.SearchRequest.offset] - for definition. - - If this field is negative, an ``INVALID_ARGUMENT`` is - returned. - - This can only be set for ``search`` events. Other event - types should not set this field. Otherwise, an - ``INVALID_ARGUMENT`` error is returned. - - This field is a member of `oneof`_ ``_offset``. - """ - - search_query: str = proto.Field( - proto.STRING, - number=1, - ) - order_by: str = proto.Field( - proto.STRING, - number=2, - ) - offset: int = proto.Field( - proto.INT32, - number=3, - optional=True, - ) - - -class CompletionInfo(proto.Message): - r"""Detailed completion information including completion - attribution token and clicked completion info. - - Attributes: - selected_suggestion (str): - End user selected - [CompleteQueryResponse.QuerySuggestion.suggestion][google.cloud.discoveryengine.v1.CompleteQueryResponse.QuerySuggestion.suggestion]. - selected_position (int): - End user selected - [CompleteQueryResponse.QuerySuggestion.suggestion][google.cloud.discoveryengine.v1.CompleteQueryResponse.QuerySuggestion.suggestion] - position, starting from 0. - """ - - selected_suggestion: str = proto.Field( - proto.STRING, - number=1, - ) - selected_position: int = proto.Field( - proto.INT32, - number=2, - ) - - -class TransactionInfo(proto.Message): - r"""A transaction represents the entire purchase transaction. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - value (float): - Required. Total non-zero value associated - with the transaction. This value may include - shipping, tax, or other adjustments to the total - value that you want to include. - - This field is a member of `oneof`_ ``_value``. - currency (str): - Required. Currency code. Use three-character - ISO-4217 code. - transaction_id (str): - The transaction ID with a length limit of 128 - characters. - tax (float): - All the taxes associated with the - transaction. - - This field is a member of `oneof`_ ``_tax``. - cost (float): - All the costs associated with the products. These can be - manufacturing costs, shipping expenses not borne by the end - user, or any other costs, such that: - - - Profit = - [value][google.cloud.discoveryengine.v1.TransactionInfo.value] - - - [tax][google.cloud.discoveryengine.v1.TransactionInfo.tax] - - - [cost][google.cloud.discoveryengine.v1.TransactionInfo.cost] - - This field is a member of `oneof`_ ``_cost``. - discount_value (float): - The total discount(s) value applied to this transaction. - This figure should be excluded from - [TransactionInfo.value][google.cloud.discoveryengine.v1.TransactionInfo.value] - - For example, if a user paid - [TransactionInfo.value][google.cloud.discoveryengine.v1.TransactionInfo.value] - amount, then nominal (pre-discount) value of the transaction - is the sum of - [TransactionInfo.value][google.cloud.discoveryengine.v1.TransactionInfo.value] - and - [TransactionInfo.discount_value][google.cloud.discoveryengine.v1.TransactionInfo.discount_value] - - This means that profit is calculated the same way, - regardless of the discount value, and that - [TransactionInfo.discount_value][google.cloud.discoveryengine.v1.TransactionInfo.discount_value] - can be larger than - [TransactionInfo.value][google.cloud.discoveryengine.v1.TransactionInfo.value]: - - - Profit = - [value][google.cloud.discoveryengine.v1.TransactionInfo.value] - - - [tax][google.cloud.discoveryengine.v1.TransactionInfo.tax] - - - [cost][google.cloud.discoveryengine.v1.TransactionInfo.cost] - - This field is a member of `oneof`_ ``_discount_value``. - """ - - value: float = proto.Field( - proto.FLOAT, - number=1, - optional=True, - ) - currency: str = proto.Field( - proto.STRING, - number=2, - ) - transaction_id: str = proto.Field( - proto.STRING, - number=3, - ) - tax: float = proto.Field( - proto.FLOAT, - number=4, - optional=True, - ) - cost: float = proto.Field( - proto.FLOAT, - number=5, - optional=True, - ) - discount_value: float = proto.Field( - proto.FLOAT, - number=6, - optional=True, - ) - - -class DocumentInfo(proto.Message): - r"""Detailed document information associated with a user event. - - 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: - id (str): - The [Document][google.cloud.discoveryengine.v1.Document] - resource ID. - - This field is a member of `oneof`_ ``document_descriptor``. - name (str): - The [Document][google.cloud.discoveryengine.v1.Document] - resource full name, of the form: - ``projects/{project_id}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}/branches/{branch_id}/documents/{document_id}`` - - This field is a member of `oneof`_ ``document_descriptor``. - uri (str): - The [Document][google.cloud.discoveryengine.v1.Document] URI - - only allowed for website data stores. - - This field is a member of `oneof`_ ``document_descriptor``. - quantity (int): - Quantity of the Document associated with the user event. - Defaults to 1. - - For example, this field will be 2 if two quantities of the - same Document are involved in a ``add-to-cart`` event. - - Required for events of the following event types: - - - ``add-to-cart`` - - ``purchase`` - - This field is a member of `oneof`_ ``_quantity``. - promotion_ids (MutableSequence[str]): - The promotion IDs associated with this - Document. Currently, this field is restricted to - at most one ID. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - oneof='document_descriptor', - ) - name: str = proto.Field( - proto.STRING, - number=2, - oneof='document_descriptor', - ) - uri: str = proto.Field( - proto.STRING, - number=6, - oneof='document_descriptor', - ) - quantity: int = proto.Field( - proto.INT32, - number=3, - optional=True, - ) - promotion_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - - -class PanelInfo(proto.Message): - r"""Detailed panel information associated with a user event. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - panel_id (str): - Required. The panel ID. - display_name (str): - The display name of the panel. - panel_position (int): - The ordered position of the panel, if shown to the user with - other panels. If set, then - [total_panels][google.cloud.discoveryengine.v1.PanelInfo.total_panels] - must also be set. - - This field is a member of `oneof`_ ``_panel_position``. - total_panels (int): - The total number of panels, including this one, shown to the - user. Must be set if - [panel_position][google.cloud.discoveryengine.v1.PanelInfo.panel_position] - is set. - - This field is a member of `oneof`_ ``_total_panels``. - """ - - panel_id: str = proto.Field( - proto.STRING, - number=2, - ) - display_name: str = proto.Field( - proto.STRING, - number=3, - ) - panel_position: int = proto.Field( - proto.INT32, - number=4, - optional=True, - ) - total_panels: int = proto.Field( - proto.INT32, - number=5, - optional=True, - ) - - -class MediaInfo(proto.Message): - r"""Media-specific user event information. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - media_progress_duration (google.protobuf.duration_pb2.Duration): - The media progress time in seconds, if applicable. For - example, if the end user has finished 90 seconds of a - playback video, then - [MediaInfo.media_progress_duration.seconds][google.protobuf.Duration.seconds] - should be set to 90. - media_progress_percentage (float): - Media progress should be computed using only the - [media_progress_duration][google.cloud.discoveryengine.v1.MediaInfo.media_progress_duration] - relative to the media total length. - - This value must be between ``[0, 1.0]`` inclusive. - - If this is not a playback or the progress cannot be computed - (e.g. ongoing livestream), this field should be unset. - - This field is a member of `oneof`_ ``_media_progress_percentage``. - """ - - media_progress_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - media_progress_percentage: float = proto.Field( - proto.FLOAT, - number=2, - optional=True, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/user_event_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/user_event_service.py deleted file mode 100644 index 6ba8f47138eb..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/google/cloud/discoveryengine_v1/types/user_event_service.py +++ /dev/null @@ -1,110 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.discoveryengine_v1.types import user_event as gcd_user_event - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1', - manifest={ - 'WriteUserEventRequest', - 'CollectUserEventRequest', - }, -) - - -class WriteUserEventRequest(proto.Message): - r"""Request message for WriteUserEvent method. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - parent (str): - Required. The parent DataStore resource name, such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. - user_event (google.cloud.discoveryengine_v1.types.UserEvent): - Required. User event to write. - - This field is a member of `oneof`_ ``_user_event``. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - user_event: gcd_user_event.UserEvent = proto.Field( - proto.MESSAGE, - number=2, - optional=True, - message=gcd_user_event.UserEvent, - ) - - -class CollectUserEventRequest(proto.Message): - r"""Request message for CollectUserEvent method. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - parent (str): - Required. The parent DataStore resource name, such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. - user_event (str): - Required. URL encoded UserEvent proto with a - length limit of 2,000,000 characters. - uri (str): - The URL including cgi-parameters but - excluding the hash fragment with a length limit - of 5,000 characters. This is often more useful - than the referer URL, because many browsers only - send the domain for third-party requests. - - This field is a member of `oneof`_ ``_uri``. - ets (int): - The event timestamp in milliseconds. This - prevents browser caching of otherwise identical - get requests. The name is abbreviated to reduce - the payload bytes. - - This field is a member of `oneof`_ ``_ets``. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - user_event: str = proto.Field( - proto.STRING, - number=2, - ) - uri: str = proto.Field( - proto.STRING, - number=3, - optional=True, - ) - ets: int = proto.Field( - proto.INT64, - number=4, - optional=True, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/mypy.ini b/owl-bot-staging/google-cloud-discoveryengine/v1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/noxfile.py b/owl-bot-staging/google-cloud-discoveryengine/v1/noxfile.py deleted file mode 100644 index 013a607914d2..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/noxfile.py +++ /dev/null @@ -1,184 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.11" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "lint_setup_py", -] - -@nox.session(python=ALL_PYTHON) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/discoveryengine_v1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - 'mypy', - 'types-requests', - 'types-protobuf' - ) - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==7.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_completion_service_complete_query_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_completion_service_complete_query_async.py deleted file mode 100644 index dd296b1f8bec..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_completion_service_complete_query_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CompleteQuery -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_CompletionService_CompleteQuery_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -async def sample_complete_query(): - # Create a client - client = discoveryengine_v1.CompletionServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.CompleteQueryRequest( - data_store="data_store_value", - query="query_value", - ) - - # Make the request - response = await client.complete_query(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1_generated_CompletionService_CompleteQuery_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_completion_service_complete_query_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_completion_service_complete_query_sync.py deleted file mode 100644 index 8e2357df0dd7..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_completion_service_complete_query_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CompleteQuery -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_CompletionService_CompleteQuery_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -def sample_complete_query(): - # Create a client - client = discoveryengine_v1.CompletionServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.CompleteQueryRequest( - data_store="data_store_value", - query="query_value", - ) - - # Make the request - response = client.complete_query(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1_generated_CompletionService_CompleteQuery_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_converse_conversation_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_converse_conversation_async.py deleted file mode 100644 index 816c3b250de7..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_converse_conversation_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ConverseConversation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_ConversationalSearchService_ConverseConversation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -async def sample_converse_conversation(): - # Create a client - client = discoveryengine_v1.ConversationalSearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.ConverseConversationRequest( - name="name_value", - ) - - # Make the request - response = await client.converse_conversation(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1_generated_ConversationalSearchService_ConverseConversation_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_converse_conversation_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_converse_conversation_sync.py deleted file mode 100644 index 7ee9ba54110c..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_converse_conversation_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ConverseConversation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_ConversationalSearchService_ConverseConversation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -def sample_converse_conversation(): - # Create a client - client = discoveryengine_v1.ConversationalSearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.ConverseConversationRequest( - name="name_value", - ) - - # Make the request - response = client.converse_conversation(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1_generated_ConversationalSearchService_ConverseConversation_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_create_conversation_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_create_conversation_async.py deleted file mode 100644 index ab3094fe6591..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_create_conversation_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateConversation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_ConversationalSearchService_CreateConversation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -async def sample_create_conversation(): - # Create a client - client = discoveryengine_v1.ConversationalSearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.CreateConversationRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_conversation(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1_generated_ConversationalSearchService_CreateConversation_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_create_conversation_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_create_conversation_sync.py deleted file mode 100644 index 023d1d5ac2c2..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_create_conversation_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateConversation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_ConversationalSearchService_CreateConversation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -def sample_create_conversation(): - # Create a client - client = discoveryengine_v1.ConversationalSearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.CreateConversationRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_conversation(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1_generated_ConversationalSearchService_CreateConversation_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_delete_conversation_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_delete_conversation_async.py deleted file mode 100644 index b5149fbf7574..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_delete_conversation_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteConversation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_ConversationalSearchService_DeleteConversation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -async def sample_delete_conversation(): - # Create a client - client = discoveryengine_v1.ConversationalSearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.DeleteConversationRequest( - name="name_value", - ) - - # Make the request - await client.delete_conversation(request=request) - - -# [END discoveryengine_v1_generated_ConversationalSearchService_DeleteConversation_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_delete_conversation_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_delete_conversation_sync.py deleted file mode 100644 index b200a8c34650..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_delete_conversation_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteConversation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_ConversationalSearchService_DeleteConversation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -def sample_delete_conversation(): - # Create a client - client = discoveryengine_v1.ConversationalSearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.DeleteConversationRequest( - name="name_value", - ) - - # Make the request - client.delete_conversation(request=request) - - -# [END discoveryengine_v1_generated_ConversationalSearchService_DeleteConversation_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_get_conversation_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_get_conversation_async.py deleted file mode 100644 index 4379c2ae855a..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_get_conversation_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetConversation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_ConversationalSearchService_GetConversation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -async def sample_get_conversation(): - # Create a client - client = discoveryengine_v1.ConversationalSearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.GetConversationRequest( - name="name_value", - ) - - # Make the request - response = await client.get_conversation(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1_generated_ConversationalSearchService_GetConversation_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_get_conversation_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_get_conversation_sync.py deleted file mode 100644 index 9685e1a75f86..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_get_conversation_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetConversation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_ConversationalSearchService_GetConversation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -def sample_get_conversation(): - # Create a client - client = discoveryengine_v1.ConversationalSearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.GetConversationRequest( - name="name_value", - ) - - # Make the request - response = client.get_conversation(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1_generated_ConversationalSearchService_GetConversation_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_list_conversations_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_list_conversations_async.py deleted file mode 100644 index 5173cd8e1438..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_list_conversations_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListConversations -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_ConversationalSearchService_ListConversations_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -async def sample_list_conversations(): - # Create a client - client = discoveryengine_v1.ConversationalSearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.ListConversationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversations(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END discoveryengine_v1_generated_ConversationalSearchService_ListConversations_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_list_conversations_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_list_conversations_sync.py deleted file mode 100644 index 8677d2518cfa..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_list_conversations_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListConversations -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_ConversationalSearchService_ListConversations_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -def sample_list_conversations(): - # Create a client - client = discoveryengine_v1.ConversationalSearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.ListConversationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversations(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END discoveryengine_v1_generated_ConversationalSearchService_ListConversations_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_update_conversation_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_update_conversation_async.py deleted file mode 100644 index f030ec185795..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_update_conversation_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for 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-discoveryengine - - -# [START discoveryengine_v1_generated_ConversationalSearchService_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 discoveryengine_v1 - - -async def sample_update_conversation(): - # Create a client - client = discoveryengine_v1.ConversationalSearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.UpdateConversationRequest( - ) - - # Make the request - response = await client.update_conversation(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1_generated_ConversationalSearchService_UpdateConversation_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_update_conversation_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_update_conversation_sync.py deleted file mode 100644 index b7a895b2c90b..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_conversational_search_service_update_conversation_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for 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-discoveryengine - - -# [START discoveryengine_v1_generated_ConversationalSearchService_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 discoveryengine_v1 - - -def sample_update_conversation(): - # Create a client - client = discoveryengine_v1.ConversationalSearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.UpdateConversationRequest( - ) - - # Make the request - response = client.update_conversation(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1_generated_ConversationalSearchService_UpdateConversation_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_create_document_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_create_document_async.py deleted file mode 100644 index a181b8613936..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_create_document_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_DocumentService_CreateDocument_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -async def sample_create_document(): - # Create a client - client = discoveryengine_v1.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.CreateDocumentRequest( - parent="parent_value", - document_id="document_id_value", - ) - - # Make the request - response = await client.create_document(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1_generated_DocumentService_CreateDocument_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_create_document_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_create_document_sync.py deleted file mode 100644 index 22f9f29f516a..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_create_document_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_DocumentService_CreateDocument_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -def sample_create_document(): - # Create a client - client = discoveryengine_v1.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.CreateDocumentRequest( - parent="parent_value", - document_id="document_id_value", - ) - - # Make the request - response = client.create_document(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1_generated_DocumentService_CreateDocument_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_delete_document_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_delete_document_async.py deleted file mode 100644 index cebcfd6c60b1..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_delete_document_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_DocumentService_DeleteDocument_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -async def sample_delete_document(): - # Create a client - client = discoveryengine_v1.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.DeleteDocumentRequest( - name="name_value", - ) - - # Make the request - await client.delete_document(request=request) - - -# [END discoveryengine_v1_generated_DocumentService_DeleteDocument_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_delete_document_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_delete_document_sync.py deleted file mode 100644 index e9f56aae2e8b..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_delete_document_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_DocumentService_DeleteDocument_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -def sample_delete_document(): - # Create a client - client = discoveryengine_v1.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.DeleteDocumentRequest( - name="name_value", - ) - - # Make the request - client.delete_document(request=request) - - -# [END discoveryengine_v1_generated_DocumentService_DeleteDocument_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_get_document_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_get_document_async.py deleted file mode 100644 index 9a6b33085029..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_get_document_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_DocumentService_GetDocument_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -async def sample_get_document(): - # Create a client - client = discoveryengine_v1.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.GetDocumentRequest( - name="name_value", - ) - - # Make the request - response = await client.get_document(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1_generated_DocumentService_GetDocument_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_get_document_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_get_document_sync.py deleted file mode 100644 index 35a409bd1698..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_get_document_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_DocumentService_GetDocument_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -def sample_get_document(): - # Create a client - client = discoveryengine_v1.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.GetDocumentRequest( - name="name_value", - ) - - # Make the request - response = client.get_document(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1_generated_DocumentService_GetDocument_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_import_documents_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_import_documents_async.py deleted file mode 100644 index 56a38712b91a..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_import_documents_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportDocuments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_DocumentService_ImportDocuments_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -async def sample_import_documents(): - # Create a client - client = discoveryengine_v1.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.ImportDocumentsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.import_documents(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END discoveryengine_v1_generated_DocumentService_ImportDocuments_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_import_documents_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_import_documents_sync.py deleted file mode 100644 index e2c623f2be83..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_import_documents_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportDocuments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_DocumentService_ImportDocuments_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -def sample_import_documents(): - # Create a client - client = discoveryengine_v1.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.ImportDocumentsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.import_documents(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END discoveryengine_v1_generated_DocumentService_ImportDocuments_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_list_documents_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_list_documents_async.py deleted file mode 100644 index 7f05ac2f773f..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_list_documents_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListDocuments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_DocumentService_ListDocuments_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -async def sample_list_documents(): - # Create a client - client = discoveryengine_v1.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.ListDocumentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_documents(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END discoveryengine_v1_generated_DocumentService_ListDocuments_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_list_documents_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_list_documents_sync.py deleted file mode 100644 index d8becd95f391..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_list_documents_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListDocuments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_DocumentService_ListDocuments_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -def sample_list_documents(): - # Create a client - client = discoveryengine_v1.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.ListDocumentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_documents(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END discoveryengine_v1_generated_DocumentService_ListDocuments_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_purge_documents_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_purge_documents_async.py deleted file mode 100644 index 6130f8ab9c23..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_purge_documents_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PurgeDocuments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_DocumentService_PurgeDocuments_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -async def sample_purge_documents(): - # Create a client - client = discoveryengine_v1.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.PurgeDocumentsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_documents(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END discoveryengine_v1_generated_DocumentService_PurgeDocuments_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_purge_documents_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_purge_documents_sync.py deleted file mode 100644 index 8c55663a89ce..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_purge_documents_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PurgeDocuments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_DocumentService_PurgeDocuments_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -def sample_purge_documents(): - # Create a client - client = discoveryengine_v1.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.PurgeDocumentsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_documents(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END discoveryengine_v1_generated_DocumentService_PurgeDocuments_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_update_document_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_update_document_async.py deleted file mode 100644 index 38823adc30dc..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_update_document_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_DocumentService_UpdateDocument_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -async def sample_update_document(): - # Create a client - client = discoveryengine_v1.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.UpdateDocumentRequest( - ) - - # Make the request - response = await client.update_document(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1_generated_DocumentService_UpdateDocument_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_update_document_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_update_document_sync.py deleted file mode 100644 index 3831e7c83da4..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_document_service_update_document_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_DocumentService_UpdateDocument_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -def sample_update_document(): - # Create a client - client = discoveryengine_v1.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.UpdateDocumentRequest( - ) - - # Make the request - response = client.update_document(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1_generated_DocumentService_UpdateDocument_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_create_schema_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_create_schema_async.py deleted file mode 100644 index 5db7f8cd3f68..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_create_schema_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateSchema -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_SchemaService_CreateSchema_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -async def sample_create_schema(): - # Create a client - client = discoveryengine_v1.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.CreateSchemaRequest( - parent="parent_value", - schema_id="schema_id_value", - ) - - # Make the request - operation = client.create_schema(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END discoveryengine_v1_generated_SchemaService_CreateSchema_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_create_schema_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_create_schema_sync.py deleted file mode 100644 index c649d3018fc3..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_create_schema_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateSchema -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_SchemaService_CreateSchema_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -def sample_create_schema(): - # Create a client - client = discoveryengine_v1.SchemaServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.CreateSchemaRequest( - parent="parent_value", - schema_id="schema_id_value", - ) - - # Make the request - operation = client.create_schema(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END discoveryengine_v1_generated_SchemaService_CreateSchema_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_delete_schema_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_delete_schema_async.py deleted file mode 100644 index b96723396227..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_delete_schema_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteSchema -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_SchemaService_DeleteSchema_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -async def sample_delete_schema(): - # Create a client - client = discoveryengine_v1.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.DeleteSchemaRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_schema(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END discoveryengine_v1_generated_SchemaService_DeleteSchema_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_delete_schema_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_delete_schema_sync.py deleted file mode 100644 index ed9a2f2bdc9b..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_delete_schema_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteSchema -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_SchemaService_DeleteSchema_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -def sample_delete_schema(): - # Create a client - client = discoveryengine_v1.SchemaServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.DeleteSchemaRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_schema(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END discoveryengine_v1_generated_SchemaService_DeleteSchema_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_get_schema_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_get_schema_async.py deleted file mode 100644 index 2fc215c9a29c..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_get_schema_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetSchema -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_SchemaService_GetSchema_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -async def sample_get_schema(): - # Create a client - client = discoveryengine_v1.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.GetSchemaRequest( - name="name_value", - ) - - # Make the request - response = await client.get_schema(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1_generated_SchemaService_GetSchema_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_get_schema_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_get_schema_sync.py deleted file mode 100644 index 97cd74f9c228..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_get_schema_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetSchema -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_SchemaService_GetSchema_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -def sample_get_schema(): - # Create a client - client = discoveryengine_v1.SchemaServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.GetSchemaRequest( - name="name_value", - ) - - # Make the request - response = client.get_schema(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1_generated_SchemaService_GetSchema_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_list_schemas_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_list_schemas_async.py deleted file mode 100644 index a46cc07b32a4..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_list_schemas_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListSchemas -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_SchemaService_ListSchemas_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -async def sample_list_schemas(): - # Create a client - client = discoveryengine_v1.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.ListSchemasRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_schemas(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END discoveryengine_v1_generated_SchemaService_ListSchemas_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_list_schemas_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_list_schemas_sync.py deleted file mode 100644 index 7476d67d150a..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_list_schemas_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListSchemas -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_SchemaService_ListSchemas_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -def sample_list_schemas(): - # Create a client - client = discoveryengine_v1.SchemaServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.ListSchemasRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_schemas(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END discoveryengine_v1_generated_SchemaService_ListSchemas_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_update_schema_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_update_schema_async.py deleted file mode 100644 index 353e941ff66b..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_update_schema_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateSchema -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_SchemaService_UpdateSchema_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -async def sample_update_schema(): - # Create a client - client = discoveryengine_v1.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.UpdateSchemaRequest( - ) - - # Make the request - operation = client.update_schema(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END discoveryengine_v1_generated_SchemaService_UpdateSchema_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_update_schema_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_update_schema_sync.py deleted file mode 100644 index 352ea1e343fc..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_schema_service_update_schema_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateSchema -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_SchemaService_UpdateSchema_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -def sample_update_schema(): - # Create a client - client = discoveryengine_v1.SchemaServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.UpdateSchemaRequest( - ) - - # Make the request - operation = client.update_schema(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END discoveryengine_v1_generated_SchemaService_UpdateSchema_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_search_service_search_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_search_service_search_async.py deleted file mode 100644 index 1a4950f86052..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_search_service_search_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Search -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_SearchService_Search_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -async def sample_search(): - # Create a client - client = discoveryengine_v1.SearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.SearchRequest( - serving_config="serving_config_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END discoveryengine_v1_generated_SearchService_Search_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_search_service_search_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_search_service_search_sync.py deleted file mode 100644 index 0821a29337dd..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_search_service_search_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Search -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_SearchService_Search_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -def sample_search(): - # Create a client - client = discoveryengine_v1.SearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.SearchRequest( - serving_config="serving_config_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END discoveryengine_v1_generated_SearchService_Search_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_collect_user_event_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_collect_user_event_async.py deleted file mode 100644 index d19646672e50..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_collect_user_event_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CollectUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_UserEventService_CollectUserEvent_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -async def sample_collect_user_event(): - # Create a client - client = discoveryengine_v1.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = await client.collect_user_event(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1_generated_UserEventService_CollectUserEvent_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_collect_user_event_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_collect_user_event_sync.py deleted file mode 100644 index 0ab2a0ba19bc..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_collect_user_event_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CollectUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_UserEventService_CollectUserEvent_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -def sample_collect_user_event(): - # Create a client - client = discoveryengine_v1.UserEventServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = client.collect_user_event(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1_generated_UserEventService_CollectUserEvent_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_import_user_events_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_import_user_events_async.py deleted file mode 100644 index 7d65b34b8373..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_import_user_events_async.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_UserEventService_ImportUserEvents_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -async def sample_import_user_events(): - # Create a client - client = discoveryengine_v1.UserEventServiceAsyncClient() - - # Initialize request argument(s) - inline_source = discoveryengine_v1.InlineSource() - inline_source.user_events.event_type = "event_type_value" - inline_source.user_events.user_pseudo_id = "user_pseudo_id_value" - - request = discoveryengine_v1.ImportUserEventsRequest( - inline_source=inline_source, - parent="parent_value", - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END discoveryengine_v1_generated_UserEventService_ImportUserEvents_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_import_user_events_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_import_user_events_sync.py deleted file mode 100644 index b6bcb67c87ef..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_import_user_events_sync.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_UserEventService_ImportUserEvents_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -def sample_import_user_events(): - # Create a client - client = discoveryengine_v1.UserEventServiceClient() - - # Initialize request argument(s) - inline_source = discoveryengine_v1.InlineSource() - inline_source.user_events.event_type = "event_type_value" - inline_source.user_events.user_pseudo_id = "user_pseudo_id_value" - - request = discoveryengine_v1.ImportUserEventsRequest( - inline_source=inline_source, - parent="parent_value", - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END discoveryengine_v1_generated_UserEventService_ImportUserEvents_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_write_user_event_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_write_user_event_async.py deleted file mode 100644 index 25cc88027ac9..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_write_user_event_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for WriteUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_UserEventService_WriteUserEvent_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -async def sample_write_user_event(): - # Create a client - client = discoveryengine_v1.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1.WriteUserEventRequest( - parent="parent_value", - ) - - # Make the request - response = await client.write_user_event(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1_generated_UserEventService_WriteUserEvent_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_write_user_event_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_write_user_event_sync.py deleted file mode 100644 index bf674d82b25c..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/discoveryengine_v1_generated_user_event_service_write_user_event_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for WriteUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1_generated_UserEventService_WriteUserEvent_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1 - - -def sample_write_user_event(): - # Create a client - client = discoveryengine_v1.UserEventServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1.WriteUserEventRequest( - parent="parent_value", - ) - - # Make the request - response = client.write_user_event(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1_generated_UserEventService_WriteUserEvent_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1.json b/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1.json deleted file mode 100644 index 7c1bfd82952e..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1.json +++ /dev/null @@ -1,3690 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.discoveryengine.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-cloud-discoveryengine", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1.CompletionServiceAsyncClient", - "shortName": "CompletionServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1.CompletionServiceAsyncClient.complete_query", - "method": { - "fullName": "google.cloud.discoveryengine.v1.CompletionService.CompleteQuery", - "service": { - "fullName": "google.cloud.discoveryengine.v1.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "CompleteQuery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.CompleteQueryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1.types.CompleteQueryResponse", - "shortName": "complete_query" - }, - "description": "Sample for CompleteQuery", - "file": "discoveryengine_v1_generated_completion_service_complete_query_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_CompletionService_CompleteQuery_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": "discoveryengine_v1_generated_completion_service_complete_query_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1.CompletionServiceClient", - "shortName": "CompletionServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1.CompletionServiceClient.complete_query", - "method": { - "fullName": "google.cloud.discoveryengine.v1.CompletionService.CompleteQuery", - "service": { - "fullName": "google.cloud.discoveryengine.v1.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "CompleteQuery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.CompleteQueryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1.types.CompleteQueryResponse", - "shortName": "complete_query" - }, - "description": "Sample for CompleteQuery", - "file": "discoveryengine_v1_generated_completion_service_complete_query_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_CompletionService_CompleteQuery_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": "discoveryengine_v1_generated_completion_service_complete_query_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient", - "shortName": "ConversationalSearchServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.converse_conversation", - "method": { - "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.ConverseConversation", - "service": { - "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService", - "shortName": "ConversationalSearchService" - }, - "shortName": "ConverseConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.ConverseConversationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "query", - "type": "google.cloud.discoveryengine_v1.types.TextInput" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1.types.ConverseConversationResponse", - "shortName": "converse_conversation" - }, - "description": "Sample for ConverseConversation", - "file": "discoveryengine_v1_generated_conversational_search_service_converse_conversation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_ConverseConversation_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": "discoveryengine_v1_generated_conversational_search_service_converse_conversation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient", - "shortName": "ConversationalSearchServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.converse_conversation", - "method": { - "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.ConverseConversation", - "service": { - "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService", - "shortName": "ConversationalSearchService" - }, - "shortName": "ConverseConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.ConverseConversationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "query", - "type": "google.cloud.discoveryengine_v1.types.TextInput" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1.types.ConverseConversationResponse", - "shortName": "converse_conversation" - }, - "description": "Sample for ConverseConversation", - "file": "discoveryengine_v1_generated_conversational_search_service_converse_conversation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_ConverseConversation_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": "discoveryengine_v1_generated_conversational_search_service_converse_conversation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient", - "shortName": "ConversationalSearchServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.create_conversation", - "method": { - "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.CreateConversation", - "service": { - "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService", - "shortName": "ConversationalSearchService" - }, - "shortName": "CreateConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.CreateConversationRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "conversation", - "type": "google.cloud.discoveryengine_v1.types.Conversation" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1.types.Conversation", - "shortName": "create_conversation" - }, - "description": "Sample for CreateConversation", - "file": "discoveryengine_v1_generated_conversational_search_service_create_conversation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_CreateConversation_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": "discoveryengine_v1_generated_conversational_search_service_create_conversation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient", - "shortName": "ConversationalSearchServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.create_conversation", - "method": { - "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.CreateConversation", - "service": { - "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService", - "shortName": "ConversationalSearchService" - }, - "shortName": "CreateConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.CreateConversationRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "conversation", - "type": "google.cloud.discoveryengine_v1.types.Conversation" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1.types.Conversation", - "shortName": "create_conversation" - }, - "description": "Sample for CreateConversation", - "file": "discoveryengine_v1_generated_conversational_search_service_create_conversation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_CreateConversation_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": "discoveryengine_v1_generated_conversational_search_service_create_conversation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient", - "shortName": "ConversationalSearchServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.delete_conversation", - "method": { - "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.DeleteConversation", - "service": { - "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService", - "shortName": "ConversationalSearchService" - }, - "shortName": "DeleteConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.DeleteConversationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_conversation" - }, - "description": "Sample for DeleteConversation", - "file": "discoveryengine_v1_generated_conversational_search_service_delete_conversation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_DeleteConversation_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": "discoveryengine_v1_generated_conversational_search_service_delete_conversation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient", - "shortName": "ConversationalSearchServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.delete_conversation", - "method": { - "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.DeleteConversation", - "service": { - "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService", - "shortName": "ConversationalSearchService" - }, - "shortName": "DeleteConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.DeleteConversationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_conversation" - }, - "description": "Sample for DeleteConversation", - "file": "discoveryengine_v1_generated_conversational_search_service_delete_conversation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_DeleteConversation_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": "discoveryengine_v1_generated_conversational_search_service_delete_conversation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient", - "shortName": "ConversationalSearchServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.get_conversation", - "method": { - "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.GetConversation", - "service": { - "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService", - "shortName": "ConversationalSearchService" - }, - "shortName": "GetConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.GetConversationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1.types.Conversation", - "shortName": "get_conversation" - }, - "description": "Sample for GetConversation", - "file": "discoveryengine_v1_generated_conversational_search_service_get_conversation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_GetConversation_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": "discoveryengine_v1_generated_conversational_search_service_get_conversation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient", - "shortName": "ConversationalSearchServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.get_conversation", - "method": { - "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.GetConversation", - "service": { - "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService", - "shortName": "ConversationalSearchService" - }, - "shortName": "GetConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.GetConversationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1.types.Conversation", - "shortName": "get_conversation" - }, - "description": "Sample for GetConversation", - "file": "discoveryengine_v1_generated_conversational_search_service_get_conversation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_GetConversation_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": "discoveryengine_v1_generated_conversational_search_service_get_conversation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient", - "shortName": "ConversationalSearchServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.list_conversations", - "method": { - "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.ListConversations", - "service": { - "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService", - "shortName": "ConversationalSearchService" - }, - "shortName": "ListConversations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.ListConversationsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1.services.conversational_search_service.pagers.ListConversationsAsyncPager", - "shortName": "list_conversations" - }, - "description": "Sample for ListConversations", - "file": "discoveryengine_v1_generated_conversational_search_service_list_conversations_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_ListConversations_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": "discoveryengine_v1_generated_conversational_search_service_list_conversations_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient", - "shortName": "ConversationalSearchServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.list_conversations", - "method": { - "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.ListConversations", - "service": { - "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService", - "shortName": "ConversationalSearchService" - }, - "shortName": "ListConversations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.ListConversationsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1.services.conversational_search_service.pagers.ListConversationsPager", - "shortName": "list_conversations" - }, - "description": "Sample for ListConversations", - "file": "discoveryengine_v1_generated_conversational_search_service_list_conversations_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_ListConversations_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": "discoveryengine_v1_generated_conversational_search_service_list_conversations_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient", - "shortName": "ConversationalSearchServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.update_conversation", - "method": { - "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.UpdateConversation", - "service": { - "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService", - "shortName": "ConversationalSearchService" - }, - "shortName": "UpdateConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.UpdateConversationRequest" - }, - { - "name": "conversation", - "type": "google.cloud.discoveryengine_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, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1.types.Conversation", - "shortName": "update_conversation" - }, - "description": "Sample for UpdateConversation", - "file": "discoveryengine_v1_generated_conversational_search_service_update_conversation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_UpdateConversation_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": "discoveryengine_v1_generated_conversational_search_service_update_conversation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient", - "shortName": "ConversationalSearchServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.update_conversation", - "method": { - "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.UpdateConversation", - "service": { - "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService", - "shortName": "ConversationalSearchService" - }, - "shortName": "UpdateConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.UpdateConversationRequest" - }, - { - "name": "conversation", - "type": "google.cloud.discoveryengine_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, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1.types.Conversation", - "shortName": "update_conversation" - }, - "description": "Sample for UpdateConversation", - "file": "discoveryengine_v1_generated_conversational_search_service_update_conversation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_UpdateConversation_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": "discoveryengine_v1_generated_conversational_search_service_update_conversation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient", - "shortName": "DocumentServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient.create_document", - "method": { - "fullName": "google.cloud.discoveryengine.v1.DocumentService.CreateDocument", - "service": { - "fullName": "google.cloud.discoveryengine.v1.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "CreateDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.CreateDocumentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "document", - "type": "google.cloud.discoveryengine_v1.types.Document" - }, - { - "name": "document_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1.types.Document", - "shortName": "create_document" - }, - "description": "Sample for CreateDocument", - "file": "discoveryengine_v1_generated_document_service_create_document_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_DocumentService_CreateDocument_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": "discoveryengine_v1_generated_document_service_create_document_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient", - "shortName": "DocumentServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient.create_document", - "method": { - "fullName": "google.cloud.discoveryengine.v1.DocumentService.CreateDocument", - "service": { - "fullName": "google.cloud.discoveryengine.v1.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "CreateDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.CreateDocumentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "document", - "type": "google.cloud.discoveryengine_v1.types.Document" - }, - { - "name": "document_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1.types.Document", - "shortName": "create_document" - }, - "description": "Sample for CreateDocument", - "file": "discoveryengine_v1_generated_document_service_create_document_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_DocumentService_CreateDocument_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": "discoveryengine_v1_generated_document_service_create_document_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient", - "shortName": "DocumentServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient.delete_document", - "method": { - "fullName": "google.cloud.discoveryengine.v1.DocumentService.DeleteDocument", - "service": { - "fullName": "google.cloud.discoveryengine.v1.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "DeleteDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.DeleteDocumentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_document" - }, - "description": "Sample for DeleteDocument", - "file": "discoveryengine_v1_generated_document_service_delete_document_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_DocumentService_DeleteDocument_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": "discoveryengine_v1_generated_document_service_delete_document_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient", - "shortName": "DocumentServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient.delete_document", - "method": { - "fullName": "google.cloud.discoveryengine.v1.DocumentService.DeleteDocument", - "service": { - "fullName": "google.cloud.discoveryengine.v1.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "DeleteDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.DeleteDocumentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_document" - }, - "description": "Sample for DeleteDocument", - "file": "discoveryengine_v1_generated_document_service_delete_document_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_DocumentService_DeleteDocument_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": "discoveryengine_v1_generated_document_service_delete_document_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient", - "shortName": "DocumentServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient.get_document", - "method": { - "fullName": "google.cloud.discoveryengine.v1.DocumentService.GetDocument", - "service": { - "fullName": "google.cloud.discoveryengine.v1.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "GetDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.GetDocumentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1.types.Document", - "shortName": "get_document" - }, - "description": "Sample for GetDocument", - "file": "discoveryengine_v1_generated_document_service_get_document_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_DocumentService_GetDocument_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": "discoveryengine_v1_generated_document_service_get_document_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient", - "shortName": "DocumentServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient.get_document", - "method": { - "fullName": "google.cloud.discoveryengine.v1.DocumentService.GetDocument", - "service": { - "fullName": "google.cloud.discoveryengine.v1.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "GetDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.GetDocumentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1.types.Document", - "shortName": "get_document" - }, - "description": "Sample for GetDocument", - "file": "discoveryengine_v1_generated_document_service_get_document_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_DocumentService_GetDocument_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": "discoveryengine_v1_generated_document_service_get_document_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient", - "shortName": "DocumentServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient.import_documents", - "method": { - "fullName": "google.cloud.discoveryengine.v1.DocumentService.ImportDocuments", - "service": { - "fullName": "google.cloud.discoveryengine.v1.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "ImportDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.ImportDocumentsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "import_documents" - }, - "description": "Sample for ImportDocuments", - "file": "discoveryengine_v1_generated_document_service_import_documents_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_DocumentService_ImportDocuments_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": "discoveryengine_v1_generated_document_service_import_documents_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient", - "shortName": "DocumentServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient.import_documents", - "method": { - "fullName": "google.cloud.discoveryengine.v1.DocumentService.ImportDocuments", - "service": { - "fullName": "google.cloud.discoveryengine.v1.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "ImportDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.ImportDocumentsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "import_documents" - }, - "description": "Sample for ImportDocuments", - "file": "discoveryengine_v1_generated_document_service_import_documents_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_DocumentService_ImportDocuments_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": "discoveryengine_v1_generated_document_service_import_documents_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient", - "shortName": "DocumentServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient.list_documents", - "method": { - "fullName": "google.cloud.discoveryengine.v1.DocumentService.ListDocuments", - "service": { - "fullName": "google.cloud.discoveryengine.v1.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "ListDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.ListDocumentsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1.services.document_service.pagers.ListDocumentsAsyncPager", - "shortName": "list_documents" - }, - "description": "Sample for ListDocuments", - "file": "discoveryengine_v1_generated_document_service_list_documents_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_DocumentService_ListDocuments_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": "discoveryengine_v1_generated_document_service_list_documents_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient", - "shortName": "DocumentServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient.list_documents", - "method": { - "fullName": "google.cloud.discoveryengine.v1.DocumentService.ListDocuments", - "service": { - "fullName": "google.cloud.discoveryengine.v1.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "ListDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.ListDocumentsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1.services.document_service.pagers.ListDocumentsPager", - "shortName": "list_documents" - }, - "description": "Sample for ListDocuments", - "file": "discoveryengine_v1_generated_document_service_list_documents_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_DocumentService_ListDocuments_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": "discoveryengine_v1_generated_document_service_list_documents_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient", - "shortName": "DocumentServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient.purge_documents", - "method": { - "fullName": "google.cloud.discoveryengine.v1.DocumentService.PurgeDocuments", - "service": { - "fullName": "google.cloud.discoveryengine.v1.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "PurgeDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.PurgeDocumentsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "purge_documents" - }, - "description": "Sample for PurgeDocuments", - "file": "discoveryengine_v1_generated_document_service_purge_documents_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_DocumentService_PurgeDocuments_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": "discoveryengine_v1_generated_document_service_purge_documents_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient", - "shortName": "DocumentServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient.purge_documents", - "method": { - "fullName": "google.cloud.discoveryengine.v1.DocumentService.PurgeDocuments", - "service": { - "fullName": "google.cloud.discoveryengine.v1.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "PurgeDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.PurgeDocumentsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "purge_documents" - }, - "description": "Sample for PurgeDocuments", - "file": "discoveryengine_v1_generated_document_service_purge_documents_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_DocumentService_PurgeDocuments_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": "discoveryengine_v1_generated_document_service_purge_documents_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient", - "shortName": "DocumentServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient.update_document", - "method": { - "fullName": "google.cloud.discoveryengine.v1.DocumentService.UpdateDocument", - "service": { - "fullName": "google.cloud.discoveryengine.v1.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "UpdateDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.UpdateDocumentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1.types.Document", - "shortName": "update_document" - }, - "description": "Sample for UpdateDocument", - "file": "discoveryengine_v1_generated_document_service_update_document_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_DocumentService_UpdateDocument_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": "discoveryengine_v1_generated_document_service_update_document_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient", - "shortName": "DocumentServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient.update_document", - "method": { - "fullName": "google.cloud.discoveryengine.v1.DocumentService.UpdateDocument", - "service": { - "fullName": "google.cloud.discoveryengine.v1.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "UpdateDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.UpdateDocumentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1.types.Document", - "shortName": "update_document" - }, - "description": "Sample for UpdateDocument", - "file": "discoveryengine_v1_generated_document_service_update_document_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_DocumentService_UpdateDocument_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": "discoveryengine_v1_generated_document_service_update_document_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient", - "shortName": "SchemaServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient.create_schema", - "method": { - "fullName": "google.cloud.discoveryengine.v1.SchemaService.CreateSchema", - "service": { - "fullName": "google.cloud.discoveryengine.v1.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "CreateSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.CreateSchemaRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "schema", - "type": "google.cloud.discoveryengine_v1.types.Schema" - }, - { - "name": "schema_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_schema" - }, - "description": "Sample for CreateSchema", - "file": "discoveryengine_v1_generated_schema_service_create_schema_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_SchemaService_CreateSchema_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": "discoveryengine_v1_generated_schema_service_create_schema_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient", - "shortName": "SchemaServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient.create_schema", - "method": { - "fullName": "google.cloud.discoveryengine.v1.SchemaService.CreateSchema", - "service": { - "fullName": "google.cloud.discoveryengine.v1.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "CreateSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.CreateSchemaRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "schema", - "type": "google.cloud.discoveryengine_v1.types.Schema" - }, - { - "name": "schema_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_schema" - }, - "description": "Sample for CreateSchema", - "file": "discoveryengine_v1_generated_schema_service_create_schema_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_SchemaService_CreateSchema_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": "discoveryengine_v1_generated_schema_service_create_schema_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient", - "shortName": "SchemaServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient.delete_schema", - "method": { - "fullName": "google.cloud.discoveryengine.v1.SchemaService.DeleteSchema", - "service": { - "fullName": "google.cloud.discoveryengine.v1.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "DeleteSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.DeleteSchemaRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_schema" - }, - "description": "Sample for DeleteSchema", - "file": "discoveryengine_v1_generated_schema_service_delete_schema_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_SchemaService_DeleteSchema_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": "discoveryengine_v1_generated_schema_service_delete_schema_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient", - "shortName": "SchemaServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient.delete_schema", - "method": { - "fullName": "google.cloud.discoveryengine.v1.SchemaService.DeleteSchema", - "service": { - "fullName": "google.cloud.discoveryengine.v1.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "DeleteSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.DeleteSchemaRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_schema" - }, - "description": "Sample for DeleteSchema", - "file": "discoveryengine_v1_generated_schema_service_delete_schema_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_SchemaService_DeleteSchema_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": "discoveryengine_v1_generated_schema_service_delete_schema_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient", - "shortName": "SchemaServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient.get_schema", - "method": { - "fullName": "google.cloud.discoveryengine.v1.SchemaService.GetSchema", - "service": { - "fullName": "google.cloud.discoveryengine.v1.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "GetSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.GetSchemaRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1.types.Schema", - "shortName": "get_schema" - }, - "description": "Sample for GetSchema", - "file": "discoveryengine_v1_generated_schema_service_get_schema_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_SchemaService_GetSchema_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": "discoveryengine_v1_generated_schema_service_get_schema_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient", - "shortName": "SchemaServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient.get_schema", - "method": { - "fullName": "google.cloud.discoveryengine.v1.SchemaService.GetSchema", - "service": { - "fullName": "google.cloud.discoveryengine.v1.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "GetSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.GetSchemaRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1.types.Schema", - "shortName": "get_schema" - }, - "description": "Sample for GetSchema", - "file": "discoveryengine_v1_generated_schema_service_get_schema_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_SchemaService_GetSchema_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": "discoveryengine_v1_generated_schema_service_get_schema_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient", - "shortName": "SchemaServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient.list_schemas", - "method": { - "fullName": "google.cloud.discoveryengine.v1.SchemaService.ListSchemas", - "service": { - "fullName": "google.cloud.discoveryengine.v1.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "ListSchemas" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.ListSchemasRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1.services.schema_service.pagers.ListSchemasAsyncPager", - "shortName": "list_schemas" - }, - "description": "Sample for ListSchemas", - "file": "discoveryengine_v1_generated_schema_service_list_schemas_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_SchemaService_ListSchemas_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": "discoveryengine_v1_generated_schema_service_list_schemas_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient", - "shortName": "SchemaServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient.list_schemas", - "method": { - "fullName": "google.cloud.discoveryengine.v1.SchemaService.ListSchemas", - "service": { - "fullName": "google.cloud.discoveryengine.v1.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "ListSchemas" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.ListSchemasRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1.services.schema_service.pagers.ListSchemasPager", - "shortName": "list_schemas" - }, - "description": "Sample for ListSchemas", - "file": "discoveryengine_v1_generated_schema_service_list_schemas_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_SchemaService_ListSchemas_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": "discoveryengine_v1_generated_schema_service_list_schemas_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient", - "shortName": "SchemaServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient.update_schema", - "method": { - "fullName": "google.cloud.discoveryengine.v1.SchemaService.UpdateSchema", - "service": { - "fullName": "google.cloud.discoveryengine.v1.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "UpdateSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.UpdateSchemaRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_schema" - }, - "description": "Sample for UpdateSchema", - "file": "discoveryengine_v1_generated_schema_service_update_schema_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_SchemaService_UpdateSchema_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "discoveryengine_v1_generated_schema_service_update_schema_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient", - "shortName": "SchemaServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient.update_schema", - "method": { - "fullName": "google.cloud.discoveryengine.v1.SchemaService.UpdateSchema", - "service": { - "fullName": "google.cloud.discoveryengine.v1.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "UpdateSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.UpdateSchemaRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_schema" - }, - "description": "Sample for UpdateSchema", - "file": "discoveryengine_v1_generated_schema_service_update_schema_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_SchemaService_UpdateSchema_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "discoveryengine_v1_generated_schema_service_update_schema_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1.SearchServiceAsyncClient", - "shortName": "SearchServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1.SearchServiceAsyncClient.search", - "method": { - "fullName": "google.cloud.discoveryengine.v1.SearchService.Search", - "service": { - "fullName": "google.cloud.discoveryengine.v1.SearchService", - "shortName": "SearchService" - }, - "shortName": "Search" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.SearchRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1.services.search_service.pagers.SearchAsyncPager", - "shortName": "search" - }, - "description": "Sample for Search", - "file": "discoveryengine_v1_generated_search_service_search_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_SearchService_Search_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": "discoveryengine_v1_generated_search_service_search_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1.SearchServiceClient", - "shortName": "SearchServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1.SearchServiceClient.search", - "method": { - "fullName": "google.cloud.discoveryengine.v1.SearchService.Search", - "service": { - "fullName": "google.cloud.discoveryengine.v1.SearchService", - "shortName": "SearchService" - }, - "shortName": "Search" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.SearchRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1.services.search_service.pagers.SearchPager", - "shortName": "search" - }, - "description": "Sample for Search", - "file": "discoveryengine_v1_generated_search_service_search_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_SearchService_Search_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": "discoveryengine_v1_generated_search_service_search_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1.UserEventServiceAsyncClient.collect_user_event", - "method": { - "fullName": "google.cloud.discoveryengine.v1.UserEventService.CollectUserEvent", - "service": { - "fullName": "google.cloud.discoveryengine.v1.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "CollectUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.CollectUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api.httpbody_pb2.HttpBody", - "shortName": "collect_user_event" - }, - "description": "Sample for CollectUserEvent", - "file": "discoveryengine_v1_generated_user_event_service_collect_user_event_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_UserEventService_CollectUserEvent_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": "discoveryengine_v1_generated_user_event_service_collect_user_event_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1.UserEventServiceClient.collect_user_event", - "method": { - "fullName": "google.cloud.discoveryengine.v1.UserEventService.CollectUserEvent", - "service": { - "fullName": "google.cloud.discoveryengine.v1.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "CollectUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.CollectUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api.httpbody_pb2.HttpBody", - "shortName": "collect_user_event" - }, - "description": "Sample for CollectUserEvent", - "file": "discoveryengine_v1_generated_user_event_service_collect_user_event_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_UserEventService_CollectUserEvent_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": "discoveryengine_v1_generated_user_event_service_collect_user_event_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1.UserEventServiceAsyncClient.import_user_events", - "method": { - "fullName": "google.cloud.discoveryengine.v1.UserEventService.ImportUserEvents", - "service": { - "fullName": "google.cloud.discoveryengine.v1.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "ImportUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.ImportUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "import_user_events" - }, - "description": "Sample for ImportUserEvents", - "file": "discoveryengine_v1_generated_user_event_service_import_user_events_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_UserEventService_ImportUserEvents_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": "discoveryengine_v1_generated_user_event_service_import_user_events_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1.UserEventServiceClient.import_user_events", - "method": { - "fullName": "google.cloud.discoveryengine.v1.UserEventService.ImportUserEvents", - "service": { - "fullName": "google.cloud.discoveryengine.v1.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "ImportUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.ImportUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "import_user_events" - }, - "description": "Sample for ImportUserEvents", - "file": "discoveryengine_v1_generated_user_event_service_import_user_events_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_UserEventService_ImportUserEvents_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": "discoveryengine_v1_generated_user_event_service_import_user_events_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1.UserEventServiceAsyncClient.write_user_event", - "method": { - "fullName": "google.cloud.discoveryengine.v1.UserEventService.WriteUserEvent", - "service": { - "fullName": "google.cloud.discoveryengine.v1.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "WriteUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.WriteUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1.types.UserEvent", - "shortName": "write_user_event" - }, - "description": "Sample for WriteUserEvent", - "file": "discoveryengine_v1_generated_user_event_service_write_user_event_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_UserEventService_WriteUserEvent_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": "discoveryengine_v1_generated_user_event_service_write_user_event_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1.UserEventServiceClient.write_user_event", - "method": { - "fullName": "google.cloud.discoveryengine.v1.UserEventService.WriteUserEvent", - "service": { - "fullName": "google.cloud.discoveryengine.v1.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "WriteUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1.types.WriteUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1.types.UserEvent", - "shortName": "write_user_event" - }, - "description": "Sample for WriteUserEvent", - "file": "discoveryengine_v1_generated_user_event_service_write_user_event_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1_generated_UserEventService_WriteUserEvent_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": "discoveryengine_v1_generated_user_event_service_write_user_event_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/scripts/fixup_discoveryengine_v1_keywords.py b/owl-bot-staging/google-cloud-discoveryengine/v1/scripts/fixup_discoveryengine_v1_keywords.py deleted file mode 100644 index 671ba001cfa9..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/scripts/fixup_discoveryengine_v1_keywords.py +++ /dev/null @@ -1,198 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class discoveryengineCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'collect_user_event': ('parent', 'user_event', 'uri', 'ets', ), - 'complete_query': ('data_store', 'query', 'query_model', 'user_pseudo_id', 'include_tail_suggestions', ), - 'converse_conversation': ('name', 'query', 'serving_config', 'conversation', 'safe_search', 'user_labels', 'summary_spec', ), - 'create_conversation': ('parent', 'conversation', ), - 'create_document': ('parent', 'document', 'document_id', ), - 'create_schema': ('parent', 'schema', 'schema_id', ), - 'delete_conversation': ('name', ), - 'delete_document': ('name', ), - 'delete_schema': ('name', ), - 'get_conversation': ('name', ), - 'get_document': ('name', ), - 'get_schema': ('name', ), - 'import_documents': ('parent', 'inline_source', 'gcs_source', 'bigquery_source', 'error_config', 'reconciliation_mode', 'auto_generate_ids', 'id_field', ), - 'import_user_events': ('parent', 'inline_source', 'gcs_source', 'bigquery_source', 'error_config', ), - 'list_conversations': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'list_documents': ('parent', 'page_size', 'page_token', ), - 'list_schemas': ('parent', 'page_size', 'page_token', ), - 'purge_documents': ('parent', 'filter', 'force', ), - 'search': ('serving_config', 'branch', 'query', 'image_query', 'page_size', 'page_token', 'offset', 'filter', 'order_by', 'user_info', 'facet_specs', 'boost_spec', 'params', 'query_expansion_spec', 'spell_correction_spec', 'user_pseudo_id', 'content_search_spec', 'safe_search', 'user_labels', ), - 'update_conversation': ('conversation', 'update_mask', ), - 'update_document': ('document', 'allow_missing', ), - 'update_schema': ('schema', 'allow_missing', ), - 'write_user_event': ('parent', 'user_event', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=discoveryengineCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the discoveryengine client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/setup.py b/owl-bot-staging/google-cloud-discoveryengine/v1/setup.py deleted file mode 100644 index 513896d68575..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/setup.py +++ /dev/null @@ -1,90 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-discoveryengine' - - -description = "Google Cloud Discoveryengine API client library" - -version = {} -with open(os.path.join(package_root, 'google/cloud/discoveryengine/gapic_version.py')) as fp: - exec(fp.read(), version) -version = version["__version__"] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "proto-plus >= 1.22.0, <2.0.0dev", - "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", - "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", -] -url = "https://github.com/googleapis/python-discoveryengine" - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, "README.rst") -with io.open(readme_filename, encoding="utf-8") as readme_file: - readme = readme_file.read() - -packages = [ - package - for package in setuptools.PEP420PackageFinder.find() - if package.startswith("google") -] - -namespaces = ["google", "google.cloud"] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - namespace_packages=namespaces, - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.10.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.10.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.11.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.11.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.12.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.12.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.7.txt deleted file mode 100644 index 6c44adfea7ee..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.7.txt +++ /dev/null @@ -1,9 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.0 -proto-plus==1.22.0 -protobuf==3.19.5 diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.8.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.8.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.9.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/testing/constraints-3.9.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/tests/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/tests/__init__.py deleted file mode 100644 index 1b4db446eb8d..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/__init__.py deleted file mode 100644 index 1b4db446eb8d..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 1b4db446eb8d..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/__init__.py deleted file mode 100644 index 1b4db446eb8d..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_completion_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_completion_service.py deleted file mode 100644 index 415348b10cc9..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_completion_service.py +++ /dev/null @@ -1,1920 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.discoveryengine_v1.services.completion_service import CompletionServiceAsyncClient -from google.cloud.discoveryengine_v1.services.completion_service import CompletionServiceClient -from google.cloud.discoveryengine_v1.services.completion_service import transports -from google.cloud.discoveryengine_v1.types import completion_service -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert CompletionServiceClient._get_default_mtls_endpoint(None) is None - assert CompletionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (CompletionServiceClient, "grpc"), - (CompletionServiceAsyncClient, "grpc_asyncio"), - (CompletionServiceClient, "rest"), -]) -def test_completion_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.CompletionServiceGrpcTransport, "grpc"), - (transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.CompletionServiceRestTransport, "rest"), -]) -def test_completion_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", [ - (CompletionServiceClient, "grpc"), - (CompletionServiceAsyncClient, "grpc_asyncio"), - (CompletionServiceClient, "rest"), -]) -def test_completion_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -def test_completion_service_client_get_transport_class(): - transport = CompletionServiceClient.get_transport_class() - available_transports = [ - transports.CompletionServiceGrpcTransport, - transports.CompletionServiceRestTransport, - ] - assert transport in available_transports - - transport = CompletionServiceClient.get_transport_class("grpc") - assert transport == transports.CompletionServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (CompletionServiceClient, transports.CompletionServiceRestTransport, "rest"), -]) -@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) -@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) -def test_completion_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(CompletionServiceClient, '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(CompletionServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "true"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "false"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (CompletionServiceClient, transports.CompletionServiceRestTransport, "rest", "true"), - (CompletionServiceClient, transports.CompletionServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) -@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_completion_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 - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - CompletionServiceClient, CompletionServiceAsyncClient -]) -@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) -@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) -def test_completion_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (CompletionServiceClient, transports.CompletionServiceRestTransport, "rest"), -]) -def test_completion_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, - 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", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (CompletionServiceClient, transports.CompletionServiceRestTransport, "rest", None), -]) -def test_completion_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, - scopes=None, - client_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_completion_service_client_client_options_from_dict(): - with mock.patch('google.cloud.discoveryengine_v1.services.completion_service.transports.CompletionServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = CompletionServiceClient( - 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", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_completion_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, - scopes=None, - client_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - completion_service.CompleteQueryRequest, - dict, -]) -def test_complete_query(request_type, transport: str = 'grpc'): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = completion_service.CompleteQueryResponse( - tail_match_triggered=True, - ) - response = client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, completion_service.CompleteQueryResponse) - assert response.tail_match_triggered is True - - -def test_complete_query_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - client.complete_query() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - -@pytest.mark.asyncio -async def test_complete_query_async(transport: str = 'grpc_asyncio', request_type=completion_service.CompleteQueryRequest): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse( - tail_match_triggered=True, - )) - response = await client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, completion_service.CompleteQueryResponse) - assert response.tail_match_triggered is True - - -@pytest.mark.asyncio -async def test_complete_query_async_from_dict(): - await test_complete_query_async(request_type=dict) - - -def test_complete_query_field_headers(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = completion_service.CompleteQueryRequest() - - request.data_store = 'data_store_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - call.return_value = completion_service.CompleteQueryResponse() - client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'data_store=data_store_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_complete_query_field_headers_async(): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = completion_service.CompleteQueryRequest() - - request.data_store = 'data_store_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse()) - await client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'data_store=data_store_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - completion_service.CompleteQueryRequest, - dict, -]) -def test_complete_query_rest(request_type): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'data_store': 'projects/sample1/locations/sample2/dataStores/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 = completion_service.CompleteQueryResponse( - tail_match_triggered=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = completion_service.CompleteQueryResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.complete_query(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, completion_service.CompleteQueryResponse) - assert response.tail_match_triggered is True - - -def test_complete_query_rest_required_fields(request_type=completion_service.CompleteQueryRequest): - transport_class = transports.CompletionServiceRestTransport - - request_init = {} - request_init["data_store"] = "" - request_init["query"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "query" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).complete_query._get_unset_required_fields(jsonified_request) - 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["dataStore"] = 'data_store_value' - jsonified_request["query"] = 'query_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).complete_query._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("include_tail_suggestions", "query", "query_model", "user_pseudo_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "dataStore" in jsonified_request - assert jsonified_request["dataStore"] == 'data_store_value' - assert "query" in jsonified_request - assert jsonified_request["query"] == 'query_value' - - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = completion_service.CompleteQueryResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = completion_service.CompleteQueryResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.complete_query(request) - - expected_params = [ - ( - "query", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_complete_query_rest_unset_required_fields(): - transport = transports.CompletionServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.complete_query._get_unset_required_fields({}) - assert set(unset_fields) == (set(("includeTailSuggestions", "query", "queryModel", "userPseudoId", )) & set(("dataStore", "query", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_complete_query_rest_interceptors(null_interceptor): - transport = transports.CompletionServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.CompletionServiceRestInterceptor(), - ) - client = CompletionServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.CompletionServiceRestInterceptor, "post_complete_query") as post, \ - mock.patch.object(transports.CompletionServiceRestInterceptor, "pre_complete_query") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = completion_service.CompleteQueryRequest.pb(completion_service.CompleteQueryRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = completion_service.CompleteQueryResponse.to_json(completion_service.CompleteQueryResponse()) - - request = completion_service.CompleteQueryRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = completion_service.CompleteQueryResponse() - - client.complete_query(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_complete_query_rest_bad_request(transport: str = 'rest', request_type=completion_service.CompleteQueryRequest): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'data_store': 'projects/sample1/locations/sample2/dataStores/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.complete_query(request) - - -def test_complete_query_rest_error(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = CompletionServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.CompletionServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.CompletionServiceGrpcTransport, - transports.CompletionServiceGrpcAsyncIOTransport, - transports.CompletionServiceRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = CompletionServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.CompletionServiceGrpcTransport, - ) - -def test_completion_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.CompletionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_completion_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.discoveryengine_v1.services.completion_service.transports.CompletionServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.CompletionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'complete_query', - 'get_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_completion_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.discoveryengine_v1.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CompletionServiceTransport( - 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_completion_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.discoveryengine_v1.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CompletionServiceTransport() - adc.assert_called_once() - - -def test_completion_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) - CompletionServiceClient() - 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.CompletionServiceGrpcTransport, - transports.CompletionServiceGrpcAsyncIOTransport, - ], -) -def test_completion_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.CompletionServiceGrpcTransport, - transports.CompletionServiceGrpcAsyncIOTransport, - transports.CompletionServiceRestTransport, - ], -) -def test_completion_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.CompletionServiceGrpcTransport, grpc_helpers), - (transports.CompletionServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_completion_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) -def test_completion_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_completion_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.CompletionServiceRestTransport ( - 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_completion_service_host_no_port(transport_name): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_completion_service_host_with_port(transport_name): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_completion_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = CompletionServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = CompletionServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.complete_query._session - session2 = client2.transport.complete_query._session - assert session1 != session2 -def test_completion_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CompletionServiceGrpcTransport( - 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_completion_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CompletionServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) -def test_completion_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.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) -def test_completion_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_data_store_path(): - project = "squid" - location = "clam" - data_store = "whelk" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) - actual = CompletionServiceClient.data_store_path(project, location, data_store) - assert expected == actual - - -def test_parse_data_store_path(): - expected = { - "project": "octopus", - "location": "oyster", - "data_store": "nudibranch", - } - path = CompletionServiceClient.data_store_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_data_store_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = CompletionServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = CompletionServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = CompletionServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = CompletionServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = CompletionServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = CompletionServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = CompletionServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = CompletionServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = CompletionServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = CompletionServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.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.CompletionServiceTransport, '_prep_wrapped_messages') as prep: - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = CompletionServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = CompletionServiceClient( - 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(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_get_operation(transport: str = "grpc"): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = CompletionServiceClient( - 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 = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = CompletionServiceClient( - 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 = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = CompletionServiceClient( - 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", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_conversational_search_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_conversational_search_service.py deleted file mode 100644 index 777c4fb62bce..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_conversational_search_service.py +++ /dev/null @@ -1,4902 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.discoveryengine_v1.services.conversational_search_service import ConversationalSearchServiceAsyncClient -from google.cloud.discoveryengine_v1.services.conversational_search_service import ConversationalSearchServiceClient -from google.cloud.discoveryengine_v1.services.conversational_search_service import pagers -from google.cloud.discoveryengine_v1.services.conversational_search_service import transports -from google.cloud.discoveryengine_v1.types import conversation -from google.cloud.discoveryengine_v1.types import conversation as gcd_conversation -from google.cloud.discoveryengine_v1.types import conversational_search_service -from google.cloud.discoveryengine_v1.types import search_service -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert ConversationalSearchServiceClient._get_default_mtls_endpoint(None) is None - assert ConversationalSearchServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ConversationalSearchServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ConversationalSearchServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ConversationalSearchServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ConversationalSearchServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ConversationalSearchServiceClient, "grpc"), - (ConversationalSearchServiceAsyncClient, "grpc_asyncio"), - (ConversationalSearchServiceClient, "rest"), -]) -def test_conversational_search_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ConversationalSearchServiceGrpcTransport, "grpc"), - (transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ConversationalSearchServiceRestTransport, "rest"), -]) -def test_conversational_search_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", [ - (ConversationalSearchServiceClient, "grpc"), - (ConversationalSearchServiceAsyncClient, "grpc_asyncio"), - (ConversationalSearchServiceClient, "rest"), -]) -def test_conversational_search_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -def test_conversational_search_service_client_get_transport_class(): - transport = ConversationalSearchServiceClient.get_transport_class() - available_transports = [ - transports.ConversationalSearchServiceGrpcTransport, - transports.ConversationalSearchServiceRestTransport, - ] - assert transport in available_transports - - transport = ConversationalSearchServiceClient.get_transport_class("grpc") - assert transport == transports.ConversationalSearchServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport, "grpc"), - (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (ConversationalSearchServiceClient, transports.ConversationalSearchServiceRestTransport, "rest"), -]) -@mock.patch.object(ConversationalSearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationalSearchServiceClient)) -@mock.patch.object(ConversationalSearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationalSearchServiceAsyncClient)) -def test_conversational_search_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(ConversationalSearchServiceClient, '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(ConversationalSearchServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport, "grpc", "true"), - (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport, "grpc", "false"), - (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (ConversationalSearchServiceClient, transports.ConversationalSearchServiceRestTransport, "rest", "true"), - (ConversationalSearchServiceClient, transports.ConversationalSearchServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(ConversationalSearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationalSearchServiceClient)) -@mock.patch.object(ConversationalSearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationalSearchServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_conversational_search_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 - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - ConversationalSearchServiceClient, ConversationalSearchServiceAsyncClient -]) -@mock.patch.object(ConversationalSearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationalSearchServiceClient)) -@mock.patch.object(ConversationalSearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationalSearchServiceAsyncClient)) -def test_conversational_search_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport, "grpc"), - (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (ConversationalSearchServiceClient, transports.ConversationalSearchServiceRestTransport, "rest"), -]) -def test_conversational_search_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, - 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", [ - (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport, "grpc", grpc_helpers), - (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (ConversationalSearchServiceClient, transports.ConversationalSearchServiceRestTransport, "rest", None), -]) -def test_conversational_search_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, - scopes=None, - client_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_conversational_search_service_client_client_options_from_dict(): - with mock.patch('google.cloud.discoveryengine_v1.services.conversational_search_service.transports.ConversationalSearchServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ConversationalSearchServiceClient( - 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", [ - (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport, "grpc", grpc_helpers), - (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_conversational_search_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, - scopes=None, - client_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - conversational_search_service.ConverseConversationRequest, - dict, -]) -def test_converse_conversation(request_type, transport: str = 'grpc'): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.converse_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversational_search_service.ConverseConversationResponse( - ) - response = client.converse_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] == conversational_search_service.ConverseConversationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, conversational_search_service.ConverseConversationResponse) - - -def test_converse_conversation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.converse_conversation), - '__call__') as call: - client.converse_conversation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversational_search_service.ConverseConversationRequest() - -@pytest.mark.asyncio -async def test_converse_conversation_async(transport: str = 'grpc_asyncio', request_type=conversational_search_service.ConverseConversationRequest): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.converse_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversational_search_service.ConverseConversationResponse( - )) - response = await client.converse_conversation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == conversational_search_service.ConverseConversationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, conversational_search_service.ConverseConversationResponse) - - -@pytest.mark.asyncio -async def test_converse_conversation_async_from_dict(): - await test_converse_conversation_async(request_type=dict) - - -def test_converse_conversation_field_headers(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversational_search_service.ConverseConversationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.converse_conversation), - '__call__') as call: - call.return_value = conversational_search_service.ConverseConversationResponse() - client.converse_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', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_converse_conversation_field_headers_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversational_search_service.ConverseConversationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.converse_conversation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversational_search_service.ConverseConversationResponse()) - await client.converse_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', - 'name=name_value', - ) in kw['metadata'] - - -def test_converse_conversation_flattened(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.converse_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversational_search_service.ConverseConversationResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.converse_conversation( - name='name_value', - query=conversation.TextInput(input='input_value'), - ) - - # Establish that the 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].query - mock_val = conversation.TextInput(input='input_value') - assert arg == mock_val - - -def test_converse_conversation_flattened_error(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.converse_conversation( - conversational_search_service.ConverseConversationRequest(), - name='name_value', - query=conversation.TextInput(input='input_value'), - ) - -@pytest.mark.asyncio -async def test_converse_conversation_flattened_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.converse_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversational_search_service.ConverseConversationResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversational_search_service.ConverseConversationResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.converse_conversation( - name='name_value', - query=conversation.TextInput(input='input_value'), - ) - - # Establish that 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].query - mock_val = conversation.TextInput(input='input_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_converse_conversation_flattened_error_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.converse_conversation( - conversational_search_service.ConverseConversationRequest(), - name='name_value', - query=conversation.TextInput(input='input_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - conversational_search_service.CreateConversationRequest, - dict, -]) -def test_create_conversation(request_type, transport: str = 'grpc'): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_conversation.Conversation( - name='name_value', - state=gcd_conversation.Conversation.State.IN_PROGRESS, - user_pseudo_id='user_pseudo_id_value', - ) - response = client.create_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] == conversational_search_service.CreateConversationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_conversation.Conversation) - assert response.name == 'name_value' - assert response.state == gcd_conversation.Conversation.State.IN_PROGRESS - assert response.user_pseudo_id == 'user_pseudo_id_value' - - -def test_create_conversation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_conversation), - '__call__') as call: - client.create_conversation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversational_search_service.CreateConversationRequest() - -@pytest.mark.asyncio -async def test_create_conversation_async(transport: str = 'grpc_asyncio', request_type=conversational_search_service.CreateConversationRequest): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation.Conversation( - name='name_value', - state=gcd_conversation.Conversation.State.IN_PROGRESS, - user_pseudo_id='user_pseudo_id_value', - )) - response = await client.create_conversation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == conversational_search_service.CreateConversationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_conversation.Conversation) - assert response.name == 'name_value' - assert response.state == gcd_conversation.Conversation.State.IN_PROGRESS - assert response.user_pseudo_id == 'user_pseudo_id_value' - - -@pytest.mark.asyncio -async def test_create_conversation_async_from_dict(): - await test_create_conversation_async(request_type=dict) - - -def test_create_conversation_field_headers(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversational_search_service.CreateConversationRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_conversation), - '__call__') as call: - call.return_value = gcd_conversation.Conversation() - client.create_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', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_conversation_field_headers_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversational_search_service.CreateConversationRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_conversation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation.Conversation()) - await client.create_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', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_conversation_flattened(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_conversation.Conversation() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_conversation( - parent='parent_value', - conversation=gcd_conversation.Conversation(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].conversation - mock_val = gcd_conversation.Conversation(name='name_value') - assert arg == mock_val - - -def test_create_conversation_flattened_error(): - client = ConversationalSearchServiceClient( - credentials=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_conversation( - conversational_search_service.CreateConversationRequest(), - parent='parent_value', - conversation=gcd_conversation.Conversation(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_conversation_flattened_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_conversation.Conversation() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation.Conversation()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_conversation( - parent='parent_value', - conversation=gcd_conversation.Conversation(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].conversation - mock_val = gcd_conversation.Conversation(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_conversation_flattened_error_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_conversation( - conversational_search_service.CreateConversationRequest(), - parent='parent_value', - conversation=gcd_conversation.Conversation(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - conversational_search_service.DeleteConversationRequest, - dict, -]) -def test_delete_conversation(request_type, transport: str = 'grpc'): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_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] == conversational_search_service.DeleteConversationRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_conversation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_conversation), - '__call__') as call: - client.delete_conversation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversational_search_service.DeleteConversationRequest() - -@pytest.mark.asyncio -async def test_delete_conversation_async(transport: str = 'grpc_asyncio', request_type=conversational_search_service.DeleteConversationRequest): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_conversation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == conversational_search_service.DeleteConversationRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_conversation_async_from_dict(): - await test_delete_conversation_async(request_type=dict) - - -def test_delete_conversation_field_headers(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversational_search_service.DeleteConversationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_conversation), - '__call__') as call: - call.return_value = None - client.delete_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', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_conversation_field_headers_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversational_search_service.DeleteConversationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_conversation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_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', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_conversation_flattened(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, 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 = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_conversation( - 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_conversation_flattened_error(): - client = ConversationalSearchServiceClient( - credentials=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_conversation( - conversational_search_service.DeleteConversationRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_conversation_flattened_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, 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 = 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_conversation( - 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_conversation_flattened_error_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_conversation( - conversational_search_service.DeleteConversationRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - conversational_search_service.UpdateConversationRequest, - dict, -]) -def test_update_conversation(request_type, transport: str = 'grpc'): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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 = gcd_conversation.Conversation( - name='name_value', - state=gcd_conversation.Conversation.State.IN_PROGRESS, - user_pseudo_id='user_pseudo_id_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] - assert args[0] == conversational_search_service.UpdateConversationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_conversation.Conversation) - assert response.name == 'name_value' - assert response.state == gcd_conversation.Conversation.State.IN_PROGRESS - assert response.user_pseudo_id == 'user_pseudo_id_value' - - -def test_update_conversation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_conversation), - '__call__') as call: - client.update_conversation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversational_search_service.UpdateConversationRequest() - -@pytest.mark.asyncio -async def test_update_conversation_async(transport: str = 'grpc_asyncio', request_type=conversational_search_service.UpdateConversationRequest): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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(gcd_conversation.Conversation( - name='name_value', - state=gcd_conversation.Conversation.State.IN_PROGRESS, - user_pseudo_id='user_pseudo_id_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] - assert args[0] == conversational_search_service.UpdateConversationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_conversation.Conversation) - assert response.name == 'name_value' - assert response.state == gcd_conversation.Conversation.State.IN_PROGRESS - assert response.user_pseudo_id == 'user_pseudo_id_value' - - -@pytest.mark.asyncio -async def test_update_conversation_async_from_dict(): - await test_update_conversation_async(request_type=dict) - - -def test_update_conversation_field_headers(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversational_search_service.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 = gcd_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 = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversational_search_service.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(gcd_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 = ConversationalSearchServiceClient( - 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 = gcd_conversation.Conversation() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_conversation( - conversation=gcd_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 = gcd_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 = ConversationalSearchServiceClient( - credentials=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( - conversational_search_service.UpdateConversationRequest(), - conversation=gcd_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 = ConversationalSearchServiceAsyncClient( - 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 = gcd_conversation.Conversation() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_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=gcd_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 = gcd_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 = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_conversation( - conversational_search_service.UpdateConversationRequest(), - conversation=gcd_conversation.Conversation(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - conversational_search_service.GetConversationRequest, - dict, -]) -def test_get_conversation(request_type, transport: str = 'grpc'): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation.Conversation( - name='name_value', - state=conversation.Conversation.State.IN_PROGRESS, - user_pseudo_id='user_pseudo_id_value', - ) - response = client.get_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] == conversational_search_service.GetConversationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, conversation.Conversation) - assert response.name == 'name_value' - assert response.state == conversation.Conversation.State.IN_PROGRESS - assert response.user_pseudo_id == 'user_pseudo_id_value' - - -def test_get_conversation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_conversation), - '__call__') as call: - client.get_conversation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversational_search_service.GetConversationRequest() - -@pytest.mark.asyncio -async def test_get_conversation_async(transport: str = 'grpc_asyncio', request_type=conversational_search_service.GetConversationRequest): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation( - name='name_value', - state=conversation.Conversation.State.IN_PROGRESS, - user_pseudo_id='user_pseudo_id_value', - )) - response = await client.get_conversation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == conversational_search_service.GetConversationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, conversation.Conversation) - assert response.name == 'name_value' - assert response.state == conversation.Conversation.State.IN_PROGRESS - assert response.user_pseudo_id == 'user_pseudo_id_value' - - -@pytest.mark.asyncio -async def test_get_conversation_async_from_dict(): - await test_get_conversation_async(request_type=dict) - - -def test_get_conversation_field_headers(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversational_search_service.GetConversationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_conversation), - '__call__') as call: - call.return_value = conversation.Conversation() - client.get_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', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_conversation_field_headers_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversational_search_service.GetConversationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_conversation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation()) - await client.get_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', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_conversation_flattened(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation.Conversation() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_conversation( - 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_conversation_flattened_error(): - client = ConversationalSearchServiceClient( - credentials=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_conversation( - conversational_search_service.GetConversationRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_conversation_flattened_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation.Conversation() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_conversation( - 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_conversation_flattened_error_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_conversation( - conversational_search_service.GetConversationRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - conversational_search_service.ListConversationsRequest, - dict, -]) -def test_list_conversations(request_type, transport: str = 'grpc'): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_conversations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversational_search_service.ListConversationsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_conversations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == conversational_search_service.ListConversationsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConversationsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_conversations_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversations), - '__call__') as call: - client.list_conversations() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversational_search_service.ListConversationsRequest() - -@pytest.mark.asyncio -async def test_list_conversations_async(transport: str = 'grpc_asyncio', request_type=conversational_search_service.ListConversationsRequest): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_conversations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversational_search_service.ListConversationsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_conversations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == conversational_search_service.ListConversationsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConversationsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_conversations_async_from_dict(): - await test_list_conversations_async(request_type=dict) - - -def test_list_conversations_field_headers(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversational_search_service.ListConversationsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversations), - '__call__') as call: - call.return_value = conversational_search_service.ListConversationsResponse() - client.list_conversations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_conversations_field_headers_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversational_search_service.ListConversationsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversations), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversational_search_service.ListConversationsResponse()) - await client.list_conversations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_conversations_flattened(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversational_search_service.ListConversationsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_conversations( - 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_conversations_flattened_error(): - client = ConversationalSearchServiceClient( - credentials=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_conversations( - conversational_search_service.ListConversationsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_conversations_flattened_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversational_search_service.ListConversationsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversational_search_service.ListConversationsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_conversations( - 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_conversations_flattened_error_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_conversations( - conversational_search_service.ListConversationsRequest(), - parent='parent_value', - ) - - -def test_list_conversations_pager(transport_name: str = "grpc"): - client = ConversationalSearchServiceClient( - 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_conversations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - conversation.Conversation(), - ], - next_page_token='abc', - ), - conversational_search_service.ListConversationsResponse( - conversations=[], - next_page_token='def', - ), - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - ], - next_page_token='ghi', - ), - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_conversations(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, conversation.Conversation) - for i in results) -def test_list_conversations_pages(transport_name: str = "grpc"): - client = ConversationalSearchServiceClient( - 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_conversations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - conversation.Conversation(), - ], - next_page_token='abc', - ), - conversational_search_service.ListConversationsResponse( - conversations=[], - next_page_token='def', - ), - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - ], - next_page_token='ghi', - ), - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - ], - ), - RuntimeError, - ) - pages = list(client.list_conversations(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_conversations_async_pager(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - conversation.Conversation(), - ], - next_page_token='abc', - ), - conversational_search_service.ListConversationsResponse( - conversations=[], - next_page_token='def', - ), - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - ], - next_page_token='ghi', - ), - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_conversations(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, conversation.Conversation) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_conversations_async_pages(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - conversation.Conversation(), - ], - next_page_token='abc', - ), - conversational_search_service.ListConversationsResponse( - conversations=[], - next_page_token='def', - ), - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - ], - next_page_token='ghi', - ), - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_conversations(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", [ - conversational_search_service.ConverseConversationRequest, - dict, -]) -def test_converse_conversation_rest(request_type): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/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 = conversational_search_service.ConverseConversationResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = conversational_search_service.ConverseConversationResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.converse_conversation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, conversational_search_service.ConverseConversationResponse) - - -def test_converse_conversation_rest_required_fields(request_type=conversational_search_service.ConverseConversationRequest): - transport_class = transports.ConversationalSearchServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).converse_conversation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).converse_conversation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = conversational_search_service.ConverseConversationResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = conversational_search_service.ConverseConversationResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.converse_conversation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_converse_conversation_rest_unset_required_fields(): - transport = transports.ConversationalSearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.converse_conversation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "query", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_converse_conversation_rest_interceptors(null_interceptor): - transport = transports.ConversationalSearchServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationalSearchServiceRestInterceptor(), - ) - client = ConversationalSearchServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "post_converse_conversation") as post, \ - mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "pre_converse_conversation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversational_search_service.ConverseConversationRequest.pb(conversational_search_service.ConverseConversationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = conversational_search_service.ConverseConversationResponse.to_json(conversational_search_service.ConverseConversationResponse()) - - request = conversational_search_service.ConverseConversationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = conversational_search_service.ConverseConversationResponse() - - client.converse_conversation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_converse_conversation_rest_bad_request(transport: str = 'rest', request_type=conversational_search_service.ConverseConversationRequest): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.converse_conversation(request) - - -def test_converse_conversation_rest_flattened(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversational_search_service.ConverseConversationResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - query=conversation.TextInput(input='input_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 = conversational_search_service.ConverseConversationResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.converse_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/{name=projects/*/locations/*/dataStores/*/conversations/*}:converse" % client.transport._host, args[1]) - - -def test_converse_conversation_rest_flattened_error(transport: str = 'rest'): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.converse_conversation( - conversational_search_service.ConverseConversationRequest(), - name='name_value', - query=conversation.TextInput(input='input_value'), - ) - - -def test_converse_conversation_rest_error(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - conversational_search_service.CreateConversationRequest, - dict, -]) -def test_create_conversation_rest(request_type): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - request_init["conversation"] = {'name': 'name_value', 'state': 1, 'user_pseudo_id': 'user_pseudo_id_value', 'messages': [{'user_input': {'input': 'input_value', 'context': {'context_documents': ['context_documents_value1', 'context_documents_value2'], 'active_document': 'active_document_value'}}, 'reply': {'summary': {'summary_text': 'summary_text_value', 'summary_skipped_reasons': [1], 'safety_attributes': {'categories': ['categories_value1', 'categories_value2'], 'scores': [0.656, 0.657]}}}, 'create_time': {'seconds': 751, 'nanos': 543}}], 'start_time': {}, 'end_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 = conversational_search_service.CreateConversationRequest.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 = gcd_conversation.Conversation( - name='name_value', - state=gcd_conversation.Conversation.State.IN_PROGRESS, - user_pseudo_id='user_pseudo_id_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 = gcd_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 - response = client.create_conversation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_conversation.Conversation) - assert response.name == 'name_value' - assert response.state == gcd_conversation.Conversation.State.IN_PROGRESS - assert response.user_pseudo_id == 'user_pseudo_id_value' - - -def test_create_conversation_rest_required_fields(request_type=conversational_search_service.CreateConversationRequest): - transport_class = transports.ConversationalSearchServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_conversation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_conversation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_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': "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 = gcd_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 - - response = client.create_conversation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_conversation_rest_unset_required_fields(): - transport = transports.ConversationalSearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_conversation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "conversation", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_conversation_rest_interceptors(null_interceptor): - transport = transports.ConversationalSearchServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationalSearchServiceRestInterceptor(), - ) - client = ConversationalSearchServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "post_create_conversation") as post, \ - mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "pre_create_conversation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversational_search_service.CreateConversationRequest.pb(conversational_search_service.CreateConversationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_conversation.Conversation.to_json(gcd_conversation.Conversation()) - - request = conversational_search_service.CreateConversationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_conversation.Conversation() - - client.create_conversation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_conversation_rest_bad_request(transport: str = 'rest', request_type=conversational_search_service.CreateConversationRequest): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_conversation(request) - - -def test_create_conversation_rest_flattened(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_conversation.Conversation() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - conversation=gcd_conversation.Conversation(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 = gcd_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 - - client.create_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/{parent=projects/*/locations/*/dataStores/*}/conversations" % client.transport._host, args[1]) - - -def test_create_conversation_rest_flattened_error(transport: str = 'rest'): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.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_conversation( - conversational_search_service.CreateConversationRequest(), - parent='parent_value', - conversation=gcd_conversation.Conversation(name='name_value'), - ) - - -def test_create_conversation_rest_error(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - conversational_search_service.DeleteConversationRequest, - dict, -]) -def test_delete_conversation_rest(request_type): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/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 = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_conversation(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_conversation_rest_required_fields(request_type=conversational_search_service.DeleteConversationRequest): - transport_class = transports.ConversationalSearchServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_conversation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_conversation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ConversationalSearchServiceClient( - 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 - - response = client.delete_conversation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_conversation_rest_unset_required_fields(): - transport = transports.ConversationalSearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_conversation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_conversation_rest_interceptors(null_interceptor): - transport = transports.ConversationalSearchServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationalSearchServiceRestInterceptor(), - ) - client = ConversationalSearchServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "pre_delete_conversation") as pre: - pre.assert_not_called() - pb_message = conversational_search_service.DeleteConversationRequest.pb(conversational_search_service.DeleteConversationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = conversational_search_service.DeleteConversationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_conversation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_conversation_rest_bad_request(transport: str = 'rest', request_type=conversational_search_service.DeleteConversationRequest): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_conversation(request) - - -def test_delete_conversation_rest_flattened(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/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 = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_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/{name=projects/*/locations/*/dataStores/*/conversations/*}" % client.transport._host, args[1]) - - -def test_delete_conversation_rest_flattened_error(transport: str = 'rest'): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.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_conversation( - conversational_search_service.DeleteConversationRequest(), - name='name_value', - ) - - -def test_delete_conversation_rest_error(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - conversational_search_service.UpdateConversationRequest, - dict, -]) -def test_update_conversation_rest(request_type): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'conversation': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'}} - request_init["conversation"] = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4', 'state': 1, 'user_pseudo_id': 'user_pseudo_id_value', 'messages': [{'user_input': {'input': 'input_value', 'context': {'context_documents': ['context_documents_value1', 'context_documents_value2'], 'active_document': 'active_document_value'}}, 'reply': {'summary': {'summary_text': 'summary_text_value', 'summary_skipped_reasons': [1], 'safety_attributes': {'categories': ['categories_value1', 'categories_value2'], 'scores': [0.656, 0.657]}}}, 'create_time': {'seconds': 751, 'nanos': 543}}], 'start_time': {}, 'end_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 = conversational_search_service.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 = gcd_conversation.Conversation( - name='name_value', - state=gcd_conversation.Conversation.State.IN_PROGRESS, - user_pseudo_id='user_pseudo_id_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 = gcd_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 - response = client.update_conversation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_conversation.Conversation) - assert response.name == 'name_value' - assert response.state == gcd_conversation.Conversation.State.IN_PROGRESS - assert response.user_pseudo_id == 'user_pseudo_id_value' - - -def test_update_conversation_rest_required_fields(request_type=conversational_search_service.UpdateConversationRequest): - transport_class = transports.ConversationalSearchServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_conversation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_conversation._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_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 = gcd_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 - - response = client.update_conversation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_conversation_rest_unset_required_fields(): - transport = transports.ConversationalSearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_conversation._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("conversation", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_conversation_rest_interceptors(null_interceptor): - transport = transports.ConversationalSearchServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationalSearchServiceRestInterceptor(), - ) - client = ConversationalSearchServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "post_update_conversation") as post, \ - mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "pre_update_conversation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversational_search_service.UpdateConversationRequest.pb(conversational_search_service.UpdateConversationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_conversation.Conversation.to_json(gcd_conversation.Conversation()) - - request = conversational_search_service.UpdateConversationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_conversation.Conversation() - - client.update_conversation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_conversation_rest_bad_request(transport: str = 'rest', request_type=conversational_search_service.UpdateConversationRequest): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'conversation': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_conversation(request) - - -def test_update_conversation_rest_flattened(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_conversation.Conversation() - - # get arguments that satisfy an http rule for this method - sample_request = {'conversation': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'}} - - # get truthy value for each flattened field - mock_args = dict( - conversation=gcd_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 = gcd_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 - - 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/*/dataStores/*/conversations/*}" % client.transport._host, args[1]) - - -def test_update_conversation_rest_flattened_error(transport: str = 'rest'): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.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( - conversational_search_service.UpdateConversationRequest(), - conversation=gcd_conversation.Conversation(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_conversation_rest_error(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - conversational_search_service.GetConversationRequest, - dict, -]) -def test_get_conversation_rest(request_type): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/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 = conversation.Conversation( - name='name_value', - state=conversation.Conversation.State.IN_PROGRESS, - user_pseudo_id='user_pseudo_id_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 = 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 - response = client.get_conversation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, conversation.Conversation) - assert response.name == 'name_value' - assert response.state == conversation.Conversation.State.IN_PROGRESS - assert response.user_pseudo_id == 'user_pseudo_id_value' - - -def test_get_conversation_rest_required_fields(request_type=conversational_search_service.GetConversationRequest): - transport_class = transports.ConversationalSearchServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_conversation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_conversation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = 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': "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 = 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 - - response = client.get_conversation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_conversation_rest_unset_required_fields(): - transport = transports.ConversationalSearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_conversation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_conversation_rest_interceptors(null_interceptor): - transport = transports.ConversationalSearchServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationalSearchServiceRestInterceptor(), - ) - client = ConversationalSearchServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "post_get_conversation") as post, \ - mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "pre_get_conversation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversational_search_service.GetConversationRequest.pb(conversational_search_service.GetConversationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = conversation.Conversation.to_json(conversation.Conversation()) - - request = conversational_search_service.GetConversationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = conversation.Conversation() - - client.get_conversation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_conversation_rest_bad_request(transport: str = 'rest', request_type=conversational_search_service.GetConversationRequest): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_conversation(request) - - -def test_get_conversation_rest_flattened(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation.Conversation() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/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 = 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 - - client.get_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/{name=projects/*/locations/*/dataStores/*/conversations/*}" % client.transport._host, args[1]) - - -def test_get_conversation_rest_flattened_error(transport: str = 'rest'): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.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_conversation( - conversational_search_service.GetConversationRequest(), - name='name_value', - ) - - -def test_get_conversation_rest_error(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - conversational_search_service.ListConversationsRequest, - dict, -]) -def test_list_conversations_rest(request_type): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/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 = conversational_search_service.ListConversationsResponse( - next_page_token='next_page_token_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 = conversational_search_service.ListConversationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_conversations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConversationsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_conversations_rest_required_fields(request_type=conversational_search_service.ListConversationsRequest): - transport_class = transports.ConversationalSearchServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_conversations._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_conversations._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = conversational_search_service.ListConversationsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = conversational_search_service.ListConversationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_conversations(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_conversations_rest_unset_required_fields(): - transport = transports.ConversationalSearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_conversations._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_conversations_rest_interceptors(null_interceptor): - transport = transports.ConversationalSearchServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationalSearchServiceRestInterceptor(), - ) - client = ConversationalSearchServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "post_list_conversations") as post, \ - mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "pre_list_conversations") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversational_search_service.ListConversationsRequest.pb(conversational_search_service.ListConversationsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = conversational_search_service.ListConversationsResponse.to_json(conversational_search_service.ListConversationsResponse()) - - request = conversational_search_service.ListConversationsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = conversational_search_service.ListConversationsResponse() - - client.list_conversations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_conversations_rest_bad_request(transport: str = 'rest', request_type=conversational_search_service.ListConversationsRequest): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_conversations(request) - - -def test_list_conversations_rest_flattened(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversational_search_service.ListConversationsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/dataStores/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 = conversational_search_service.ListConversationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_conversations(**mock_args) - - # Establish that the underlying call 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/*/dataStores/*}/conversations" % client.transport._host, args[1]) - - -def test_list_conversations_rest_flattened_error(transport: str = 'rest'): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.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_conversations( - conversational_search_service.ListConversationsRequest(), - parent='parent_value', - ) - - -def test_list_conversations_rest_pager(transport: str = 'rest'): - client = ConversationalSearchServiceClient( - 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 = ( - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - conversation.Conversation(), - ], - next_page_token='abc', - ), - conversational_search_service.ListConversationsResponse( - conversations=[], - next_page_token='def', - ), - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - ], - next_page_token='ghi', - ), - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(conversational_search_service.ListConversationsResponse.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/dataStores/sample3'} - - pager = client.list_conversations(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, conversation.Conversation) - for i in results) - - pages = list(client.list_conversations(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.ConversationalSearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ConversationalSearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ConversationalSearchServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ConversationalSearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ConversationalSearchServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ConversationalSearchServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ConversationalSearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ConversationalSearchServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ConversationalSearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ConversationalSearchServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ConversationalSearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ConversationalSearchServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ConversationalSearchServiceGrpcTransport, - transports.ConversationalSearchServiceGrpcAsyncIOTransport, - transports.ConversationalSearchServiceRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = ConversationalSearchServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ConversationalSearchServiceGrpcTransport, - ) - -def test_conversational_search_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ConversationalSearchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_conversational_search_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.discoveryengine_v1.services.conversational_search_service.transports.ConversationalSearchServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ConversationalSearchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'converse_conversation', - 'create_conversation', - 'delete_conversation', - 'update_conversation', - 'get_conversation', - 'list_conversations', - 'get_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_conversational_search_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.discoveryengine_v1.services.conversational_search_service.transports.ConversationalSearchServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ConversationalSearchServiceTransport( - 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_conversational_search_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.discoveryengine_v1.services.conversational_search_service.transports.ConversationalSearchServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ConversationalSearchServiceTransport() - adc.assert_called_once() - - -def test_conversational_search_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) - ConversationalSearchServiceClient() - 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.ConversationalSearchServiceGrpcTransport, - transports.ConversationalSearchServiceGrpcAsyncIOTransport, - ], -) -def test_conversational_search_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.ConversationalSearchServiceGrpcTransport, - transports.ConversationalSearchServiceGrpcAsyncIOTransport, - transports.ConversationalSearchServiceRestTransport, - ], -) -def test_conversational_search_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.ConversationalSearchServiceGrpcTransport, grpc_helpers), - (transports.ConversationalSearchServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_conversational_search_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ConversationalSearchServiceGrpcTransport, transports.ConversationalSearchServiceGrpcAsyncIOTransport]) -def test_conversational_search_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_conversational_search_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.ConversationalSearchServiceRestTransport ( - 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_conversational_search_service_host_no_port(transport_name): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_conversational_search_service_host_with_port(transport_name): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_conversational_search_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = ConversationalSearchServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = ConversationalSearchServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.converse_conversation._session - session2 = client2.transport.converse_conversation._session - assert session1 != session2 - session1 = client1.transport.create_conversation._session - session2 = client2.transport.create_conversation._session - assert session1 != session2 - 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 - session1 = client1.transport.list_conversations._session - session2 = client2.transport.list_conversations._session - assert session1 != session2 -def test_conversational_search_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ConversationalSearchServiceGrpcTransport( - 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_conversational_search_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ConversationalSearchServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.ConversationalSearchServiceGrpcTransport, transports.ConversationalSearchServiceGrpcAsyncIOTransport]) -def test_conversational_search_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.ConversationalSearchServiceGrpcTransport, transports.ConversationalSearchServiceGrpcAsyncIOTransport]) -def test_conversational_search_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_conversation_path(): - project = "squid" - location = "clam" - data_store = "whelk" - conversation = "octopus" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}/conversations/{conversation}".format(project=project, location=location, data_store=data_store, conversation=conversation, ) - actual = ConversationalSearchServiceClient.conversation_path(project, location, data_store, conversation) - assert expected == actual - - -def test_parse_conversation_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "data_store": "cuttlefish", - "conversation": "mussel", - } - path = ConversationalSearchServiceClient.conversation_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationalSearchServiceClient.parse_conversation_path(path) - assert expected == actual - -def test_data_store_path(): - project = "winkle" - location = "nautilus" - data_store = "scallop" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) - actual = ConversationalSearchServiceClient.data_store_path(project, location, data_store) - assert expected == actual - - -def test_parse_data_store_path(): - expected = { - "project": "abalone", - "location": "squid", - "data_store": "clam", - } - path = ConversationalSearchServiceClient.data_store_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationalSearchServiceClient.parse_data_store_path(path) - assert expected == actual - -def test_document_path(): - project = "whelk" - location = "octopus" - data_store = "oyster" - branch = "nudibranch" - document = "cuttlefish" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) - actual = ConversationalSearchServiceClient.document_path(project, location, data_store, branch, document) - assert expected == actual - - -def test_parse_document_path(): - expected = { - "project": "mussel", - "location": "winkle", - "data_store": "nautilus", - "branch": "scallop", - "document": "abalone", - } - path = ConversationalSearchServiceClient.document_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationalSearchServiceClient.parse_document_path(path) - assert expected == actual - -def test_serving_config_path(): - project = "squid" - location = "clam" - data_store = "whelk" - serving_config = "octopus" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}/servingConfigs/{serving_config}".format(project=project, location=location, data_store=data_store, serving_config=serving_config, ) - actual = ConversationalSearchServiceClient.serving_config_path(project, location, data_store, serving_config) - assert expected == actual - - -def test_parse_serving_config_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "data_store": "cuttlefish", - "serving_config": "mussel", - } - path = ConversationalSearchServiceClient.serving_config_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationalSearchServiceClient.parse_serving_config_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ConversationalSearchServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nautilus", - } - path = ConversationalSearchServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationalSearchServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "scallop" - expected = "folders/{folder}".format(folder=folder, ) - actual = ConversationalSearchServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "abalone", - } - path = ConversationalSearchServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationalSearchServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "squid" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ConversationalSearchServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "clam", - } - path = ConversationalSearchServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationalSearchServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "whelk" - expected = "projects/{project}".format(project=project, ) - actual = ConversationalSearchServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "octopus", - } - path = ConversationalSearchServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationalSearchServiceClient.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 = ConversationalSearchServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - } - path = ConversationalSearchServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationalSearchServiceClient.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.ConversationalSearchServiceTransport, '_prep_wrapped_messages') as prep: - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ConversationalSearchServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = ConversationalSearchServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = ConversationalSearchServiceClient( - 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(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_get_operation(transport: str = "grpc"): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = ConversationalSearchServiceClient( - 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 = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = ConversationalSearchServiceClient( - 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 = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = ConversationalSearchServiceClient( - 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", [ - (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport), - (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_document_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_document_service.py deleted file mode 100644 index 293af0486221..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_document_service.py +++ /dev/null @@ -1,4999 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.discoveryengine_v1.services.document_service import DocumentServiceAsyncClient -from google.cloud.discoveryengine_v1.services.document_service import DocumentServiceClient -from google.cloud.discoveryengine_v1.services.document_service import pagers -from google.cloud.discoveryengine_v1.services.document_service import transports -from google.cloud.discoveryengine_v1.types import document -from google.cloud.discoveryengine_v1.types import document as gcd_document -from google.cloud.discoveryengine_v1.types import document_service -from google.cloud.discoveryengine_v1.types import import_config -from google.cloud.discoveryengine_v1.types import purge_config -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import struct_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert DocumentServiceClient._get_default_mtls_endpoint(None) is None - assert DocumentServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert DocumentServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert DocumentServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert DocumentServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert DocumentServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (DocumentServiceClient, "grpc"), - (DocumentServiceAsyncClient, "grpc_asyncio"), - (DocumentServiceClient, "rest"), -]) -def test_document_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.DocumentServiceGrpcTransport, "grpc"), - (transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.DocumentServiceRestTransport, "rest"), -]) -def test_document_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", [ - (DocumentServiceClient, "grpc"), - (DocumentServiceAsyncClient, "grpc_asyncio"), - (DocumentServiceClient, "rest"), -]) -def test_document_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -def test_document_service_client_get_transport_class(): - transport = DocumentServiceClient.get_transport_class() - available_transports = [ - transports.DocumentServiceGrpcTransport, - transports.DocumentServiceRestTransport, - ] - assert transport in available_transports - - transport = DocumentServiceClient.get_transport_class("grpc") - assert transport == transports.DocumentServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc"), - (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (DocumentServiceClient, transports.DocumentServiceRestTransport, "rest"), -]) -@mock.patch.object(DocumentServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceClient)) -@mock.patch.object(DocumentServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceAsyncClient)) -def test_document_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(DocumentServiceClient, '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(DocumentServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc", "true"), - (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc", "false"), - (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (DocumentServiceClient, transports.DocumentServiceRestTransport, "rest", "true"), - (DocumentServiceClient, transports.DocumentServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(DocumentServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceClient)) -@mock.patch.object(DocumentServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_document_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 - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - DocumentServiceClient, DocumentServiceAsyncClient -]) -@mock.patch.object(DocumentServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceClient)) -@mock.patch.object(DocumentServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceAsyncClient)) -def test_document_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc"), - (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (DocumentServiceClient, transports.DocumentServiceRestTransport, "rest"), -]) -def test_document_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, - 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", [ - (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc", grpc_helpers), - (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (DocumentServiceClient, transports.DocumentServiceRestTransport, "rest", None), -]) -def test_document_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, - scopes=None, - client_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_document_service_client_client_options_from_dict(): - with mock.patch('google.cloud.discoveryengine_v1.services.document_service.transports.DocumentServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = DocumentServiceClient( - 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", [ - (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc", grpc_helpers), - (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_document_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, - scopes=None, - client_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - document_service.GetDocumentRequest, - dict, -]) -def test_get_document(request_type, transport: str = 'grpc'): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document.Document( - name='name_value', - id='id_value', - schema_id='schema_id_value', - parent_document_id='parent_document_id_value', - json_data='json_data_value', - ) - response = client.get_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.GetDocumentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, document.Document) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.schema_id == 'schema_id_value' - assert response.parent_document_id == 'parent_document_id_value' - - -def test_get_document_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_document), - '__call__') as call: - client.get_document() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.GetDocumentRequest() - -@pytest.mark.asyncio -async def test_get_document_async(transport: str = 'grpc_asyncio', request_type=document_service.GetDocumentRequest): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document.Document( - name='name_value', - id='id_value', - schema_id='schema_id_value', - parent_document_id='parent_document_id_value', - )) - response = await client.get_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.GetDocumentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, document.Document) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.schema_id == 'schema_id_value' - assert response.parent_document_id == 'parent_document_id_value' - - -@pytest.mark.asyncio -async def test_get_document_async_from_dict(): - await test_get_document_async(request_type=dict) - - -def test_get_document_field_headers(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.GetDocumentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_document), - '__call__') as call: - call.return_value = document.Document() - client.get_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_document_field_headers_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.GetDocumentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_document), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.Document()) - await client.get_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_document_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document.Document() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_document( - 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_document_flattened_error(): - client = DocumentServiceClient( - credentials=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_document( - document_service.GetDocumentRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_document_flattened_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document.Document() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.Document()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_document( - 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_document_flattened_error_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_document( - document_service.GetDocumentRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_service.ListDocumentsRequest, - dict, -]) -def test_list_documents(request_type, transport: str = 'grpc'): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_documents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_service.ListDocumentsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_documents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.ListDocumentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDocumentsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_documents_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_documents), - '__call__') as call: - client.list_documents() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.ListDocumentsRequest() - -@pytest.mark.asyncio -async def test_list_documents_async(transport: str = 'grpc_asyncio', request_type=document_service.ListDocumentsRequest): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_documents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document_service.ListDocumentsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_documents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.ListDocumentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDocumentsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_documents_async_from_dict(): - await test_list_documents_async(request_type=dict) - - -def test_list_documents_field_headers(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.ListDocumentsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_documents), - '__call__') as call: - call.return_value = document_service.ListDocumentsResponse() - client.list_documents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_documents_field_headers_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.ListDocumentsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_documents), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_service.ListDocumentsResponse()) - await client.list_documents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_documents_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_documents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_service.ListDocumentsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_documents( - 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_documents_flattened_error(): - client = DocumentServiceClient( - credentials=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_documents( - document_service.ListDocumentsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_documents_flattened_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_documents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_service.ListDocumentsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_service.ListDocumentsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_documents( - 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_documents_flattened_error_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_documents( - document_service.ListDocumentsRequest(), - parent='parent_value', - ) - - -def test_list_documents_pager(transport_name: str = "grpc"): - client = DocumentServiceClient( - 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_documents), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - document.Document(), - ], - next_page_token='abc', - ), - document_service.ListDocumentsResponse( - documents=[], - next_page_token='def', - ), - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - ], - next_page_token='ghi', - ), - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_documents(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, document.Document) - for i in results) -def test_list_documents_pages(transport_name: str = "grpc"): - client = DocumentServiceClient( - 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_documents), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - document.Document(), - ], - next_page_token='abc', - ), - document_service.ListDocumentsResponse( - documents=[], - next_page_token='def', - ), - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - ], - next_page_token='ghi', - ), - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - ], - ), - RuntimeError, - ) - pages = list(client.list_documents(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_documents_async_pager(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_documents), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - document.Document(), - ], - next_page_token='abc', - ), - document_service.ListDocumentsResponse( - documents=[], - next_page_token='def', - ), - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - ], - next_page_token='ghi', - ), - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_documents(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, document.Document) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_documents_async_pages(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_documents), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - document.Document(), - ], - next_page_token='abc', - ), - document_service.ListDocumentsResponse( - documents=[], - next_page_token='def', - ), - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - ], - next_page_token='ghi', - ), - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_documents(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", [ - document_service.CreateDocumentRequest, - dict, -]) -def test_create_document(request_type, transport: str = 'grpc'): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_document.Document( - name='name_value', - id='id_value', - schema_id='schema_id_value', - parent_document_id='parent_document_id_value', - json_data='json_data_value', - ) - response = client.create_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.CreateDocumentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_document.Document) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.schema_id == 'schema_id_value' - assert response.parent_document_id == 'parent_document_id_value' - - -def test_create_document_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_document), - '__call__') as call: - client.create_document() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.CreateDocumentRequest() - -@pytest.mark.asyncio -async def test_create_document_async(transport: str = 'grpc_asyncio', request_type=document_service.CreateDocumentRequest): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_document.Document( - name='name_value', - id='id_value', - schema_id='schema_id_value', - parent_document_id='parent_document_id_value', - )) - response = await client.create_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.CreateDocumentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_document.Document) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.schema_id == 'schema_id_value' - assert response.parent_document_id == 'parent_document_id_value' - - -@pytest.mark.asyncio -async def test_create_document_async_from_dict(): - await test_create_document_async(request_type=dict) - - -def test_create_document_field_headers(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.CreateDocumentRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_document), - '__call__') as call: - call.return_value = gcd_document.Document() - client.create_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_document_field_headers_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.CreateDocumentRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_document), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_document.Document()) - await client.create_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_document_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_document.Document() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_document( - parent='parent_value', - document=gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), - document_id='document_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].document - mock_val = gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})) - assert arg == mock_val - arg = args[0].document_id - mock_val = 'document_id_value' - assert arg == mock_val - - -def test_create_document_flattened_error(): - client = DocumentServiceClient( - credentials=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_document( - document_service.CreateDocumentRequest(), - parent='parent_value', - document=gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), - document_id='document_id_value', - ) - -@pytest.mark.asyncio -async def test_create_document_flattened_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_document.Document() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_document.Document()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_document( - parent='parent_value', - document=gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), - document_id='document_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].document - mock_val = gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})) - assert arg == mock_val - arg = args[0].document_id - mock_val = 'document_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_document_flattened_error_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_document( - document_service.CreateDocumentRequest(), - parent='parent_value', - document=gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), - document_id='document_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_service.UpdateDocumentRequest, - dict, -]) -def test_update_document(request_type, transport: str = 'grpc'): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document.Document( - name='name_value', - id='id_value', - schema_id='schema_id_value', - parent_document_id='parent_document_id_value', - json_data='json_data_value', - ) - response = client.update_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.UpdateDocumentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, document.Document) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.schema_id == 'schema_id_value' - assert response.parent_document_id == 'parent_document_id_value' - - -def test_update_document_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_document), - '__call__') as call: - client.update_document() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.UpdateDocumentRequest() - -@pytest.mark.asyncio -async def test_update_document_async(transport: str = 'grpc_asyncio', request_type=document_service.UpdateDocumentRequest): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document.Document( - name='name_value', - id='id_value', - schema_id='schema_id_value', - parent_document_id='parent_document_id_value', - )) - response = await client.update_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.UpdateDocumentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, document.Document) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.schema_id == 'schema_id_value' - assert response.parent_document_id == 'parent_document_id_value' - - -@pytest.mark.asyncio -async def test_update_document_async_from_dict(): - await test_update_document_async(request_type=dict) - - -def test_update_document_field_headers(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.UpdateDocumentRequest() - - request.document.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_document), - '__call__') as call: - call.return_value = document.Document() - client.update_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'document.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_document_field_headers_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.UpdateDocumentRequest() - - request.document.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_document), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.Document()) - await client.update_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'document.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - document_service.DeleteDocumentRequest, - dict, -]) -def test_delete_document(request_type, transport: str = 'grpc'): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.DeleteDocumentRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_document_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_document), - '__call__') as call: - client.delete_document() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.DeleteDocumentRequest() - -@pytest.mark.asyncio -async def test_delete_document_async(transport: str = 'grpc_asyncio', request_type=document_service.DeleteDocumentRequest): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.DeleteDocumentRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_document_async_from_dict(): - await test_delete_document_async(request_type=dict) - - -def test_delete_document_field_headers(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.DeleteDocumentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_document), - '__call__') as call: - call.return_value = None - client.delete_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_document_field_headers_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.DeleteDocumentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_document), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_document_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_document), - '__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_document( - 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_document_flattened_error(): - client = DocumentServiceClient( - credentials=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_document( - document_service.DeleteDocumentRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_document_flattened_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_document), - '__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_document( - 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_document_flattened_error_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_document( - document_service.DeleteDocumentRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportDocumentsRequest, - dict, -]) -def test_import_documents(request_type, transport: str = 'grpc'): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_documents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_documents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportDocumentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_documents_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_documents), - '__call__') as call: - client.import_documents() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportDocumentsRequest() - -@pytest.mark.asyncio -async def test_import_documents_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportDocumentsRequest): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_documents), - '__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_documents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportDocumentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_documents_async_from_dict(): - await test_import_documents_async(request_type=dict) - - -def test_import_documents_field_headers(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportDocumentsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_documents), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_documents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_import_documents_field_headers_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportDocumentsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_documents), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_documents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - purge_config.PurgeDocumentsRequest, - dict, -]) -def test_purge_documents(request_type, transport: str = 'grpc'): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_documents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.purge_documents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeDocumentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_purge_documents_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_documents), - '__call__') as call: - client.purge_documents() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeDocumentsRequest() - -@pytest.mark.asyncio -async def test_purge_documents_async(transport: str = 'grpc_asyncio', request_type=purge_config.PurgeDocumentsRequest): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_documents), - '__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.purge_documents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeDocumentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_purge_documents_async_from_dict(): - await test_purge_documents_async(request_type=dict) - - -def test_purge_documents_field_headers(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = purge_config.PurgeDocumentsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_documents), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.purge_documents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_purge_documents_field_headers_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = purge_config.PurgeDocumentsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_documents), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.purge_documents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - document_service.GetDocumentRequest, - dict, -]) -def test_get_document_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document.Document( - name='name_value', - id='id_value', - schema_id='schema_id_value', - parent_document_id='parent_document_id_value', - json_data='json_data_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 = document.Document.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_document(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, document.Document) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.schema_id == 'schema_id_value' - assert response.parent_document_id == 'parent_document_id_value' - - -def test_get_document_rest_required_fields(request_type=document_service.GetDocumentRequest): - transport_class = transports.DocumentServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document.Document() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = document.Document.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_document(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_document_rest_unset_required_fields(): - transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_document._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_document_rest_interceptors(null_interceptor): - transport = transports.DocumentServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), - ) - client = DocumentServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "post_get_document") as post, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_get_document") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_service.GetDocumentRequest.pb(document_service.GetDocumentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document.Document.to_json(document.Document()) - - request = document_service.GetDocumentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document.Document() - - client.get_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_document_rest_bad_request(transport: str = 'rest', request_type=document_service.GetDocumentRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_document(request) - - -def test_get_document_rest_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document.Document() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = document.Document.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_document(**mock_args) - - # Establish that the underlying call 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/*/dataStores/*/branches/*/documents/*}" % client.transport._host, args[1]) - - -def test_get_document_rest_flattened_error(transport: str = 'rest'): - client = DocumentServiceClient( - credentials=ga_credentials.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_document( - document_service.GetDocumentRequest(), - name='name_value', - ) - - -def test_get_document_rest_error(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_service.ListDocumentsRequest, - dict, -]) -def test_list_documents_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/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 = document_service.ListDocumentsResponse( - next_page_token='next_page_token_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 = document_service.ListDocumentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_documents(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDocumentsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_documents_rest_required_fields(request_type=document_service.ListDocumentsRequest): - transport_class = transports.DocumentServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_documents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_documents._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document_service.ListDocumentsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = document_service.ListDocumentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_documents(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_documents_rest_unset_required_fields(): - transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_documents._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_documents_rest_interceptors(null_interceptor): - transport = transports.DocumentServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), - ) - client = DocumentServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "post_list_documents") as post, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_list_documents") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_service.ListDocumentsRequest.pb(document_service.ListDocumentsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document_service.ListDocumentsResponse.to_json(document_service.ListDocumentsResponse()) - - request = document_service.ListDocumentsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document_service.ListDocumentsResponse() - - client.list_documents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_documents_rest_bad_request(transport: str = 'rest', request_type=document_service.ListDocumentsRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_documents(request) - - -def test_list_documents_rest_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_service.ListDocumentsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = document_service.ListDocumentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_documents(**mock_args) - - # Establish that the underlying call 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/*/dataStores/*/branches/*}/documents" % client.transport._host, args[1]) - - -def test_list_documents_rest_flattened_error(transport: str = 'rest'): - client = DocumentServiceClient( - credentials=ga_credentials.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_documents( - document_service.ListDocumentsRequest(), - parent='parent_value', - ) - - -def test_list_documents_rest_pager(transport: str = 'rest'): - client = DocumentServiceClient( - 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 = ( - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - document.Document(), - ], - next_page_token='abc', - ), - document_service.ListDocumentsResponse( - documents=[], - next_page_token='def', - ), - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - ], - next_page_token='ghi', - ), - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(document_service.ListDocumentsResponse.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/dataStores/sample3/branches/sample4'} - - pager = client.list_documents(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, document.Document) - for i in results) - - pages = list(client.list_documents(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - document_service.CreateDocumentRequest, - dict, -]) -def test_create_document_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} - request_init["document"] = {'struct_data': {'fields': {}}, 'json_data': 'json_data_value', 'name': 'name_value', 'id': 'id_value', 'schema_id': 'schema_id_value', 'content': {'raw_bytes': b'raw_bytes_blob', 'uri': 'uri_value', 'mime_type': 'mime_type_value'}, 'parent_document_id': 'parent_document_id_value', 'derived_struct_data': {}} - # 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 = document_service.CreateDocumentRequest.meta.fields["document"] - - 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["document"].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["document"][field])): - del request_init["document"][field][i][subfield] - else: - del request_init["document"][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 = gcd_document.Document( - name='name_value', - id='id_value', - schema_id='schema_id_value', - parent_document_id='parent_document_id_value', - json_data='json_data_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 = gcd_document.Document.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_document(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_document.Document) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.schema_id == 'schema_id_value' - assert response.parent_document_id == 'parent_document_id_value' - - -def test_create_document_rest_required_fields(request_type=document_service.CreateDocumentRequest): - transport_class = transports.DocumentServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["document_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "documentId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "documentId" in jsonified_request - assert jsonified_request["documentId"] == request_init["document_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["documentId"] = 'document_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_document._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("document_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "documentId" in jsonified_request - assert jsonified_request["documentId"] == 'document_id_value' - - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_document.Document() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcd_document.Document.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_document(request) - - expected_params = [ - ( - "documentId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_document_rest_unset_required_fields(): - transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_document._get_unset_required_fields({}) - assert set(unset_fields) == (set(("documentId", )) & set(("parent", "document", "documentId", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_document_rest_interceptors(null_interceptor): - transport = transports.DocumentServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), - ) - client = DocumentServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "post_create_document") as post, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_create_document") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_service.CreateDocumentRequest.pb(document_service.CreateDocumentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_document.Document.to_json(gcd_document.Document()) - - request = document_service.CreateDocumentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_document.Document() - - client.create_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_document_rest_bad_request(transport: str = 'rest', request_type=document_service.CreateDocumentRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_document(request) - - -def test_create_document_rest_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_document.Document() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - document=gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), - document_id='document_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 = gcd_document.Document.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_document(**mock_args) - - # Establish that the underlying call 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/*/dataStores/*/branches/*}/documents" % client.transport._host, args[1]) - - -def test_create_document_rest_flattened_error(transport: str = 'rest'): - client = DocumentServiceClient( - credentials=ga_credentials.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_document( - document_service.CreateDocumentRequest(), - parent='parent_value', - document=gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), - document_id='document_id_value', - ) - - -def test_create_document_rest_error(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_service.UpdateDocumentRequest, - dict, -]) -def test_update_document_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'document': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'}} - request_init["document"] = {'struct_data': {'fields': {}}, 'json_data': 'json_data_value', 'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5', 'id': 'id_value', 'schema_id': 'schema_id_value', 'content': {'raw_bytes': b'raw_bytes_blob', 'uri': 'uri_value', 'mime_type': 'mime_type_value'}, 'parent_document_id': 'parent_document_id_value', 'derived_struct_data': {}} - # 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 = document_service.UpdateDocumentRequest.meta.fields["document"] - - 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["document"].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["document"][field])): - del request_init["document"][field][i][subfield] - else: - del request_init["document"][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 = document.Document( - name='name_value', - id='id_value', - schema_id='schema_id_value', - parent_document_id='parent_document_id_value', - json_data='json_data_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 = document.Document.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_document(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, document.Document) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.schema_id == 'schema_id_value' - assert response.parent_document_id == 'parent_document_id_value' - - -def test_update_document_rest_required_fields(request_type=document_service.UpdateDocumentRequest): - transport_class = transports.DocumentServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_document._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_missing", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document.Document() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = document.Document.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_document(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_document_rest_unset_required_fields(): - transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_document._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowMissing", )) & set(("document", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_document_rest_interceptors(null_interceptor): - transport = transports.DocumentServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), - ) - client = DocumentServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "post_update_document") as post, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_update_document") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_service.UpdateDocumentRequest.pb(document_service.UpdateDocumentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document.Document.to_json(document.Document()) - - request = document_service.UpdateDocumentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document.Document() - - client.update_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_document_rest_bad_request(transport: str = 'rest', request_type=document_service.UpdateDocumentRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'document': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_document(request) - - -def test_update_document_rest_error(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_service.DeleteDocumentRequest, - dict, -]) -def test_delete_document_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_document(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_document_rest_required_fields(request_type=document_service.DeleteDocumentRequest): - transport_class = transports.DocumentServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentServiceClient( - 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 - - response = client.delete_document(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_document_rest_unset_required_fields(): - transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_document._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_document_rest_interceptors(null_interceptor): - transport = transports.DocumentServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), - ) - client = DocumentServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_delete_document") as pre: - pre.assert_not_called() - pb_message = document_service.DeleteDocumentRequest.pb(document_service.DeleteDocumentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = document_service.DeleteDocumentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_document_rest_bad_request(transport: str = 'rest', request_type=document_service.DeleteDocumentRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_document(request) - - -def test_delete_document_rest_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_document(**mock_args) - - # Establish that the underlying call 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/*/dataStores/*/branches/*/documents/*}" % client.transport._host, args[1]) - - -def test_delete_document_rest_flattened_error(transport: str = 'rest'): - client = DocumentServiceClient( - credentials=ga_credentials.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_document( - document_service.DeleteDocumentRequest(), - name='name_value', - ) - - -def test_delete_document_rest_error(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportDocumentsRequest, - dict, -]) -def test_import_documents_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.import_documents(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_import_documents_rest_required_fields(request_type=import_config.ImportDocumentsRequest): - transport_class = transports.DocumentServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_documents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_documents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.import_documents(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_import_documents_rest_unset_required_fields(): - transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.import_documents._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_import_documents_rest_interceptors(null_interceptor): - transport = transports.DocumentServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), - ) - client = DocumentServiceClient(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.DocumentServiceRestInterceptor, "post_import_documents") as post, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_import_documents") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = import_config.ImportDocumentsRequest.pb(import_config.ImportDocumentsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = import_config.ImportDocumentsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.import_documents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_import_documents_rest_bad_request(transport: str = 'rest', request_type=import_config.ImportDocumentsRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.import_documents(request) - - -def test_import_documents_rest_error(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - purge_config.PurgeDocumentsRequest, - dict, -]) -def test_purge_documents_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.purge_documents(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_purge_documents_rest_required_fields(request_type=purge_config.PurgeDocumentsRequest): - transport_class = transports.DocumentServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["filter"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).purge_documents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - jsonified_request["filter"] = 'filter_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).purge_documents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "filter" in jsonified_request - assert jsonified_request["filter"] == 'filter_value' - - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.purge_documents(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_purge_documents_rest_unset_required_fields(): - transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.purge_documents._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "filter", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_purge_documents_rest_interceptors(null_interceptor): - transport = transports.DocumentServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), - ) - client = DocumentServiceClient(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.DocumentServiceRestInterceptor, "post_purge_documents") as post, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_purge_documents") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = purge_config.PurgeDocumentsRequest.pb(purge_config.PurgeDocumentsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = purge_config.PurgeDocumentsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.purge_documents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_purge_documents_rest_bad_request(transport: str = 'rest', request_type=purge_config.PurgeDocumentsRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.purge_documents(request) - - -def test_purge_documents_rest_error(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.DocumentServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.DocumentServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DocumentServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.DocumentServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = DocumentServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = DocumentServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.DocumentServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DocumentServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.DocumentServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = DocumentServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.DocumentServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.DocumentServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.DocumentServiceGrpcTransport, - transports.DocumentServiceGrpcAsyncIOTransport, - transports.DocumentServiceRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = DocumentServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.DocumentServiceGrpcTransport, - ) - -def test_document_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.DocumentServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_document_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.discoveryengine_v1.services.document_service.transports.DocumentServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.DocumentServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_document', - 'list_documents', - 'create_document', - 'update_document', - 'delete_document', - 'import_documents', - 'purge_documents', - 'get_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_document_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.discoveryengine_v1.services.document_service.transports.DocumentServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DocumentServiceTransport( - 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_document_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.discoveryengine_v1.services.document_service.transports.DocumentServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DocumentServiceTransport() - adc.assert_called_once() - - -def test_document_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) - DocumentServiceClient() - 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.DocumentServiceGrpcTransport, - transports.DocumentServiceGrpcAsyncIOTransport, - ], -) -def test_document_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.DocumentServiceGrpcTransport, - transports.DocumentServiceGrpcAsyncIOTransport, - transports.DocumentServiceRestTransport, - ], -) -def test_document_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.DocumentServiceGrpcTransport, grpc_helpers), - (transports.DocumentServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_document_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.DocumentServiceGrpcTransport, transports.DocumentServiceGrpcAsyncIOTransport]) -def test_document_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_document_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.DocumentServiceRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_document_service_rest_lro_client(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_document_service_host_no_port(transport_name): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_document_service_host_with_port(transport_name): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_document_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = DocumentServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = DocumentServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_document._session - session2 = client2.transport.get_document._session - assert session1 != session2 - session1 = client1.transport.list_documents._session - session2 = client2.transport.list_documents._session - assert session1 != session2 - session1 = client1.transport.create_document._session - session2 = client2.transport.create_document._session - assert session1 != session2 - session1 = client1.transport.update_document._session - session2 = client2.transport.update_document._session - assert session1 != session2 - session1 = client1.transport.delete_document._session - session2 = client2.transport.delete_document._session - assert session1 != session2 - session1 = client1.transport.import_documents._session - session2 = client2.transport.import_documents._session - assert session1 != session2 - session1 = client1.transport.purge_documents._session - session2 = client2.transport.purge_documents._session - assert session1 != session2 -def test_document_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DocumentServiceGrpcTransport( - 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_document_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DocumentServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.DocumentServiceGrpcTransport, transports.DocumentServiceGrpcAsyncIOTransport]) -def test_document_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.DocumentServiceGrpcTransport, transports.DocumentServiceGrpcAsyncIOTransport]) -def test_document_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_document_service_grpc_lro_client(): - client = DocumentServiceClient( - 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_document_service_grpc_lro_async_client(): - client = DocumentServiceAsyncClient( - 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_branch_path(): - project = "squid" - location = "clam" - data_store = "whelk" - branch = "octopus" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}".format(project=project, location=location, data_store=data_store, branch=branch, ) - actual = DocumentServiceClient.branch_path(project, location, data_store, branch) - assert expected == actual - - -def test_parse_branch_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "data_store": "cuttlefish", - "branch": "mussel", - } - path = DocumentServiceClient.branch_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentServiceClient.parse_branch_path(path) - assert expected == actual - -def test_document_path(): - project = "winkle" - location = "nautilus" - data_store = "scallop" - branch = "abalone" - document = "squid" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) - actual = DocumentServiceClient.document_path(project, location, data_store, branch, document) - assert expected == actual - - -def test_parse_document_path(): - expected = { - "project": "clam", - "location": "whelk", - "data_store": "octopus", - "branch": "oyster", - "document": "nudibranch", - } - path = DocumentServiceClient.document_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentServiceClient.parse_document_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = DocumentServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = DocumentServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = DocumentServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = DocumentServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = DocumentServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = DocumentServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = DocumentServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = DocumentServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = DocumentServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = DocumentServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentServiceClient.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.DocumentServiceTransport, '_prep_wrapped_messages') as prep: - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.DocumentServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = DocumentServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = DocumentServiceClient( - 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(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_get_operation(transport: str = "grpc"): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = DocumentServiceClient( - 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 = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = DocumentServiceClient( - 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 = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = DocumentServiceClient( - 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", [ - (DocumentServiceClient, transports.DocumentServiceGrpcTransport), - (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_schema_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_schema_service.py deleted file mode 100644 index a0335d58b8cd..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_schema_service.py +++ /dev/null @@ -1,4265 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.discoveryengine_v1.services.schema_service import SchemaServiceAsyncClient -from google.cloud.discoveryengine_v1.services.schema_service import SchemaServiceClient -from google.cloud.discoveryengine_v1.services.schema_service import pagers -from google.cloud.discoveryengine_v1.services.schema_service import transports -from google.cloud.discoveryengine_v1.types import schema -from google.cloud.discoveryengine_v1.types import schema as gcd_schema -from google.cloud.discoveryengine_v1.types import schema_service -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert SchemaServiceClient._get_default_mtls_endpoint(None) is None - assert SchemaServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SchemaServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SchemaServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SchemaServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SchemaServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (SchemaServiceClient, "grpc"), - (SchemaServiceAsyncClient, "grpc_asyncio"), - (SchemaServiceClient, "rest"), -]) -def test_schema_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.SchemaServiceGrpcTransport, "grpc"), - (transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.SchemaServiceRestTransport, "rest"), -]) -def test_schema_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", [ - (SchemaServiceClient, "grpc"), - (SchemaServiceAsyncClient, "grpc_asyncio"), - (SchemaServiceClient, "rest"), -]) -def test_schema_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -def test_schema_service_client_get_transport_class(): - transport = SchemaServiceClient.get_transport_class() - available_transports = [ - transports.SchemaServiceGrpcTransport, - transports.SchemaServiceRestTransport, - ] - assert transport in available_transports - - transport = SchemaServiceClient.get_transport_class("grpc") - assert transport == transports.SchemaServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc"), - (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (SchemaServiceClient, transports.SchemaServiceRestTransport, "rest"), -]) -@mock.patch.object(SchemaServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceClient)) -@mock.patch.object(SchemaServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceAsyncClient)) -def test_schema_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(SchemaServiceClient, '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(SchemaServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc", "true"), - (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc", "false"), - (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (SchemaServiceClient, transports.SchemaServiceRestTransport, "rest", "true"), - (SchemaServiceClient, transports.SchemaServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(SchemaServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceClient)) -@mock.patch.object(SchemaServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_schema_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 - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - SchemaServiceClient, SchemaServiceAsyncClient -]) -@mock.patch.object(SchemaServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceClient)) -@mock.patch.object(SchemaServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceAsyncClient)) -def test_schema_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc"), - (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (SchemaServiceClient, transports.SchemaServiceRestTransport, "rest"), -]) -def test_schema_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, - 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", [ - (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc", grpc_helpers), - (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (SchemaServiceClient, transports.SchemaServiceRestTransport, "rest", None), -]) -def test_schema_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, - scopes=None, - client_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_schema_service_client_client_options_from_dict(): - with mock.patch('google.cloud.discoveryengine_v1.services.schema_service.transports.SchemaServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SchemaServiceClient( - 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", [ - (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc", grpc_helpers), - (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_schema_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, - scopes=None, - client_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - schema_service.GetSchemaRequest, - dict, -]) -def test_get_schema(request_type, transport: str = 'grpc'): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema.Schema( - name='name_value', - json_schema='json_schema_value', - ) - response = client.get_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.GetSchemaRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, schema.Schema) - assert response.name == 'name_value' - - -def test_get_schema_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_schema), - '__call__') as call: - client.get_schema() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.GetSchemaRequest() - -@pytest.mark.asyncio -async def test_get_schema_async(transport: str = 'grpc_asyncio', request_type=schema_service.GetSchemaRequest): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(schema.Schema( - name='name_value', - )) - response = await client.get_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.GetSchemaRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, schema.Schema) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_schema_async_from_dict(): - await test_get_schema_async(request_type=dict) - - -def test_get_schema_field_headers(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema_service.GetSchemaRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_schema), - '__call__') as call: - call.return_value = schema.Schema() - client.get_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_schema_field_headers_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema_service.GetSchemaRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_schema), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.Schema()) - await client.get_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_schema_flattened(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema.Schema() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_schema( - 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_schema_flattened_error(): - client = SchemaServiceClient( - credentials=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_schema( - schema_service.GetSchemaRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_schema_flattened_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema.Schema() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.Schema()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_schema( - 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_schema_flattened_error_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_schema( - schema_service.GetSchemaRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - schema_service.ListSchemasRequest, - dict, -]) -def test_list_schemas(request_type, transport: str = 'grpc'): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_schemas), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema_service.ListSchemasResponse( - next_page_token='next_page_token_value', - ) - response = client.list_schemas(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.ListSchemasRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSchemasPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_schemas_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__') as call: - client.list_schemas() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.ListSchemasRequest() - -@pytest.mark.asyncio -async def test_list_schemas_async(transport: str = 'grpc_asyncio', request_type=schema_service.ListSchemasRequest): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_schemas), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(schema_service.ListSchemasResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_schemas(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.ListSchemasRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSchemasAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_schemas_async_from_dict(): - await test_list_schemas_async(request_type=dict) - - -def test_list_schemas_field_headers(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema_service.ListSchemasRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__') as call: - call.return_value = schema_service.ListSchemasResponse() - client.list_schemas(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_schemas_field_headers_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema_service.ListSchemasRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema_service.ListSchemasResponse()) - await client.list_schemas(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_schemas_flattened(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema_service.ListSchemasResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_schemas( - 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_schemas_flattened_error(): - client = SchemaServiceClient( - credentials=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_schemas( - schema_service.ListSchemasRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_schemas_flattened_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema_service.ListSchemasResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema_service.ListSchemasResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_schemas( - 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_schemas_flattened_error_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_schemas( - schema_service.ListSchemasRequest(), - parent='parent_value', - ) - - -def test_list_schemas_pager(transport_name: str = "grpc"): - client = SchemaServiceClient( - 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_schemas), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - schema.Schema(), - ], - next_page_token='abc', - ), - schema_service.ListSchemasResponse( - schemas=[], - next_page_token='def', - ), - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - ], - next_page_token='ghi', - ), - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_schemas(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, schema.Schema) - for i in results) -def test_list_schemas_pages(transport_name: str = "grpc"): - client = SchemaServiceClient( - 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_schemas), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - schema.Schema(), - ], - next_page_token='abc', - ), - schema_service.ListSchemasResponse( - schemas=[], - next_page_token='def', - ), - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - ], - next_page_token='ghi', - ), - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - ], - ), - RuntimeError, - ) - pages = list(client.list_schemas(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_schemas_async_pager(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - schema.Schema(), - ], - next_page_token='abc', - ), - schema_service.ListSchemasResponse( - schemas=[], - next_page_token='def', - ), - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - ], - next_page_token='ghi', - ), - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_schemas(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, schema.Schema) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_schemas_async_pages(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - schema.Schema(), - ], - next_page_token='abc', - ), - schema_service.ListSchemasResponse( - schemas=[], - next_page_token='def', - ), - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - ], - next_page_token='ghi', - ), - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_schemas(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", [ - schema_service.CreateSchemaRequest, - dict, -]) -def test_create_schema(request_type, transport: str = 'grpc'): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.CreateSchemaRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_schema_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_schema), - '__call__') as call: - client.create_schema() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.CreateSchemaRequest() - -@pytest.mark.asyncio -async def test_create_schema_async(transport: str = 'grpc_asyncio', request_type=schema_service.CreateSchemaRequest): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_schema), - '__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_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.CreateSchemaRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_schema_async_from_dict(): - await test_create_schema_async(request_type=dict) - - -def test_create_schema_field_headers(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema_service.CreateSchemaRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_schema), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_schema_field_headers_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema_service.CreateSchemaRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_schema), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_schema_flattened(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_schema), - '__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_schema( - parent='parent_value', - schema=gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), - schema_id='schema_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].schema - mock_val = gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})) - assert arg == mock_val - arg = args[0].schema_id - mock_val = 'schema_id_value' - assert arg == mock_val - - -def test_create_schema_flattened_error(): - client = SchemaServiceClient( - credentials=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_schema( - schema_service.CreateSchemaRequest(), - parent='parent_value', - schema=gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), - schema_id='schema_id_value', - ) - -@pytest.mark.asyncio -async def test_create_schema_flattened_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_schema), - '__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_schema( - parent='parent_value', - schema=gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), - schema_id='schema_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].schema - mock_val = gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})) - assert arg == mock_val - arg = args[0].schema_id - mock_val = 'schema_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_schema_flattened_error_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_schema( - schema_service.CreateSchemaRequest(), - parent='parent_value', - schema=gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), - schema_id='schema_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - schema_service.UpdateSchemaRequest, - dict, -]) -def test_update_schema(request_type, transport: str = 'grpc'): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.UpdateSchemaRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_schema_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_schema), - '__call__') as call: - client.update_schema() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.UpdateSchemaRequest() - -@pytest.mark.asyncio -async def test_update_schema_async(transport: str = 'grpc_asyncio', request_type=schema_service.UpdateSchemaRequest): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_schema), - '__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_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.UpdateSchemaRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_schema_async_from_dict(): - await test_update_schema_async(request_type=dict) - - -def test_update_schema_field_headers(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema_service.UpdateSchemaRequest() - - request.schema.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_schema), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'schema.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_schema_field_headers_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema_service.UpdateSchemaRequest() - - request.schema.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_schema), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'schema.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - schema_service.DeleteSchemaRequest, - dict, -]) -def test_delete_schema(request_type, transport: str = 'grpc'): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.DeleteSchemaRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_schema_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_schema), - '__call__') as call: - client.delete_schema() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.DeleteSchemaRequest() - -@pytest.mark.asyncio -async def test_delete_schema_async(transport: str = 'grpc_asyncio', request_type=schema_service.DeleteSchemaRequest): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_schema), - '__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_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.DeleteSchemaRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_schema_async_from_dict(): - await test_delete_schema_async(request_type=dict) - - -def test_delete_schema_field_headers(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema_service.DeleteSchemaRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_schema), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_schema_field_headers_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema_service.DeleteSchemaRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_schema), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_schema_flattened(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_schema), - '__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_schema( - 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_schema_flattened_error(): - client = SchemaServiceClient( - credentials=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_schema( - schema_service.DeleteSchemaRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_schema_flattened_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_schema), - '__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_schema( - 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_schema_flattened_error_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_schema( - schema_service.DeleteSchemaRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - schema_service.GetSchemaRequest, - dict, -]) -def test_get_schema_rest(request_type): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/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 = schema.Schema( - name='name_value', - json_schema='json_schema_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 = schema.Schema.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_schema(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, schema.Schema) - assert response.name == 'name_value' - - -def test_get_schema_rest_required_fields(request_type=schema_service.GetSchemaRequest): - transport_class = transports.SchemaServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_schema._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_schema._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = schema.Schema() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = schema.Schema.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_schema(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_schema_rest_unset_required_fields(): - transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_schema._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_schema_rest_interceptors(null_interceptor): - transport = transports.SchemaServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), - ) - client = SchemaServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SchemaServiceRestInterceptor, "post_get_schema") as post, \ - mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_get_schema") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = schema_service.GetSchemaRequest.pb(schema_service.GetSchemaRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = schema.Schema.to_json(schema.Schema()) - - request = schema_service.GetSchemaRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = schema.Schema() - - client.get_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_schema_rest_bad_request(transport: str = 'rest', request_type=schema_service.GetSchemaRequest): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_schema(request) - - -def test_get_schema_rest_flattened(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = schema.Schema() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/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 = schema.Schema.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_schema(**mock_args) - - # Establish that the underlying call 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/*/dataStores/*/schemas/*}" % client.transport._host, args[1]) - - -def test_get_schema_rest_flattened_error(transport: str = 'rest'): - client = SchemaServiceClient( - credentials=ga_credentials.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_schema( - schema_service.GetSchemaRequest(), - name='name_value', - ) - - -def test_get_schema_rest_error(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - schema_service.ListSchemasRequest, - dict, -]) -def test_list_schemas_rest(request_type): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/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 = schema_service.ListSchemasResponse( - next_page_token='next_page_token_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 = schema_service.ListSchemasResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_schemas(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSchemasPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_schemas_rest_required_fields(request_type=schema_service.ListSchemasRequest): - transport_class = transports.SchemaServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_schemas._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_schemas._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = schema_service.ListSchemasResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = schema_service.ListSchemasResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_schemas(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_schemas_rest_unset_required_fields(): - transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_schemas._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_schemas_rest_interceptors(null_interceptor): - transport = transports.SchemaServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), - ) - client = SchemaServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SchemaServiceRestInterceptor, "post_list_schemas") as post, \ - mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_list_schemas") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = schema_service.ListSchemasRequest.pb(schema_service.ListSchemasRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = schema_service.ListSchemasResponse.to_json(schema_service.ListSchemasResponse()) - - request = schema_service.ListSchemasRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = schema_service.ListSchemasResponse() - - client.list_schemas(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_schemas_rest_bad_request(transport: str = 'rest', request_type=schema_service.ListSchemasRequest): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_schemas(request) - - -def test_list_schemas_rest_flattened(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = schema_service.ListSchemasResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/dataStores/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 = schema_service.ListSchemasResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_schemas(**mock_args) - - # Establish that the underlying call 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/*/dataStores/*}/schemas" % client.transport._host, args[1]) - - -def test_list_schemas_rest_flattened_error(transport: str = 'rest'): - client = SchemaServiceClient( - credentials=ga_credentials.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_schemas( - schema_service.ListSchemasRequest(), - parent='parent_value', - ) - - -def test_list_schemas_rest_pager(transport: str = 'rest'): - client = SchemaServiceClient( - 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 = ( - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - schema.Schema(), - ], - next_page_token='abc', - ), - schema_service.ListSchemasResponse( - schemas=[], - next_page_token='def', - ), - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - ], - next_page_token='ghi', - ), - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(schema_service.ListSchemasResponse.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/dataStores/sample3'} - - pager = client.list_schemas(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, schema.Schema) - for i in results) - - pages = list(client.list_schemas(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - schema_service.CreateSchemaRequest, - dict, -]) -def test_create_schema_rest(request_type): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - request_init["schema"] = {'struct_schema': {'fields': {}}, 'json_schema': 'json_schema_value', 'name': 'name_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 = schema_service.CreateSchemaRequest.meta.fields["schema"] - - 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["schema"].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["schema"][field])): - del request_init["schema"][field][i][subfield] - else: - del request_init["schema"][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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_schema(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_create_schema_rest_required_fields(request_type=schema_service.CreateSchemaRequest): - transport_class = transports.SchemaServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["schema_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "schemaId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_schema._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "schemaId" in jsonified_request - assert jsonified_request["schemaId"] == request_init["schema_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["schemaId"] = 'schema_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_schema._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("schema_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "schemaId" in jsonified_request - assert jsonified_request["schemaId"] == 'schema_id_value' - - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_schema(request) - - expected_params = [ - ( - "schemaId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_schema_rest_unset_required_fields(): - transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_schema._get_unset_required_fields({}) - assert set(unset_fields) == (set(("schemaId", )) & set(("parent", "schema", "schemaId", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_schema_rest_interceptors(null_interceptor): - transport = transports.SchemaServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), - ) - client = SchemaServiceClient(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.SchemaServiceRestInterceptor, "post_create_schema") as post, \ - mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_create_schema") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = schema_service.CreateSchemaRequest.pb(schema_service.CreateSchemaRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = schema_service.CreateSchemaRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_schema_rest_bad_request(transport: str = 'rest', request_type=schema_service.CreateSchemaRequest): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_schema(request) - - -def test_create_schema_rest_flattened(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.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/dataStores/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - schema=gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), - schema_id='schema_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_schema(**mock_args) - - # Establish that the underlying call 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/*/dataStores/*}/schemas" % client.transport._host, args[1]) - - -def test_create_schema_rest_flattened_error(transport: str = 'rest'): - client = SchemaServiceClient( - credentials=ga_credentials.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_schema( - schema_service.CreateSchemaRequest(), - parent='parent_value', - schema=gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), - schema_id='schema_id_value', - ) - - -def test_create_schema_rest_error(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - schema_service.UpdateSchemaRequest, - dict, -]) -def test_update_schema_rest(request_type): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'schema': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/sample4'}} - request_init["schema"] = {'struct_schema': {'fields': {}}, 'json_schema': 'json_schema_value', 'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/sample4'} - # 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 = schema_service.UpdateSchemaRequest.meta.fields["schema"] - - 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["schema"].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["schema"][field])): - del request_init["schema"][field][i][subfield] - else: - del request_init["schema"][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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_schema(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_update_schema_rest_required_fields(request_type=schema_service.UpdateSchemaRequest): - transport_class = transports.SchemaServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_schema._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_schema._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_missing", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_schema(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_schema_rest_unset_required_fields(): - transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_schema._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowMissing", )) & set(("schema", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_schema_rest_interceptors(null_interceptor): - transport = transports.SchemaServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), - ) - client = SchemaServiceClient(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.SchemaServiceRestInterceptor, "post_update_schema") as post, \ - mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_update_schema") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = schema_service.UpdateSchemaRequest.pb(schema_service.UpdateSchemaRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = schema_service.UpdateSchemaRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_schema_rest_bad_request(transport: str = 'rest', request_type=schema_service.UpdateSchemaRequest): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'schema': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/sample4'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_schema(request) - - -def test_update_schema_rest_error(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - schema_service.DeleteSchemaRequest, - dict, -]) -def test_delete_schema_rest(request_type): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_schema(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_delete_schema_rest_required_fields(request_type=schema_service.DeleteSchemaRequest): - transport_class = transports.SchemaServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_schema._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_schema._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_schema(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_schema_rest_unset_required_fields(): - transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_schema._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_schema_rest_interceptors(null_interceptor): - transport = transports.SchemaServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), - ) - client = SchemaServiceClient(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.SchemaServiceRestInterceptor, "post_delete_schema") as post, \ - mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_delete_schema") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = schema_service.DeleteSchemaRequest.pb(schema_service.DeleteSchemaRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = schema_service.DeleteSchemaRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_schema_rest_bad_request(transport: str = 'rest', request_type=schema_service.DeleteSchemaRequest): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_schema(request) - - -def test_delete_schema_rest_flattened(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.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/dataStores/sample3/schemas/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_schema(**mock_args) - - # Establish that the underlying call 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/*/dataStores/*/schemas/*}" % client.transport._host, args[1]) - - -def test_delete_schema_rest_flattened_error(transport: str = 'rest'): - client = SchemaServiceClient( - credentials=ga_credentials.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_schema( - schema_service.DeleteSchemaRequest(), - name='name_value', - ) - - -def test_delete_schema_rest_error(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.SchemaServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SchemaServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SchemaServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.SchemaServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SchemaServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SchemaServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SchemaServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SchemaServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SchemaServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SchemaServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SchemaServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SchemaServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.SchemaServiceGrpcTransport, - transports.SchemaServiceGrpcAsyncIOTransport, - transports.SchemaServiceRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = SchemaServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.SchemaServiceGrpcTransport, - ) - -def test_schema_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.SchemaServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_schema_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.discoveryengine_v1.services.schema_service.transports.SchemaServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SchemaServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_schema', - 'list_schemas', - 'create_schema', - 'update_schema', - 'delete_schema', - 'get_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_schema_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.discoveryengine_v1.services.schema_service.transports.SchemaServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SchemaServiceTransport( - 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_schema_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.discoveryengine_v1.services.schema_service.transports.SchemaServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SchemaServiceTransport() - adc.assert_called_once() - - -def test_schema_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) - SchemaServiceClient() - 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.SchemaServiceGrpcTransport, - transports.SchemaServiceGrpcAsyncIOTransport, - ], -) -def test_schema_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.SchemaServiceGrpcTransport, - transports.SchemaServiceGrpcAsyncIOTransport, - transports.SchemaServiceRestTransport, - ], -) -def test_schema_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.SchemaServiceGrpcTransport, grpc_helpers), - (transports.SchemaServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_schema_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.SchemaServiceGrpcTransport, transports.SchemaServiceGrpcAsyncIOTransport]) -def test_schema_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_schema_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.SchemaServiceRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_schema_service_rest_lro_client(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_schema_service_host_no_port(transport_name): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_schema_service_host_with_port(transport_name): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_schema_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = SchemaServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = SchemaServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_schema._session - session2 = client2.transport.get_schema._session - assert session1 != session2 - session1 = client1.transport.list_schemas._session - session2 = client2.transport.list_schemas._session - assert session1 != session2 - session1 = client1.transport.create_schema._session - session2 = client2.transport.create_schema._session - assert session1 != session2 - session1 = client1.transport.update_schema._session - session2 = client2.transport.update_schema._session - assert session1 != session2 - session1 = client1.transport.delete_schema._session - session2 = client2.transport.delete_schema._session - assert session1 != session2 -def test_schema_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SchemaServiceGrpcTransport( - 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_schema_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SchemaServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.SchemaServiceGrpcTransport, transports.SchemaServiceGrpcAsyncIOTransport]) -def test_schema_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.SchemaServiceGrpcTransport, transports.SchemaServiceGrpcAsyncIOTransport]) -def test_schema_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_schema_service_grpc_lro_client(): - client = SchemaServiceClient( - 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_schema_service_grpc_lro_async_client(): - client = SchemaServiceAsyncClient( - 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_data_store_path(): - project = "squid" - location = "clam" - data_store = "whelk" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) - actual = SchemaServiceClient.data_store_path(project, location, data_store) - assert expected == actual - - -def test_parse_data_store_path(): - expected = { - "project": "octopus", - "location": "oyster", - "data_store": "nudibranch", - } - path = SchemaServiceClient.data_store_path(**expected) - - # Check that the path construction is reversible. - actual = SchemaServiceClient.parse_data_store_path(path) - assert expected == actual - -def test_schema_path(): - project = "cuttlefish" - location = "mussel" - data_store = "winkle" - schema = "nautilus" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}/schemas/{schema}".format(project=project, location=location, data_store=data_store, schema=schema, ) - actual = SchemaServiceClient.schema_path(project, location, data_store, schema) - assert expected == actual - - -def test_parse_schema_path(): - expected = { - "project": "scallop", - "location": "abalone", - "data_store": "squid", - "schema": "clam", - } - path = SchemaServiceClient.schema_path(**expected) - - # Check that the path construction is reversible. - actual = SchemaServiceClient.parse_schema_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SchemaServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = SchemaServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SchemaServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = SchemaServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = SchemaServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SchemaServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SchemaServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = SchemaServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SchemaServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = SchemaServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = SchemaServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SchemaServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "scallop" - location = "abalone" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = SchemaServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = SchemaServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SchemaServiceClient.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.SchemaServiceTransport, '_prep_wrapped_messages') as prep: - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SchemaServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = SchemaServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = SchemaServiceClient( - 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(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_get_operation(transport: str = "grpc"): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SchemaServiceClient( - 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 = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SchemaServiceClient( - 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 = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = SchemaServiceClient( - 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", [ - (SchemaServiceClient, transports.SchemaServiceGrpcTransport), - (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_search_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_search_service.py deleted file mode 100644 index 27c324f3c01e..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_search_service.py +++ /dev/null @@ -1,2233 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.discoveryengine_v1.services.search_service import SearchServiceAsyncClient -from google.cloud.discoveryengine_v1.services.search_service import SearchServiceClient -from google.cloud.discoveryengine_v1.services.search_service import pagers -from google.cloud.discoveryengine_v1.services.search_service import transports -from google.cloud.discoveryengine_v1.types import common -from google.cloud.discoveryengine_v1.types import search_service -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import struct_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert SearchServiceClient._get_default_mtls_endpoint(None) is None - assert SearchServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (SearchServiceClient, "grpc"), - (SearchServiceAsyncClient, "grpc_asyncio"), - (SearchServiceClient, "rest"), -]) -def test_search_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.SearchServiceGrpcTransport, "grpc"), - (transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.SearchServiceRestTransport, "rest"), -]) -def test_search_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", [ - (SearchServiceClient, "grpc"), - (SearchServiceAsyncClient, "grpc_asyncio"), - (SearchServiceClient, "rest"), -]) -def test_search_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -def test_search_service_client_get_transport_class(): - transport = SearchServiceClient.get_transport_class() - available_transports = [ - transports.SearchServiceGrpcTransport, - transports.SearchServiceRestTransport, - ] - assert transport in available_transports - - transport = SearchServiceClient.get_transport_class("grpc") - assert transport == transports.SearchServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (SearchServiceClient, transports.SearchServiceRestTransport, "rest"), -]) -@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) -@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) -def test_search_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(SearchServiceClient, '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(SearchServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "true"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "false"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (SearchServiceClient, transports.SearchServiceRestTransport, "rest", "true"), - (SearchServiceClient, transports.SearchServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) -@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_search_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 - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - SearchServiceClient, SearchServiceAsyncClient -]) -@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) -@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) -def test_search_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (SearchServiceClient, transports.SearchServiceRestTransport, "rest"), -]) -def test_search_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, - 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", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (SearchServiceClient, transports.SearchServiceRestTransport, "rest", None), -]) -def test_search_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, - scopes=None, - client_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_search_service_client_client_options_from_dict(): - with mock.patch('google.cloud.discoveryengine_v1.services.search_service.transports.SearchServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SearchServiceClient( - 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", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_search_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, - scopes=None, - client_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - search_service.SearchRequest, - dict, -]) -def test_search(request_type, transport: str = 'grpc'): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = search_service.SearchResponse( - total_size=1086, - attribution_token='attribution_token_value', - redirect_uri='redirect_uri_value', - next_page_token='next_page_token_value', - corrected_query='corrected_query_value', - ) - response = client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchPager) - assert response.total_size == 1086 - assert response.attribution_token == 'attribution_token_value' - assert response.redirect_uri == 'redirect_uri_value' - assert response.next_page_token == 'next_page_token_value' - assert response.corrected_query == 'corrected_query_value' - - -def test_search_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - client.search() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - -@pytest.mark.asyncio -async def test_search_async(transport: str = 'grpc_asyncio', request_type=search_service.SearchRequest): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse( - total_size=1086, - attribution_token='attribution_token_value', - redirect_uri='redirect_uri_value', - next_page_token='next_page_token_value', - corrected_query='corrected_query_value', - )) - response = await client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchAsyncPager) - assert response.total_size == 1086 - assert response.attribution_token == 'attribution_token_value' - assert response.redirect_uri == 'redirect_uri_value' - assert response.next_page_token == 'next_page_token_value' - assert response.corrected_query == 'corrected_query_value' - - -@pytest.mark.asyncio -async def test_search_async_from_dict(): - await test_search_async(request_type=dict) - - -def test_search_field_headers(): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = search_service.SearchRequest() - - request.serving_config = 'serving_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - call.return_value = search_service.SearchResponse() - client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config=serving_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_search_field_headers_async(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = search_service.SearchRequest() - - request.serving_config = 'serving_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse()) - await client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config=serving_config_value', - ) in kw['metadata'] - - -def test_search_pager(transport_name: str = "grpc"): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('serving_config', ''), - )), - ) - pager = client.search(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, search_service.SearchResponse.SearchResult) - for i in results) -def test_search_pages(transport_name: str = "grpc"): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - pages = list(client.search(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_search_async_pager(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.search(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, search_service.SearchResponse.SearchResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_search_async_pages(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.search(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", [ - search_service.SearchRequest, - dict, -]) -def test_search_rest(request_type): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'serving_config': 'projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/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 = search_service.SearchResponse( - total_size=1086, - attribution_token='attribution_token_value', - redirect_uri='redirect_uri_value', - next_page_token='next_page_token_value', - corrected_query='corrected_query_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 = search_service.SearchResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.search(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchPager) - assert response.total_size == 1086 - assert response.attribution_token == 'attribution_token_value' - assert response.redirect_uri == 'redirect_uri_value' - assert response.next_page_token == 'next_page_token_value' - assert response.corrected_query == 'corrected_query_value' - - -def test_search_rest_required_fields(request_type=search_service.SearchRequest): - transport_class = transports.SearchServiceRestTransport - - request_init = {} - request_init["serving_config"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["servingConfig"] = 'serving_config_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "servingConfig" in jsonified_request - assert jsonified_request["servingConfig"] == 'serving_config_value' - - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = search_service.SearchResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = search_service.SearchResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.search(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_search_rest_unset_required_fields(): - transport = transports.SearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.search._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("servingConfig", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_search_rest_interceptors(null_interceptor): - transport = transports.SearchServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SearchServiceRestInterceptor(), - ) - client = SearchServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SearchServiceRestInterceptor, "post_search") as post, \ - mock.patch.object(transports.SearchServiceRestInterceptor, "pre_search") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = search_service.SearchRequest.pb(search_service.SearchRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = search_service.SearchResponse.to_json(search_service.SearchResponse()) - - request = search_service.SearchRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = search_service.SearchResponse() - - client.search(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_search_rest_bad_request(transport: str = 'rest', request_type=search_service.SearchRequest): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'serving_config': 'projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.search(request) - - -def test_search_rest_pager(transport: str = 'rest'): - client = SearchServiceClient( - 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 = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(search_service.SearchResponse.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 = {'serving_config': 'projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/sample4'} - - pager = client.search(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, search_service.SearchResponse.SearchResult) - for i in results) - - pages = list(client.search(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.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SearchServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SearchServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.SearchServiceGrpcTransport, - transports.SearchServiceGrpcAsyncIOTransport, - transports.SearchServiceRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = SearchServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.SearchServiceGrpcTransport, - ) - -def test_search_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.SearchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_search_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.discoveryengine_v1.services.search_service.transports.SearchServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SearchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'search', - 'get_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_search_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.discoveryengine_v1.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SearchServiceTransport( - 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_search_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.discoveryengine_v1.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SearchServiceTransport() - adc.assert_called_once() - - -def test_search_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) - SearchServiceClient() - 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.SearchServiceGrpcTransport, - transports.SearchServiceGrpcAsyncIOTransport, - ], -) -def test_search_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.SearchServiceGrpcTransport, - transports.SearchServiceGrpcAsyncIOTransport, - transports.SearchServiceRestTransport, - ], -) -def test_search_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.SearchServiceGrpcTransport, grpc_helpers), - (transports.SearchServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_search_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) -def test_search_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_search_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.SearchServiceRestTransport ( - 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_search_service_host_no_port(transport_name): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_search_service_host_with_port(transport_name): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_search_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = SearchServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = SearchServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.search._session - session2 = client2.transport.search._session - assert session1 != session2 -def test_search_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SearchServiceGrpcTransport( - 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_search_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SearchServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) -def test_search_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.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) -def test_search_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_branch_path(): - project = "squid" - location = "clam" - data_store = "whelk" - branch = "octopus" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}".format(project=project, location=location, data_store=data_store, branch=branch, ) - actual = SearchServiceClient.branch_path(project, location, data_store, branch) - assert expected == actual - - -def test_parse_branch_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "data_store": "cuttlefish", - "branch": "mussel", - } - path = SearchServiceClient.branch_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_branch_path(path) - assert expected == actual - -def test_document_path(): - project = "winkle" - location = "nautilus" - data_store = "scallop" - branch = "abalone" - document = "squid" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) - actual = SearchServiceClient.document_path(project, location, data_store, branch, document) - assert expected == actual - - -def test_parse_document_path(): - expected = { - "project": "clam", - "location": "whelk", - "data_store": "octopus", - "branch": "oyster", - "document": "nudibranch", - } - path = SearchServiceClient.document_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_document_path(path) - assert expected == actual - -def test_serving_config_path(): - project = "cuttlefish" - location = "mussel" - data_store = "winkle" - serving_config = "nautilus" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}/servingConfigs/{serving_config}".format(project=project, location=location, data_store=data_store, serving_config=serving_config, ) - actual = SearchServiceClient.serving_config_path(project, location, data_store, serving_config) - assert expected == actual - - -def test_parse_serving_config_path(): - expected = { - "project": "scallop", - "location": "abalone", - "data_store": "squid", - "serving_config": "clam", - } - path = SearchServiceClient.serving_config_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_serving_config_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SearchServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = SearchServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = SearchServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = SearchServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SearchServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = SearchServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = SearchServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = SearchServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "scallop" - location = "abalone" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = SearchServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = SearchServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.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.SearchServiceTransport, '_prep_wrapped_messages') as prep: - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = SearchServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = SearchServiceClient( - 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(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_get_operation(transport: str = "grpc"): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SearchServiceClient( - 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 = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SearchServiceClient( - 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 = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = SearchServiceClient( - 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", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_user_event_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_user_event_service.py deleted file mode 100644 index 7ff0ea1d704a..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1/tests/unit/gapic/discoveryengine_v1/test_user_event_service.py +++ /dev/null @@ -1,2786 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.discoveryengine_v1.services.user_event_service import UserEventServiceAsyncClient -from google.cloud.discoveryengine_v1.services.user_event_service import UserEventServiceClient -from google.cloud.discoveryengine_v1.services.user_event_service import transports -from google.cloud.discoveryengine_v1.types import common -from google.cloud.discoveryengine_v1.types import import_config -from google.cloud.discoveryengine_v1.types import user_event -from google.cloud.discoveryengine_v1.types import user_event_service -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert UserEventServiceClient._get_default_mtls_endpoint(None) is None - assert UserEventServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (UserEventServiceClient, "grpc"), - (UserEventServiceAsyncClient, "grpc_asyncio"), - (UserEventServiceClient, "rest"), -]) -def test_user_event_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.UserEventServiceGrpcTransport, "grpc"), - (transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.UserEventServiceRestTransport, "rest"), -]) -def test_user_event_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", [ - (UserEventServiceClient, "grpc"), - (UserEventServiceAsyncClient, "grpc_asyncio"), - (UserEventServiceClient, "rest"), -]) -def test_user_event_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -def test_user_event_service_client_get_transport_class(): - transport = UserEventServiceClient.get_transport_class() - available_transports = [ - transports.UserEventServiceGrpcTransport, - transports.UserEventServiceRestTransport, - ] - assert transport in available_transports - - transport = UserEventServiceClient.get_transport_class("grpc") - assert transport == transports.UserEventServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (UserEventServiceClient, transports.UserEventServiceRestTransport, "rest"), -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -def test_user_event_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(UserEventServiceClient, '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(UserEventServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "true"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "false"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (UserEventServiceClient, transports.UserEventServiceRestTransport, "rest", "true"), - (UserEventServiceClient, transports.UserEventServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_user_event_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 - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - UserEventServiceClient, UserEventServiceAsyncClient -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -def test_user_event_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (UserEventServiceClient, transports.UserEventServiceRestTransport, "rest"), -]) -def test_user_event_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, - 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", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (UserEventServiceClient, transports.UserEventServiceRestTransport, "rest", None), -]) -def test_user_event_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, - scopes=None, - client_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_user_event_service_client_client_options_from_dict(): - with mock.patch('google.cloud.discoveryengine_v1.services.user_event_service.transports.UserEventServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = UserEventServiceClient( - 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", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_user_event_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, - scopes=None, - client_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - user_event_service.WriteUserEventRequest, - dict, -]) -def test_write_user_event(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = user_event.UserEvent( - event_type='event_type_value', - user_pseudo_id='user_pseudo_id_value', - direct_user_request=True, - session_id='session_id_value', - attribution_token='attribution_token_value', - filter='filter_value', - tag_ids=['tag_ids_value'], - promotion_ids=['promotion_ids_value'], - ) - response = client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, user_event.UserEvent) - assert response.event_type == 'event_type_value' - assert response.user_pseudo_id == 'user_pseudo_id_value' - assert response.direct_user_request is True - assert response.session_id == 'session_id_value' - assert response.attribution_token == 'attribution_token_value' - assert response.filter == 'filter_value' - assert response.tag_ids == ['tag_ids_value'] - assert response.promotion_ids == ['promotion_ids_value'] - - -def test_write_user_event_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - client.write_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - -@pytest.mark.asyncio -async def test_write_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.WriteUserEventRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent( - event_type='event_type_value', - user_pseudo_id='user_pseudo_id_value', - direct_user_request=True, - session_id='session_id_value', - attribution_token='attribution_token_value', - filter='filter_value', - tag_ids=['tag_ids_value'], - promotion_ids=['promotion_ids_value'], - )) - response = await client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, user_event.UserEvent) - assert response.event_type == 'event_type_value' - assert response.user_pseudo_id == 'user_pseudo_id_value' - assert response.direct_user_request is True - assert response.session_id == 'session_id_value' - assert response.attribution_token == 'attribution_token_value' - assert response.filter == 'filter_value' - assert response.tag_ids == ['tag_ids_value'] - assert response.promotion_ids == ['promotion_ids_value'] - - -@pytest.mark.asyncio -async def test_write_user_event_async_from_dict(): - await test_write_user_event_async(request_type=dict) - - -def test_write_user_event_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.WriteUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - call.return_value = user_event.UserEvent() - client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_write_user_event_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.WriteUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent()) - await client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - user_event_service.CollectUserEventRequest, - dict, -]) -def test_collect_user_event(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - ) - response = client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -def test_collect_user_event_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - client.collect_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - -@pytest.mark.asyncio -async def test_collect_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.CollectUserEventRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - )) - response = await client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -@pytest.mark.asyncio -async def test_collect_user_event_async_from_dict(): - await test_collect_user_event_async(request_type=dict) - - -def test_collect_user_event_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.CollectUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - call.return_value = httpbody_pb2.HttpBody() - client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_collect_user_event_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.CollectUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody()) - await client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportUserEventsRequest, - dict, -]) -def test_import_user_events(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - client.import_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - -@pytest.mark.asyncio -async def test_import_user_events_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportUserEventsRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__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_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_user_events_async_from_dict(): - await test_import_user_events_async(request_type=dict) - - -def test_import_user_events_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_import_user_events_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - user_event_service.WriteUserEventRequest, - dict, -]) -def test_write_user_event_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - request_init["user_event"] = {'event_type': 'event_type_value', 'user_pseudo_id': 'user_pseudo_id_value', 'event_time': {'seconds': 751, 'nanos': 543}, 'user_info': {'user_id': 'user_id_value', 'user_agent': 'user_agent_value'}, 'direct_user_request': True, 'session_id': 'session_id_value', 'page_info': {'pageview_id': 'pageview_id_value', 'page_category': 'page_category_value', 'uri': 'uri_value', 'referrer_uri': 'referrer_uri_value'}, 'attribution_token': 'attribution_token_value', 'filter': 'filter_value', 'documents': [{'id': 'id_value', 'name': 'name_value', 'uri': 'uri_value', 'quantity': 895, 'promotion_ids': ['promotion_ids_value1', 'promotion_ids_value2']}], 'panel': {'panel_id': 'panel_id_value', 'display_name': 'display_name_value', 'panel_position': 1508, 'total_panels': 1286}, 'search_info': {'search_query': 'search_query_value', 'order_by': 'order_by_value', 'offset': 647}, 'completion_info': {'selected_suggestion': 'selected_suggestion_value', 'selected_position': 1821}, 'transaction_info': {'value': 0.541, 'currency': 'currency_value', 'transaction_id': 'transaction_id_value', 'tax': 0.333, 'cost': 0.441, 'discount_value': 0.1509}, 'tag_ids': ['tag_ids_value1', 'tag_ids_value2'], 'promotion_ids': ['promotion_ids_value1', 'promotion_ids_value2'], 'attributes': {}, 'media_info': {'media_progress_duration': {'seconds': 751, 'nanos': 543}, 'media_progress_percentage': 0.2641}} - # 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 = user_event_service.WriteUserEventRequest.meta.fields["user_event"] - - 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_event"].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_event"][field])): - del request_init["user_event"][field][i][subfield] - else: - del request_init["user_event"][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 = user_event.UserEvent( - event_type='event_type_value', - user_pseudo_id='user_pseudo_id_value', - direct_user_request=True, - session_id='session_id_value', - attribution_token='attribution_token_value', - filter='filter_value', - tag_ids=['tag_ids_value'], - promotion_ids=['promotion_ids_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 = user_event.UserEvent.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.write_user_event(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, user_event.UserEvent) - assert response.event_type == 'event_type_value' - assert response.user_pseudo_id == 'user_pseudo_id_value' - assert response.direct_user_request is True - assert response.session_id == 'session_id_value' - assert response.attribution_token == 'attribution_token_value' - assert response.filter == 'filter_value' - assert response.tag_ids == ['tag_ids_value'] - assert response.promotion_ids == ['promotion_ids_value'] - - -def test_write_user_event_rest_required_fields(request_type=user_event_service.WriteUserEventRequest): - transport_class = transports.UserEventServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).write_user_event._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).write_user_event._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = user_event.UserEvent() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = user_event.UserEvent.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.write_user_event(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_write_user_event_rest_unset_required_fields(): - transport = transports.UserEventServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.write_user_event._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "userEvent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_write_user_event_rest_interceptors(null_interceptor): - transport = transports.UserEventServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.UserEventServiceRestInterceptor(), - ) - client = UserEventServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.UserEventServiceRestInterceptor, "post_write_user_event") as post, \ - mock.patch.object(transports.UserEventServiceRestInterceptor, "pre_write_user_event") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = user_event_service.WriteUserEventRequest.pb(user_event_service.WriteUserEventRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = user_event.UserEvent.to_json(user_event.UserEvent()) - - request = user_event_service.WriteUserEventRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = user_event.UserEvent() - - client.write_user_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_write_user_event_rest_bad_request(transport: str = 'rest', request_type=user_event_service.WriteUserEventRequest): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.write_user_event(request) - - -def test_write_user_event_rest_error(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - user_event_service.CollectUserEventRequest, - dict, -]) -def test_collect_user_event_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/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 = httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.collect_user_event(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -def test_collect_user_event_rest_required_fields(request_type=user_event_service.CollectUserEventRequest): - transport_class = transports.UserEventServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["user_event"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "userEvent" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).collect_user_event._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "userEvent" in jsonified_request - assert jsonified_request["userEvent"] == request_init["user_event"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["userEvent"] = 'user_event_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).collect_user_event._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("ets", "uri", "user_event", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "userEvent" in jsonified_request - assert jsonified_request["userEvent"] == 'user_event_value' - - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = httpbody_pb2.HttpBody() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 - - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.collect_user_event(request) - - expected_params = [ - ( - "userEvent", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_collect_user_event_rest_unset_required_fields(): - transport = transports.UserEventServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.collect_user_event._get_unset_required_fields({}) - assert set(unset_fields) == (set(("ets", "uri", "userEvent", )) & set(("parent", "userEvent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_collect_user_event_rest_interceptors(null_interceptor): - transport = transports.UserEventServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.UserEventServiceRestInterceptor(), - ) - client = UserEventServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.UserEventServiceRestInterceptor, "post_collect_user_event") as post, \ - mock.patch.object(transports.UserEventServiceRestInterceptor, "pre_collect_user_event") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = user_event_service.CollectUserEventRequest.pb(user_event_service.CollectUserEventRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(httpbody_pb2.HttpBody()) - - request = user_event_service.CollectUserEventRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = httpbody_pb2.HttpBody() - - client.collect_user_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_collect_user_event_rest_bad_request(transport: str = 'rest', request_type=user_event_service.CollectUserEventRequest): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.collect_user_event(request) - - -def test_collect_user_event_rest_error(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportUserEventsRequest, - dict, -]) -def test_import_user_events_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.import_user_events(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_import_user_events_rest_required_fields(request_type=import_config.ImportUserEventsRequest): - transport_class = transports.UserEventServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_user_events._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_user_events._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.import_user_events(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_import_user_events_rest_unset_required_fields(): - transport = transports.UserEventServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.import_user_events._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_import_user_events_rest_interceptors(null_interceptor): - transport = transports.UserEventServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.UserEventServiceRestInterceptor(), - ) - client = UserEventServiceClient(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.UserEventServiceRestInterceptor, "post_import_user_events") as post, \ - mock.patch.object(transports.UserEventServiceRestInterceptor, "pre_import_user_events") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = import_config.ImportUserEventsRequest.pb(import_config.ImportUserEventsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = import_config.ImportUserEventsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.import_user_events(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_import_user_events_rest_bad_request(transport: str = 'rest', request_type=import_config.ImportUserEventsRequest): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.import_user_events(request) - - -def test_import_user_events_rest_error(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = UserEventServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.UserEventServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, - transports.UserEventServiceRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = UserEventServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.UserEventServiceGrpcTransport, - ) - -def test_user_event_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.UserEventServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_user_event_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.discoveryengine_v1.services.user_event_service.transports.UserEventServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.UserEventServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'write_user_event', - 'collect_user_event', - 'import_user_events', - 'get_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_user_event_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.discoveryengine_v1.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.UserEventServiceTransport( - 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_user_event_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.discoveryengine_v1.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.UserEventServiceTransport() - adc.assert_called_once() - - -def test_user_event_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) - UserEventServiceClient() - 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.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, - ], -) -def test_user_event_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.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, - transports.UserEventServiceRestTransport, - ], -) -def test_user_event_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.UserEventServiceGrpcTransport, grpc_helpers), - (transports.UserEventServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_user_event_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_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_user_event_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.UserEventServiceRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_user_event_service_rest_lro_client(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_user_event_service_host_no_port(transport_name): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_user_event_service_host_with_port(transport_name): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_user_event_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = UserEventServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = UserEventServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.write_user_event._session - session2 = client2.transport.write_user_event._session - assert session1 != session2 - session1 = client1.transport.collect_user_event._session - session2 = client2.transport.collect_user_event._session - assert session1 != session2 - session1 = client1.transport.import_user_events._session - session2 = client2.transport.import_user_events._session - assert session1 != session2 -def test_user_event_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.UserEventServiceGrpcTransport( - 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_user_event_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.UserEventServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_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.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_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_user_event_service_grpc_lro_client(): - client = UserEventServiceClient( - 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_user_event_service_grpc_lro_async_client(): - client = UserEventServiceAsyncClient( - 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_data_store_path(): - project = "squid" - location = "clam" - data_store = "whelk" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) - actual = UserEventServiceClient.data_store_path(project, location, data_store) - assert expected == actual - - -def test_parse_data_store_path(): - expected = { - "project": "octopus", - "location": "oyster", - "data_store": "nudibranch", - } - path = UserEventServiceClient.data_store_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_data_store_path(path) - assert expected == actual - -def test_document_path(): - project = "cuttlefish" - location = "mussel" - data_store = "winkle" - branch = "nautilus" - document = "scallop" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) - actual = UserEventServiceClient.document_path(project, location, data_store, branch, document) - assert expected == actual - - -def test_parse_document_path(): - expected = { - "project": "abalone", - "location": "squid", - "data_store": "clam", - "branch": "whelk", - "document": "octopus", - } - path = UserEventServiceClient.document_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_document_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = UserEventServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = UserEventServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = UserEventServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = UserEventServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = UserEventServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = UserEventServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = UserEventServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = UserEventServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "squid" - location = "clam" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = UserEventServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = UserEventServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.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.UserEventServiceTransport, '_prep_wrapped_messages') as prep: - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = UserEventServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/operations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/operations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = UserEventServiceClient( - 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(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_get_operation(transport: str = "grpc"): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = UserEventServiceClient( - 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 = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = UserEventServiceClient( - 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 = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = UserEventServiceClient( - 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", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/.coveragerc b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/.coveragerc deleted file mode 100644 index f2c9bc595be9..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/discoveryengine/__init__.py - google/cloud/discoveryengine/gapic_version.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/.flake8 b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/MANIFEST.in b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/MANIFEST.in deleted file mode 100644 index f798e554c570..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/discoveryengine *.py -recursive-include google/cloud/discoveryengine_v1alpha *.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/README.rst b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/README.rst deleted file mode 100644 index 25f579284266..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Discoveryengine API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Discoveryengine API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/_static/custom.css b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/conf.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/conf.py deleted file mode 100644 index 9852ef988546..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-cloud-discoveryengine documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-cloud-discoveryengine" -copyright = u"2023, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = 'en' - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-discoveryengine-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-cloud-discoveryengine.tex", - u"google-cloud-discoveryengine Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - root_doc, - "google-cloud-discoveryengine", - u"Google Cloud Discoveryengine Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-cloud-discoveryengine", - u"google-cloud-discoveryengine Documentation", - author, - "google-cloud-discoveryengine", - "GAPIC library for Google Cloud Discoveryengine API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/completion_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/completion_service.rst deleted file mode 100644 index 8f4c72412f68..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/completion_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -CompletionService ------------------------------------ - -.. automodule:: google.cloud.discoveryengine_v1alpha.services.completion_service - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/conversational_search_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/conversational_search_service.rst deleted file mode 100644 index 50123289725d..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/conversational_search_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -ConversationalSearchService ---------------------------------------------- - -.. automodule:: google.cloud.discoveryengine_v1alpha.services.conversational_search_service - :members: - :inherited-members: - -.. automodule:: google.cloud.discoveryengine_v1alpha.services.conversational_search_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/document_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/document_service.rst deleted file mode 100644 index 295c3e8a2875..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/document_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -DocumentService ---------------------------------- - -.. automodule:: google.cloud.discoveryengine_v1alpha.services.document_service - :members: - :inherited-members: - -.. automodule:: google.cloud.discoveryengine_v1alpha.services.document_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/recommendation_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/recommendation_service.rst deleted file mode 100644 index 440ff0398fd3..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/recommendation_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -RecommendationService ---------------------------------------- - -.. automodule:: google.cloud.discoveryengine_v1alpha.services.recommendation_service - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/schema_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/schema_service.rst deleted file mode 100644 index 73d40c3718e6..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/schema_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -SchemaService -------------------------------- - -.. automodule:: google.cloud.discoveryengine_v1alpha.services.schema_service - :members: - :inherited-members: - -.. automodule:: google.cloud.discoveryengine_v1alpha.services.schema_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/search_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/search_service.rst deleted file mode 100644 index fa744f4a4ae9..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/search_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -SearchService -------------------------------- - -.. automodule:: google.cloud.discoveryengine_v1alpha.services.search_service - :members: - :inherited-members: - -.. automodule:: google.cloud.discoveryengine_v1alpha.services.search_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/services_.rst b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/services_.rst deleted file mode 100644 index 0177e984c5cc..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/services_.rst +++ /dev/null @@ -1,15 +0,0 @@ -Services for Google Cloud Discoveryengine v1alpha API -===================================================== -.. toctree:: - :maxdepth: 2 - - completion_service - conversational_search_service - data_store_service - document_service - engine_service - recommendation_service - schema_service - search_service - site_search_engine_service - user_event_service diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/site_search_engine_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/site_search_engine_service.rst deleted file mode 100644 index 438309914a4a..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/site_search_engine_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -SiteSearchEngineService ------------------------------------------ - -.. automodule:: google.cloud.discoveryengine_v1alpha.services.site_search_engine_service - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/types_.rst b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/types_.rst deleted file mode 100644 index 8d74074a2c19..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Discoveryengine v1alpha API -================================================== - -.. automodule:: google.cloud.discoveryengine_v1alpha.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/user_event_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/user_event_service.rst deleted file mode 100644 index 3b383e9c7d16..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/user_event_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -UserEventService ----------------------------------- - -.. automodule:: google.cloud.discoveryengine_v1alpha.services.user_event_service - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/index.rst b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/index.rst deleted file mode 100644 index d45fecf9bdd5..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - discoveryengine_v1alpha/services - discoveryengine_v1alpha/types diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine/__init__.py deleted file mode 100644 index c5d2e50633bd..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine/__init__.py +++ /dev/null @@ -1,255 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.cloud.discoveryengine import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.discoveryengine_v1alpha.services.completion_service.client import CompletionServiceClient -from google.cloud.discoveryengine_v1alpha.services.completion_service.async_client import CompletionServiceAsyncClient -from google.cloud.discoveryengine_v1alpha.services.conversational_search_service.client import ConversationalSearchServiceClient -from google.cloud.discoveryengine_v1alpha.services.conversational_search_service.async_client import ConversationalSearchServiceAsyncClient -from google.cloud.discoveryengine_v1alpha.services.data_store_service.client import DataStoreServiceClient -from google.cloud.discoveryengine_v1alpha.services.data_store_service.async_client import DataStoreServiceAsyncClient -from google.cloud.discoveryengine_v1alpha.services.document_service.client import DocumentServiceClient -from google.cloud.discoveryengine_v1alpha.services.document_service.async_client import DocumentServiceAsyncClient -from google.cloud.discoveryengine_v1alpha.services.engine_service.client import EngineServiceClient -from google.cloud.discoveryengine_v1alpha.services.engine_service.async_client import EngineServiceAsyncClient -from google.cloud.discoveryengine_v1alpha.services.recommendation_service.client import RecommendationServiceClient -from google.cloud.discoveryengine_v1alpha.services.recommendation_service.async_client import RecommendationServiceAsyncClient -from google.cloud.discoveryengine_v1alpha.services.schema_service.client import SchemaServiceClient -from google.cloud.discoveryengine_v1alpha.services.schema_service.async_client import SchemaServiceAsyncClient -from google.cloud.discoveryengine_v1alpha.services.search_service.client import SearchServiceClient -from google.cloud.discoveryengine_v1alpha.services.search_service.async_client import SearchServiceAsyncClient -from google.cloud.discoveryengine_v1alpha.services.site_search_engine_service.client import SiteSearchEngineServiceClient -from google.cloud.discoveryengine_v1alpha.services.site_search_engine_service.async_client import SiteSearchEngineServiceAsyncClient -from google.cloud.discoveryengine_v1alpha.services.user_event_service.client import UserEventServiceClient -from google.cloud.discoveryengine_v1alpha.services.user_event_service.async_client import UserEventServiceAsyncClient - -from google.cloud.discoveryengine_v1alpha.types.common import CustomAttribute -from google.cloud.discoveryengine_v1alpha.types.common import DoubleList -from google.cloud.discoveryengine_v1alpha.types.common import Interval -from google.cloud.discoveryengine_v1alpha.types.common import UserInfo -from google.cloud.discoveryengine_v1alpha.types.common import IndustryVertical -from google.cloud.discoveryengine_v1alpha.types.common import SearchAddOn -from google.cloud.discoveryengine_v1alpha.types.common import SearchTier -from google.cloud.discoveryengine_v1alpha.types.common import SolutionType -from google.cloud.discoveryengine_v1alpha.types.completion_service import CompleteQueryRequest -from google.cloud.discoveryengine_v1alpha.types.completion_service import CompleteQueryResponse -from google.cloud.discoveryengine_v1alpha.types.conversation import Conversation -from google.cloud.discoveryengine_v1alpha.types.conversation import ConversationContext -from google.cloud.discoveryengine_v1alpha.types.conversation import ConversationMessage -from google.cloud.discoveryengine_v1alpha.types.conversation import Reply -from google.cloud.discoveryengine_v1alpha.types.conversation import TextInput -from google.cloud.discoveryengine_v1alpha.types.conversational_search_service import ConverseConversationRequest -from google.cloud.discoveryengine_v1alpha.types.conversational_search_service import ConverseConversationResponse -from google.cloud.discoveryengine_v1alpha.types.conversational_search_service import CreateConversationRequest -from google.cloud.discoveryengine_v1alpha.types.conversational_search_service import DeleteConversationRequest -from google.cloud.discoveryengine_v1alpha.types.conversational_search_service import GetConversationRequest -from google.cloud.discoveryengine_v1alpha.types.conversational_search_service import ListConversationsRequest -from google.cloud.discoveryengine_v1alpha.types.conversational_search_service import ListConversationsResponse -from google.cloud.discoveryengine_v1alpha.types.conversational_search_service import UpdateConversationRequest -from google.cloud.discoveryengine_v1alpha.types.data_store import DataStore -from google.cloud.discoveryengine_v1alpha.types.data_store_service import CreateDataStoreMetadata -from google.cloud.discoveryengine_v1alpha.types.data_store_service import CreateDataStoreRequest -from google.cloud.discoveryengine_v1alpha.types.data_store_service import DeleteDataStoreMetadata -from google.cloud.discoveryengine_v1alpha.types.data_store_service import DeleteDataStoreRequest -from google.cloud.discoveryengine_v1alpha.types.data_store_service import GetDataStoreRequest -from google.cloud.discoveryengine_v1alpha.types.data_store_service import ListDataStoresRequest -from google.cloud.discoveryengine_v1alpha.types.data_store_service import ListDataStoresResponse -from google.cloud.discoveryengine_v1alpha.types.data_store_service import UpdateDataStoreRequest -from google.cloud.discoveryengine_v1alpha.types.document import Document -from google.cloud.discoveryengine_v1alpha.types.document_service import CreateDocumentRequest -from google.cloud.discoveryengine_v1alpha.types.document_service import DeleteDocumentRequest -from google.cloud.discoveryengine_v1alpha.types.document_service import GetDocumentRequest -from google.cloud.discoveryengine_v1alpha.types.document_service import ListDocumentsRequest -from google.cloud.discoveryengine_v1alpha.types.document_service import ListDocumentsResponse -from google.cloud.discoveryengine_v1alpha.types.document_service import UpdateDocumentRequest -from google.cloud.discoveryengine_v1alpha.types.engine import Engine -from google.cloud.discoveryengine_v1alpha.types.engine_service import CreateEngineMetadata -from google.cloud.discoveryengine_v1alpha.types.engine_service import CreateEngineRequest -from google.cloud.discoveryengine_v1alpha.types.engine_service import DeleteEngineMetadata -from google.cloud.discoveryengine_v1alpha.types.engine_service import DeleteEngineRequest -from google.cloud.discoveryengine_v1alpha.types.engine_service import GetEngineRequest -from google.cloud.discoveryengine_v1alpha.types.engine_service import ListEnginesRequest -from google.cloud.discoveryengine_v1alpha.types.engine_service import ListEnginesResponse -from google.cloud.discoveryengine_v1alpha.types.engine_service import PauseEngineRequest -from google.cloud.discoveryengine_v1alpha.types.engine_service import ResumeEngineRequest -from google.cloud.discoveryengine_v1alpha.types.engine_service import TuneEngineMetadata -from google.cloud.discoveryengine_v1alpha.types.engine_service import TuneEngineRequest -from google.cloud.discoveryengine_v1alpha.types.engine_service import TuneEngineResponse -from google.cloud.discoveryengine_v1alpha.types.engine_service import UpdateEngineRequest -from google.cloud.discoveryengine_v1alpha.types.import_config import BigQuerySource -from google.cloud.discoveryengine_v1alpha.types.import_config import GcsSource -from google.cloud.discoveryengine_v1alpha.types.import_config import ImportDocumentsMetadata -from google.cloud.discoveryengine_v1alpha.types.import_config import ImportDocumentsRequest -from google.cloud.discoveryengine_v1alpha.types.import_config import ImportDocumentsResponse -from google.cloud.discoveryengine_v1alpha.types.import_config import ImportErrorConfig -from google.cloud.discoveryengine_v1alpha.types.import_config import ImportUserEventsMetadata -from google.cloud.discoveryengine_v1alpha.types.import_config import ImportUserEventsRequest -from google.cloud.discoveryengine_v1alpha.types.import_config import ImportUserEventsResponse -from google.cloud.discoveryengine_v1alpha.types.purge_config import PurgeDocumentsMetadata -from google.cloud.discoveryengine_v1alpha.types.purge_config import PurgeDocumentsRequest -from google.cloud.discoveryengine_v1alpha.types.purge_config import PurgeDocumentsResponse -from google.cloud.discoveryengine_v1alpha.types.purge_config import PurgeUserEventsMetadata -from google.cloud.discoveryengine_v1alpha.types.purge_config import PurgeUserEventsRequest -from google.cloud.discoveryengine_v1alpha.types.purge_config import PurgeUserEventsResponse -from google.cloud.discoveryengine_v1alpha.types.recommendation_service import RecommendRequest -from google.cloud.discoveryengine_v1alpha.types.recommendation_service import RecommendResponse -from google.cloud.discoveryengine_v1alpha.types.schema import FieldConfig -from google.cloud.discoveryengine_v1alpha.types.schema import Schema -from google.cloud.discoveryengine_v1alpha.types.schema_service import CreateSchemaMetadata -from google.cloud.discoveryengine_v1alpha.types.schema_service import CreateSchemaRequest -from google.cloud.discoveryengine_v1alpha.types.schema_service import DeleteSchemaMetadata -from google.cloud.discoveryengine_v1alpha.types.schema_service import DeleteSchemaRequest -from google.cloud.discoveryengine_v1alpha.types.schema_service import GetSchemaRequest -from google.cloud.discoveryengine_v1alpha.types.schema_service import ListSchemasRequest -from google.cloud.discoveryengine_v1alpha.types.schema_service import ListSchemasResponse -from google.cloud.discoveryengine_v1alpha.types.schema_service import UpdateSchemaMetadata -from google.cloud.discoveryengine_v1alpha.types.schema_service import UpdateSchemaRequest -from google.cloud.discoveryengine_v1alpha.types.search_service import SearchRequest -from google.cloud.discoveryengine_v1alpha.types.search_service import SearchResponse -from google.cloud.discoveryengine_v1alpha.types.site_search_engine_service import RecrawlUrisMetadata -from google.cloud.discoveryengine_v1alpha.types.site_search_engine_service import RecrawlUrisRequest -from google.cloud.discoveryengine_v1alpha.types.site_search_engine_service import RecrawlUrisResponse -from google.cloud.discoveryengine_v1alpha.types.user_event import CompletionInfo -from google.cloud.discoveryengine_v1alpha.types.user_event import DocumentInfo -from google.cloud.discoveryengine_v1alpha.types.user_event import MediaInfo -from google.cloud.discoveryengine_v1alpha.types.user_event import PageInfo -from google.cloud.discoveryengine_v1alpha.types.user_event import PanelInfo -from google.cloud.discoveryengine_v1alpha.types.user_event import SearchInfo -from google.cloud.discoveryengine_v1alpha.types.user_event import TransactionInfo -from google.cloud.discoveryengine_v1alpha.types.user_event import UserEvent -from google.cloud.discoveryengine_v1alpha.types.user_event_service import CollectUserEventRequest -from google.cloud.discoveryengine_v1alpha.types.user_event_service import WriteUserEventRequest - -__all__ = ('CompletionServiceClient', - 'CompletionServiceAsyncClient', - 'ConversationalSearchServiceClient', - 'ConversationalSearchServiceAsyncClient', - 'DataStoreServiceClient', - 'DataStoreServiceAsyncClient', - 'DocumentServiceClient', - 'DocumentServiceAsyncClient', - 'EngineServiceClient', - 'EngineServiceAsyncClient', - 'RecommendationServiceClient', - 'RecommendationServiceAsyncClient', - 'SchemaServiceClient', - 'SchemaServiceAsyncClient', - 'SearchServiceClient', - 'SearchServiceAsyncClient', - 'SiteSearchEngineServiceClient', - 'SiteSearchEngineServiceAsyncClient', - 'UserEventServiceClient', - 'UserEventServiceAsyncClient', - 'CustomAttribute', - 'DoubleList', - 'Interval', - 'UserInfo', - 'IndustryVertical', - 'SearchAddOn', - 'SearchTier', - 'SolutionType', - 'CompleteQueryRequest', - 'CompleteQueryResponse', - 'Conversation', - 'ConversationContext', - 'ConversationMessage', - 'Reply', - 'TextInput', - 'ConverseConversationRequest', - 'ConverseConversationResponse', - 'CreateConversationRequest', - 'DeleteConversationRequest', - 'GetConversationRequest', - 'ListConversationsRequest', - 'ListConversationsResponse', - 'UpdateConversationRequest', - 'DataStore', - 'CreateDataStoreMetadata', - 'CreateDataStoreRequest', - 'DeleteDataStoreMetadata', - 'DeleteDataStoreRequest', - 'GetDataStoreRequest', - 'ListDataStoresRequest', - 'ListDataStoresResponse', - 'UpdateDataStoreRequest', - 'Document', - 'CreateDocumentRequest', - 'DeleteDocumentRequest', - 'GetDocumentRequest', - 'ListDocumentsRequest', - 'ListDocumentsResponse', - 'UpdateDocumentRequest', - 'Engine', - 'CreateEngineMetadata', - 'CreateEngineRequest', - 'DeleteEngineMetadata', - 'DeleteEngineRequest', - 'GetEngineRequest', - 'ListEnginesRequest', - 'ListEnginesResponse', - 'PauseEngineRequest', - 'ResumeEngineRequest', - 'TuneEngineMetadata', - 'TuneEngineRequest', - 'TuneEngineResponse', - 'UpdateEngineRequest', - 'BigQuerySource', - 'GcsSource', - 'ImportDocumentsMetadata', - 'ImportDocumentsRequest', - 'ImportDocumentsResponse', - 'ImportErrorConfig', - 'ImportUserEventsMetadata', - 'ImportUserEventsRequest', - 'ImportUserEventsResponse', - 'PurgeDocumentsMetadata', - 'PurgeDocumentsRequest', - 'PurgeDocumentsResponse', - 'PurgeUserEventsMetadata', - 'PurgeUserEventsRequest', - 'PurgeUserEventsResponse', - 'RecommendRequest', - 'RecommendResponse', - 'FieldConfig', - 'Schema', - 'CreateSchemaMetadata', - 'CreateSchemaRequest', - 'DeleteSchemaMetadata', - 'DeleteSchemaRequest', - 'GetSchemaRequest', - 'ListSchemasRequest', - 'ListSchemasResponse', - 'UpdateSchemaMetadata', - 'UpdateSchemaRequest', - 'SearchRequest', - 'SearchResponse', - 'RecrawlUrisMetadata', - 'RecrawlUrisRequest', - 'RecrawlUrisResponse', - 'CompletionInfo', - 'DocumentInfo', - 'MediaInfo', - 'PageInfo', - 'PanelInfo', - 'SearchInfo', - 'TransactionInfo', - 'UserEvent', - 'CollectUserEventRequest', - 'WriteUserEventRequest', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine/gapic_version.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine/gapic_version.py deleted file mode 100644 index 360a0d13ebdd..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine/py.typed b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine/py.typed deleted file mode 100644 index 2ff6437cf473..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-discoveryengine package uses inline types. diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/__init__.py deleted file mode 100644 index 06627ea8bf76..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/__init__.py +++ /dev/null @@ -1,256 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.cloud.discoveryengine_v1alpha import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.completion_service import CompletionServiceClient -from .services.completion_service import CompletionServiceAsyncClient -from .services.conversational_search_service import ConversationalSearchServiceClient -from .services.conversational_search_service import ConversationalSearchServiceAsyncClient -from .services.data_store_service import DataStoreServiceClient -from .services.data_store_service import DataStoreServiceAsyncClient -from .services.document_service import DocumentServiceClient -from .services.document_service import DocumentServiceAsyncClient -from .services.engine_service import EngineServiceClient -from .services.engine_service import EngineServiceAsyncClient -from .services.recommendation_service import RecommendationServiceClient -from .services.recommendation_service import RecommendationServiceAsyncClient -from .services.schema_service import SchemaServiceClient -from .services.schema_service import SchemaServiceAsyncClient -from .services.search_service import SearchServiceClient -from .services.search_service import SearchServiceAsyncClient -from .services.site_search_engine_service import SiteSearchEngineServiceClient -from .services.site_search_engine_service import SiteSearchEngineServiceAsyncClient -from .services.user_event_service import UserEventServiceClient -from .services.user_event_service import UserEventServiceAsyncClient - -from .types.common import CustomAttribute -from .types.common import DoubleList -from .types.common import Interval -from .types.common import UserInfo -from .types.common import IndustryVertical -from .types.common import SearchAddOn -from .types.common import SearchTier -from .types.common import SolutionType -from .types.completion_service import CompleteQueryRequest -from .types.completion_service import CompleteQueryResponse -from .types.conversation import Conversation -from .types.conversation import ConversationContext -from .types.conversation import ConversationMessage -from .types.conversation import Reply -from .types.conversation import TextInput -from .types.conversational_search_service import ConverseConversationRequest -from .types.conversational_search_service import ConverseConversationResponse -from .types.conversational_search_service import CreateConversationRequest -from .types.conversational_search_service import DeleteConversationRequest -from .types.conversational_search_service import GetConversationRequest -from .types.conversational_search_service import ListConversationsRequest -from .types.conversational_search_service import ListConversationsResponse -from .types.conversational_search_service import UpdateConversationRequest -from .types.data_store import DataStore -from .types.data_store_service import CreateDataStoreMetadata -from .types.data_store_service import CreateDataStoreRequest -from .types.data_store_service import DeleteDataStoreMetadata -from .types.data_store_service import DeleteDataStoreRequest -from .types.data_store_service import GetDataStoreRequest -from .types.data_store_service import ListDataStoresRequest -from .types.data_store_service import ListDataStoresResponse -from .types.data_store_service import UpdateDataStoreRequest -from .types.document import Document -from .types.document_service import CreateDocumentRequest -from .types.document_service import DeleteDocumentRequest -from .types.document_service import GetDocumentRequest -from .types.document_service import ListDocumentsRequest -from .types.document_service import ListDocumentsResponse -from .types.document_service import UpdateDocumentRequest -from .types.engine import Engine -from .types.engine_service import CreateEngineMetadata -from .types.engine_service import CreateEngineRequest -from .types.engine_service import DeleteEngineMetadata -from .types.engine_service import DeleteEngineRequest -from .types.engine_service import GetEngineRequest -from .types.engine_service import ListEnginesRequest -from .types.engine_service import ListEnginesResponse -from .types.engine_service import PauseEngineRequest -from .types.engine_service import ResumeEngineRequest -from .types.engine_service import TuneEngineMetadata -from .types.engine_service import TuneEngineRequest -from .types.engine_service import TuneEngineResponse -from .types.engine_service import UpdateEngineRequest -from .types.import_config import BigQuerySource -from .types.import_config import GcsSource -from .types.import_config import ImportDocumentsMetadata -from .types.import_config import ImportDocumentsRequest -from .types.import_config import ImportDocumentsResponse -from .types.import_config import ImportErrorConfig -from .types.import_config import ImportUserEventsMetadata -from .types.import_config import ImportUserEventsRequest -from .types.import_config import ImportUserEventsResponse -from .types.purge_config import PurgeDocumentsMetadata -from .types.purge_config import PurgeDocumentsRequest -from .types.purge_config import PurgeDocumentsResponse -from .types.purge_config import PurgeUserEventsMetadata -from .types.purge_config import PurgeUserEventsRequest -from .types.purge_config import PurgeUserEventsResponse -from .types.recommendation_service import RecommendRequest -from .types.recommendation_service import RecommendResponse -from .types.schema import FieldConfig -from .types.schema import Schema -from .types.schema_service import CreateSchemaMetadata -from .types.schema_service import CreateSchemaRequest -from .types.schema_service import DeleteSchemaMetadata -from .types.schema_service import DeleteSchemaRequest -from .types.schema_service import GetSchemaRequest -from .types.schema_service import ListSchemasRequest -from .types.schema_service import ListSchemasResponse -from .types.schema_service import UpdateSchemaMetadata -from .types.schema_service import UpdateSchemaRequest -from .types.search_service import SearchRequest -from .types.search_service import SearchResponse -from .types.site_search_engine_service import RecrawlUrisMetadata -from .types.site_search_engine_service import RecrawlUrisRequest -from .types.site_search_engine_service import RecrawlUrisResponse -from .types.user_event import CompletionInfo -from .types.user_event import DocumentInfo -from .types.user_event import MediaInfo -from .types.user_event import PageInfo -from .types.user_event import PanelInfo -from .types.user_event import SearchInfo -from .types.user_event import TransactionInfo -from .types.user_event import UserEvent -from .types.user_event_service import CollectUserEventRequest -from .types.user_event_service import WriteUserEventRequest - -__all__ = ( - 'CompletionServiceAsyncClient', - 'ConversationalSearchServiceAsyncClient', - 'DataStoreServiceAsyncClient', - 'DocumentServiceAsyncClient', - 'EngineServiceAsyncClient', - 'RecommendationServiceAsyncClient', - 'SchemaServiceAsyncClient', - 'SearchServiceAsyncClient', - 'SiteSearchEngineServiceAsyncClient', - 'UserEventServiceAsyncClient', -'BigQuerySource', -'CollectUserEventRequest', -'CompleteQueryRequest', -'CompleteQueryResponse', -'CompletionInfo', -'CompletionServiceClient', -'Conversation', -'ConversationContext', -'ConversationMessage', -'ConversationalSearchServiceClient', -'ConverseConversationRequest', -'ConverseConversationResponse', -'CreateConversationRequest', -'CreateDataStoreMetadata', -'CreateDataStoreRequest', -'CreateDocumentRequest', -'CreateEngineMetadata', -'CreateEngineRequest', -'CreateSchemaMetadata', -'CreateSchemaRequest', -'CustomAttribute', -'DataStore', -'DataStoreServiceClient', -'DeleteConversationRequest', -'DeleteDataStoreMetadata', -'DeleteDataStoreRequest', -'DeleteDocumentRequest', -'DeleteEngineMetadata', -'DeleteEngineRequest', -'DeleteSchemaMetadata', -'DeleteSchemaRequest', -'Document', -'DocumentInfo', -'DocumentServiceClient', -'DoubleList', -'Engine', -'EngineServiceClient', -'FieldConfig', -'GcsSource', -'GetConversationRequest', -'GetDataStoreRequest', -'GetDocumentRequest', -'GetEngineRequest', -'GetSchemaRequest', -'ImportDocumentsMetadata', -'ImportDocumentsRequest', -'ImportDocumentsResponse', -'ImportErrorConfig', -'ImportUserEventsMetadata', -'ImportUserEventsRequest', -'ImportUserEventsResponse', -'IndustryVertical', -'Interval', -'ListConversationsRequest', -'ListConversationsResponse', -'ListDataStoresRequest', -'ListDataStoresResponse', -'ListDocumentsRequest', -'ListDocumentsResponse', -'ListEnginesRequest', -'ListEnginesResponse', -'ListSchemasRequest', -'ListSchemasResponse', -'MediaInfo', -'PageInfo', -'PanelInfo', -'PauseEngineRequest', -'PurgeDocumentsMetadata', -'PurgeDocumentsRequest', -'PurgeDocumentsResponse', -'PurgeUserEventsMetadata', -'PurgeUserEventsRequest', -'PurgeUserEventsResponse', -'RecommendRequest', -'RecommendResponse', -'RecommendationServiceClient', -'RecrawlUrisMetadata', -'RecrawlUrisRequest', -'RecrawlUrisResponse', -'Reply', -'ResumeEngineRequest', -'Schema', -'SchemaServiceClient', -'SearchAddOn', -'SearchInfo', -'SearchRequest', -'SearchResponse', -'SearchServiceClient', -'SearchTier', -'SiteSearchEngineServiceClient', -'SolutionType', -'TextInput', -'TransactionInfo', -'TuneEngineMetadata', -'TuneEngineRequest', -'TuneEngineResponse', -'UpdateConversationRequest', -'UpdateDataStoreRequest', -'UpdateDocumentRequest', -'UpdateEngineRequest', -'UpdateSchemaMetadata', -'UpdateSchemaRequest', -'UserEvent', -'UserEventServiceClient', -'UserInfo', -'WriteUserEventRequest', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/gapic_metadata.json b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/gapic_metadata.json deleted file mode 100644 index 6d78899820ae..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/gapic_metadata.json +++ /dev/null @@ -1,784 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.discoveryengine_v1alpha", - "protoPackage": "google.cloud.discoveryengine.v1alpha", - "schema": "1.0", - "services": { - "CompletionService": { - "clients": { - "grpc": { - "libraryClient": "CompletionServiceClient", - "rpcs": { - "CompleteQuery": { - "methods": [ - "complete_query" - ] - } - } - }, - "grpc-async": { - "libraryClient": "CompletionServiceAsyncClient", - "rpcs": { - "CompleteQuery": { - "methods": [ - "complete_query" - ] - } - } - }, - "rest": { - "libraryClient": "CompletionServiceClient", - "rpcs": { - "CompleteQuery": { - "methods": [ - "complete_query" - ] - } - } - } - } - }, - "ConversationalSearchService": { - "clients": { - "grpc": { - "libraryClient": "ConversationalSearchServiceClient", - "rpcs": { - "ConverseConversation": { - "methods": [ - "converse_conversation" - ] - }, - "CreateConversation": { - "methods": [ - "create_conversation" - ] - }, - "DeleteConversation": { - "methods": [ - "delete_conversation" - ] - }, - "GetConversation": { - "methods": [ - "get_conversation" - ] - }, - "ListConversations": { - "methods": [ - "list_conversations" - ] - }, - "UpdateConversation": { - "methods": [ - "update_conversation" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ConversationalSearchServiceAsyncClient", - "rpcs": { - "ConverseConversation": { - "methods": [ - "converse_conversation" - ] - }, - "CreateConversation": { - "methods": [ - "create_conversation" - ] - }, - "DeleteConversation": { - "methods": [ - "delete_conversation" - ] - }, - "GetConversation": { - "methods": [ - "get_conversation" - ] - }, - "ListConversations": { - "methods": [ - "list_conversations" - ] - }, - "UpdateConversation": { - "methods": [ - "update_conversation" - ] - } - } - }, - "rest": { - "libraryClient": "ConversationalSearchServiceClient", - "rpcs": { - "ConverseConversation": { - "methods": [ - "converse_conversation" - ] - }, - "CreateConversation": { - "methods": [ - "create_conversation" - ] - }, - "DeleteConversation": { - "methods": [ - "delete_conversation" - ] - }, - "GetConversation": { - "methods": [ - "get_conversation" - ] - }, - "ListConversations": { - "methods": [ - "list_conversations" - ] - }, - "UpdateConversation": { - "methods": [ - "update_conversation" - ] - } - } - } - } - }, - "DataStoreService": { - "clients": { - "grpc": { - "libraryClient": "DataStoreServiceClient", - "rpcs": { - "CreateDataStore": { - "methods": [ - "create_data_store" - ] - }, - "DeleteDataStore": { - "methods": [ - "delete_data_store" - ] - }, - "GetDataStore": { - "methods": [ - "get_data_store" - ] - }, - "ListDataStores": { - "methods": [ - "list_data_stores" - ] - }, - "UpdateDataStore": { - "methods": [ - "update_data_store" - ] - } - } - }, - "grpc-async": { - "libraryClient": "DataStoreServiceAsyncClient", - "rpcs": { - "CreateDataStore": { - "methods": [ - "create_data_store" - ] - }, - "DeleteDataStore": { - "methods": [ - "delete_data_store" - ] - }, - "GetDataStore": { - "methods": [ - "get_data_store" - ] - }, - "ListDataStores": { - "methods": [ - "list_data_stores" - ] - }, - "UpdateDataStore": { - "methods": [ - "update_data_store" - ] - } - } - }, - "rest": { - "libraryClient": "DataStoreServiceClient", - "rpcs": { - "CreateDataStore": { - "methods": [ - "create_data_store" - ] - }, - "DeleteDataStore": { - "methods": [ - "delete_data_store" - ] - }, - "GetDataStore": { - "methods": [ - "get_data_store" - ] - }, - "ListDataStores": { - "methods": [ - "list_data_stores" - ] - }, - "UpdateDataStore": { - "methods": [ - "update_data_store" - ] - } - } - } - } - }, - "DocumentService": { - "clients": { - "grpc": { - "libraryClient": "DocumentServiceClient", - "rpcs": { - "CreateDocument": { - "methods": [ - "create_document" - ] - }, - "DeleteDocument": { - "methods": [ - "delete_document" - ] - }, - "GetDocument": { - "methods": [ - "get_document" - ] - }, - "ImportDocuments": { - "methods": [ - "import_documents" - ] - }, - "ListDocuments": { - "methods": [ - "list_documents" - ] - }, - "PurgeDocuments": { - "methods": [ - "purge_documents" - ] - }, - "UpdateDocument": { - "methods": [ - "update_document" - ] - } - } - }, - "grpc-async": { - "libraryClient": "DocumentServiceAsyncClient", - "rpcs": { - "CreateDocument": { - "methods": [ - "create_document" - ] - }, - "DeleteDocument": { - "methods": [ - "delete_document" - ] - }, - "GetDocument": { - "methods": [ - "get_document" - ] - }, - "ImportDocuments": { - "methods": [ - "import_documents" - ] - }, - "ListDocuments": { - "methods": [ - "list_documents" - ] - }, - "PurgeDocuments": { - "methods": [ - "purge_documents" - ] - }, - "UpdateDocument": { - "methods": [ - "update_document" - ] - } - } - }, - "rest": { - "libraryClient": "DocumentServiceClient", - "rpcs": { - "CreateDocument": { - "methods": [ - "create_document" - ] - }, - "DeleteDocument": { - "methods": [ - "delete_document" - ] - }, - "GetDocument": { - "methods": [ - "get_document" - ] - }, - "ImportDocuments": { - "methods": [ - "import_documents" - ] - }, - "ListDocuments": { - "methods": [ - "list_documents" - ] - }, - "PurgeDocuments": { - "methods": [ - "purge_documents" - ] - }, - "UpdateDocument": { - "methods": [ - "update_document" - ] - } - } - } - } - }, - "EngineService": { - "clients": { - "grpc": { - "libraryClient": "EngineServiceClient", - "rpcs": { - "CreateEngine": { - "methods": [ - "create_engine" - ] - }, - "DeleteEngine": { - "methods": [ - "delete_engine" - ] - }, - "GetEngine": { - "methods": [ - "get_engine" - ] - }, - "ListEngines": { - "methods": [ - "list_engines" - ] - }, - "PauseEngine": { - "methods": [ - "pause_engine" - ] - }, - "ResumeEngine": { - "methods": [ - "resume_engine" - ] - }, - "TuneEngine": { - "methods": [ - "tune_engine" - ] - }, - "UpdateEngine": { - "methods": [ - "update_engine" - ] - } - } - }, - "grpc-async": { - "libraryClient": "EngineServiceAsyncClient", - "rpcs": { - "CreateEngine": { - "methods": [ - "create_engine" - ] - }, - "DeleteEngine": { - "methods": [ - "delete_engine" - ] - }, - "GetEngine": { - "methods": [ - "get_engine" - ] - }, - "ListEngines": { - "methods": [ - "list_engines" - ] - }, - "PauseEngine": { - "methods": [ - "pause_engine" - ] - }, - "ResumeEngine": { - "methods": [ - "resume_engine" - ] - }, - "TuneEngine": { - "methods": [ - "tune_engine" - ] - }, - "UpdateEngine": { - "methods": [ - "update_engine" - ] - } - } - }, - "rest": { - "libraryClient": "EngineServiceClient", - "rpcs": { - "CreateEngine": { - "methods": [ - "create_engine" - ] - }, - "DeleteEngine": { - "methods": [ - "delete_engine" - ] - }, - "GetEngine": { - "methods": [ - "get_engine" - ] - }, - "ListEngines": { - "methods": [ - "list_engines" - ] - }, - "PauseEngine": { - "methods": [ - "pause_engine" - ] - }, - "ResumeEngine": { - "methods": [ - "resume_engine" - ] - }, - "TuneEngine": { - "methods": [ - "tune_engine" - ] - }, - "UpdateEngine": { - "methods": [ - "update_engine" - ] - } - } - } - } - }, - "RecommendationService": { - "clients": { - "grpc": { - "libraryClient": "RecommendationServiceClient", - "rpcs": { - "Recommend": { - "methods": [ - "recommend" - ] - } - } - }, - "grpc-async": { - "libraryClient": "RecommendationServiceAsyncClient", - "rpcs": { - "Recommend": { - "methods": [ - "recommend" - ] - } - } - }, - "rest": { - "libraryClient": "RecommendationServiceClient", - "rpcs": { - "Recommend": { - "methods": [ - "recommend" - ] - } - } - } - } - }, - "SchemaService": { - "clients": { - "grpc": { - "libraryClient": "SchemaServiceClient", - "rpcs": { - "CreateSchema": { - "methods": [ - "create_schema" - ] - }, - "DeleteSchema": { - "methods": [ - "delete_schema" - ] - }, - "GetSchema": { - "methods": [ - "get_schema" - ] - }, - "ListSchemas": { - "methods": [ - "list_schemas" - ] - }, - "UpdateSchema": { - "methods": [ - "update_schema" - ] - } - } - }, - "grpc-async": { - "libraryClient": "SchemaServiceAsyncClient", - "rpcs": { - "CreateSchema": { - "methods": [ - "create_schema" - ] - }, - "DeleteSchema": { - "methods": [ - "delete_schema" - ] - }, - "GetSchema": { - "methods": [ - "get_schema" - ] - }, - "ListSchemas": { - "methods": [ - "list_schemas" - ] - }, - "UpdateSchema": { - "methods": [ - "update_schema" - ] - } - } - }, - "rest": { - "libraryClient": "SchemaServiceClient", - "rpcs": { - "CreateSchema": { - "methods": [ - "create_schema" - ] - }, - "DeleteSchema": { - "methods": [ - "delete_schema" - ] - }, - "GetSchema": { - "methods": [ - "get_schema" - ] - }, - "ListSchemas": { - "methods": [ - "list_schemas" - ] - }, - "UpdateSchema": { - "methods": [ - "update_schema" - ] - } - } - } - } - }, - "SearchService": { - "clients": { - "grpc": { - "libraryClient": "SearchServiceClient", - "rpcs": { - "Search": { - "methods": [ - "search" - ] - } - } - }, - "grpc-async": { - "libraryClient": "SearchServiceAsyncClient", - "rpcs": { - "Search": { - "methods": [ - "search" - ] - } - } - }, - "rest": { - "libraryClient": "SearchServiceClient", - "rpcs": { - "Search": { - "methods": [ - "search" - ] - } - } - } - } - }, - "SiteSearchEngineService": { - "clients": { - "grpc": { - "libraryClient": "SiteSearchEngineServiceClient", - "rpcs": { - "RecrawlUris": { - "methods": [ - "recrawl_uris" - ] - } - } - }, - "grpc-async": { - "libraryClient": "SiteSearchEngineServiceAsyncClient", - "rpcs": { - "RecrawlUris": { - "methods": [ - "recrawl_uris" - ] - } - } - }, - "rest": { - "libraryClient": "SiteSearchEngineServiceClient", - "rpcs": { - "RecrawlUris": { - "methods": [ - "recrawl_uris" - ] - } - } - } - } - }, - "UserEventService": { - "clients": { - "grpc": { - "libraryClient": "UserEventServiceClient", - "rpcs": { - "CollectUserEvent": { - "methods": [ - "collect_user_event" - ] - }, - "ImportUserEvents": { - "methods": [ - "import_user_events" - ] - }, - "PurgeUserEvents": { - "methods": [ - "purge_user_events" - ] - }, - "WriteUserEvent": { - "methods": [ - "write_user_event" - ] - } - } - }, - "grpc-async": { - "libraryClient": "UserEventServiceAsyncClient", - "rpcs": { - "CollectUserEvent": { - "methods": [ - "collect_user_event" - ] - }, - "ImportUserEvents": { - "methods": [ - "import_user_events" - ] - }, - "PurgeUserEvents": { - "methods": [ - "purge_user_events" - ] - }, - "WriteUserEvent": { - "methods": [ - "write_user_event" - ] - } - } - }, - "rest": { - "libraryClient": "UserEventServiceClient", - "rpcs": { - "CollectUserEvent": { - "methods": [ - "collect_user_event" - ] - }, - "ImportUserEvents": { - "methods": [ - "import_user_events" - ] - }, - "PurgeUserEvents": { - "methods": [ - "purge_user_events" - ] - }, - "WriteUserEvent": { - "methods": [ - "write_user_event" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/gapic_version.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/gapic_version.py deleted file mode 100644 index 360a0d13ebdd..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/py.typed b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/py.typed deleted file mode 100644 index 2ff6437cf473..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-discoveryengine package uses inline types. diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/__init__.py deleted file mode 100644 index 89a37dc92c5a..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/__init__.py deleted file mode 100644 index 440cbfb40963..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import CompletionServiceClient -from .async_client import CompletionServiceAsyncClient - -__all__ = ( - 'CompletionServiceClient', - 'CompletionServiceAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/async_client.py deleted file mode 100644 index fc3be4cb3409..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/async_client.py +++ /dev/null @@ -1,386 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.discoveryengine_v1alpha import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.discoveryengine_v1alpha.types import completion_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport -from .client import CompletionServiceClient - - -class CompletionServiceAsyncClient: - """Service for Auto-Completion.""" - - _client: CompletionServiceClient - - DEFAULT_ENDPOINT = CompletionServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = CompletionServiceClient.DEFAULT_MTLS_ENDPOINT - - data_store_path = staticmethod(CompletionServiceClient.data_store_path) - parse_data_store_path = staticmethod(CompletionServiceClient.parse_data_store_path) - common_billing_account_path = staticmethod(CompletionServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(CompletionServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(CompletionServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(CompletionServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(CompletionServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(CompletionServiceClient.parse_common_organization_path) - common_project_path = staticmethod(CompletionServiceClient.common_project_path) - parse_common_project_path = staticmethod(CompletionServiceClient.parse_common_project_path) - common_location_path = staticmethod(CompletionServiceClient.common_location_path) - parse_common_location_path = staticmethod(CompletionServiceClient.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: - CompletionServiceAsyncClient: The constructed client. - """ - return CompletionServiceClient.from_service_account_info.__func__(CompletionServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceAsyncClient: The constructed client. - """ - return CompletionServiceClient.from_service_account_file.__func__(CompletionServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return CompletionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> CompletionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CompletionServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(CompletionServiceClient).get_transport_class, type(CompletionServiceClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, CompletionServiceTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the completion 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 (Union[str, ~.CompletionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = CompletionServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def complete_query(self, - request: Optional[Union[completion_service.CompleteQueryRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> completion_service.CompleteQueryResponse: - r"""Completes the specified user input with keyword - suggestions. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - async def sample_complete_query(): - # Create a client - client = discoveryengine_v1alpha.CompletionServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.CompleteQueryRequest( - data_store="data_store_value", - query="query_value", - ) - - # Make the request - response = await client.complete_query(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.CompleteQueryRequest, dict]]): - The request object. Request message for - [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1alpha.CompletionService.CompleteQuery] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1alpha.types.CompleteQueryResponse: - Response message for - [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1alpha.CompletionService.CompleteQuery] - method. - - """ - # Create or coerce a protobuf request object. - request = completion_service.CompleteQueryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.complete_query, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("data_store", request.data_store), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "CompletionServiceAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "CompletionServiceAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/client.py deleted file mode 100644 index 0a1d4409407e..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/client.py +++ /dev/null @@ -1,594 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.discoveryengine_v1alpha import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.discoveryengine_v1alpha.types import completion_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import CompletionServiceGrpcTransport -from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport -from .transports.rest import CompletionServiceRestTransport - - -class CompletionServiceClientMeta(type): - """Metaclass for the CompletionService 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[CompletionServiceTransport]] - _transport_registry["grpc"] = CompletionServiceGrpcTransport - _transport_registry["grpc_asyncio"] = CompletionServiceGrpcAsyncIOTransport - _transport_registry["rest"] = CompletionServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[CompletionServiceTransport]: - """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 CompletionServiceClient(metaclass=CompletionServiceClientMeta): - """Service for Auto-Completion.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceClient: 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: - CompletionServiceClient: 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) -> CompletionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CompletionServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def data_store_path(project: str,location: str,data_store: str,) -> str: - """Returns a fully-qualified data_store string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) - - @staticmethod - def parse_data_store_path(path: str) -> Dict[str,str]: - """Parses a data_store path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, CompletionServiceTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the completion 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 (Union[str, CompletionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, CompletionServiceTransport): - # transport is a CompletionServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def complete_query(self, - request: Optional[Union[completion_service.CompleteQueryRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> completion_service.CompleteQueryResponse: - r"""Completes the specified user input with keyword - suggestions. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - def sample_complete_query(): - # Create a client - client = discoveryengine_v1alpha.CompletionServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.CompleteQueryRequest( - data_store="data_store_value", - query="query_value", - ) - - # Make the request - response = client.complete_query(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1alpha.types.CompleteQueryRequest, dict]): - The request object. Request message for - [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1alpha.CompletionService.CompleteQuery] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1alpha.types.CompleteQueryResponse: - Response message for - [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1alpha.CompletionService.CompleteQuery] - method. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a completion_service.CompleteQueryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, completion_service.CompleteQueryRequest): - request = completion_service.CompleteQueryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.complete_query] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("data_store", request.data_store), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "CompletionServiceClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - - - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "CompletionServiceClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/__init__.py deleted file mode 100644 index f32ad4419b13..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import CompletionServiceTransport -from .grpc import CompletionServiceGrpcTransport -from .grpc_asyncio import CompletionServiceGrpcAsyncIOTransport -from .rest import CompletionServiceRestTransport -from .rest import CompletionServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] -_transport_registry['grpc'] = CompletionServiceGrpcTransport -_transport_registry['grpc_asyncio'] = CompletionServiceGrpcAsyncIOTransport -_transport_registry['rest'] = CompletionServiceRestTransport - -__all__ = ( - 'CompletionServiceTransport', - 'CompletionServiceGrpcTransport', - 'CompletionServiceGrpcAsyncIOTransport', - 'CompletionServiceRestTransport', - 'CompletionServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/base.py deleted file mode 100644 index e4f66cbdc4d3..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/base.py +++ /dev/null @@ -1,168 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.discoveryengine_v1alpha import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.discoveryengine_v1alpha.types import completion_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class CompletionServiceTransport(abc.ABC): - """Abstract transport class for CompletionService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'discoveryengine.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.complete_query: gapic_v1.method.wrap_method( - self.complete_query, - 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 complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - Union[ - completion_service.CompleteQueryResponse, - Awaitable[completion_service.CompleteQueryResponse] - ]]: - 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 kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'CompletionServiceTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/grpc.py deleted file mode 100644 index 01af23230592..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/grpc.py +++ /dev/null @@ -1,303 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.discoveryengine_v1alpha.types import completion_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO - - -class CompletionServiceGrpcTransport(CompletionServiceTransport): - """gRPC backend transport for CompletionService. - - Service for Auto-Completion. - - 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - completion_service.CompleteQueryResponse]: - r"""Return a callable for the complete query method over gRPC. - - Completes the specified user input with keyword - suggestions. - - Returns: - Callable[[~.CompleteQueryRequest], - ~.CompleteQueryResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'complete_query' not in self._stubs: - self._stubs['complete_query'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.CompletionService/CompleteQuery', - request_serializer=completion_service.CompleteQueryRequest.serialize, - response_deserializer=completion_service.CompleteQueryResponse.deserialize, - ) - return self._stubs['complete_query'] - - def close(self): - self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'CompletionServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/grpc_asyncio.py deleted file mode 100644 index 2b7eea04ea61..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,302 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.discoveryengine_v1alpha.types import completion_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import CompletionServiceGrpcTransport - - -class CompletionServiceGrpcAsyncIOTransport(CompletionServiceTransport): - """gRPC AsyncIO backend transport for CompletionService. - - Service for Auto-Completion. - - 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - Awaitable[completion_service.CompleteQueryResponse]]: - r"""Return a callable for the complete query method over gRPC. - - Completes the specified user input with keyword - suggestions. - - Returns: - Callable[[~.CompleteQueryRequest], - Awaitable[~.CompleteQueryResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'complete_query' not in self._stubs: - self._stubs['complete_query'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.CompletionService/CompleteQuery', - request_serializer=completion_service.CompleteQueryRequest.serialize, - response_deserializer=completion_service.CompleteQueryResponse.deserialize, - ) - return self._stubs['complete_query'] - - def close(self): - return self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - -__all__ = ( - 'CompletionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/rest.py deleted file mode 100644 index 70ffa099b61f..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/completion_service/transports/rest.py +++ /dev/null @@ -1,566 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.cloud.location import locations_pb2 # type: ignore -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.discoveryengine_v1alpha.types import completion_service -from google.longrunning import operations_pb2 # type: ignore - -from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class CompletionServiceRestInterceptor: - """Interceptor for CompletionService. - - 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 CompletionServiceRestTransport. - - .. code-block:: python - class MyCustomCompletionServiceInterceptor(CompletionServiceRestInterceptor): - def pre_complete_query(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_complete_query(self, response): - logging.log(f"Received response: {response}") - return response - - transport = CompletionServiceRestTransport(interceptor=MyCustomCompletionServiceInterceptor()) - client = CompletionServiceClient(transport=transport) - - - """ - def pre_complete_query(self, request: completion_service.CompleteQueryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[completion_service.CompleteQueryRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for complete_query - - Override in a subclass to manipulate the request or metadata - before they are sent to the CompletionService server. - """ - return request, metadata - - def post_complete_query(self, response: completion_service.CompleteQueryResponse) -> completion_service.CompleteQueryResponse: - """Post-rpc interceptor for complete_query - - Override in a subclass to manipulate the response - after it is returned by the CompletionService server but before - it is returned to user code. - """ - return response - - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the CompletionService 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 CompletionService server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the CompletionService 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 CompletionService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class CompletionServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: CompletionServiceRestInterceptor - - -class CompletionServiceRestTransport(CompletionServiceTransport): - """REST backend transport for CompletionService. - - Service for Auto-Completion. - - 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 = 'discoveryengine.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[CompletionServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or CompletionServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _CompleteQuery(CompletionServiceRestStub): - def __hash__(self): - return hash("CompleteQuery") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "query" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: completion_service.CompleteQueryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> completion_service.CompleteQueryResponse: - r"""Call the complete query method over HTTP. - - Args: - request (~.completion_service.CompleteQueryRequest): - The request object. Request message for - [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1alpha.CompletionService.CompleteQuery] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.completion_service.CompleteQueryResponse: - Response message for - [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1alpha.CompletionService.CompleteQuery] - method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{data_store=projects/*/locations/*/dataStores/*}:completeQuery', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{data_store=projects/*/locations/*/collections/*/dataStores/*}:completeQuery', - }, - ] - request, metadata = self._interceptor.pre_complete_query(request, metadata) - pb_request = completion_service.CompleteQueryRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = completion_service.CompleteQueryResponse() - pb_resp = completion_service.CompleteQueryResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_complete_query(resp) - return resp - - @property - def complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - completion_service.CompleteQueryResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CompleteQuery(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(CompletionServiceRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(CompletionServiceRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'CompletionServiceRestTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/__init__.py deleted file mode 100644 index 4bf42b241a8b..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import ConversationalSearchServiceClient -from .async_client import ConversationalSearchServiceAsyncClient - -__all__ = ( - 'ConversationalSearchServiceClient', - 'ConversationalSearchServiceAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/async_client.py deleted file mode 100644 index f0be82ed1b20..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/async_client.py +++ /dev/null @@ -1,971 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.discoveryengine_v1alpha import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.discoveryengine_v1alpha.services.conversational_search_service import pagers -from google.cloud.discoveryengine_v1alpha.types import conversation -from google.cloud.discoveryengine_v1alpha.types import conversation as gcd_conversation -from google.cloud.discoveryengine_v1alpha.types import conversational_search_service -from google.cloud.discoveryengine_v1alpha.types import search_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import ConversationalSearchServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ConversationalSearchServiceGrpcAsyncIOTransport -from .client import ConversationalSearchServiceClient - - -class ConversationalSearchServiceAsyncClient: - """Service for conversational search.""" - - _client: ConversationalSearchServiceClient - - DEFAULT_ENDPOINT = ConversationalSearchServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ConversationalSearchServiceClient.DEFAULT_MTLS_ENDPOINT - - conversation_path = staticmethod(ConversationalSearchServiceClient.conversation_path) - parse_conversation_path = staticmethod(ConversationalSearchServiceClient.parse_conversation_path) - data_store_path = staticmethod(ConversationalSearchServiceClient.data_store_path) - parse_data_store_path = staticmethod(ConversationalSearchServiceClient.parse_data_store_path) - document_path = staticmethod(ConversationalSearchServiceClient.document_path) - parse_document_path = staticmethod(ConversationalSearchServiceClient.parse_document_path) - serving_config_path = staticmethod(ConversationalSearchServiceClient.serving_config_path) - parse_serving_config_path = staticmethod(ConversationalSearchServiceClient.parse_serving_config_path) - common_billing_account_path = staticmethod(ConversationalSearchServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ConversationalSearchServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ConversationalSearchServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(ConversationalSearchServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(ConversationalSearchServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(ConversationalSearchServiceClient.parse_common_organization_path) - common_project_path = staticmethod(ConversationalSearchServiceClient.common_project_path) - parse_common_project_path = staticmethod(ConversationalSearchServiceClient.parse_common_project_path) - common_location_path = staticmethod(ConversationalSearchServiceClient.common_location_path) - parse_common_location_path = staticmethod(ConversationalSearchServiceClient.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: - ConversationalSearchServiceAsyncClient: The constructed client. - """ - return ConversationalSearchServiceClient.from_service_account_info.__func__(ConversationalSearchServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ConversationalSearchServiceAsyncClient: The constructed client. - """ - return ConversationalSearchServiceClient.from_service_account_file.__func__(ConversationalSearchServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return ConversationalSearchServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ConversationalSearchServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ConversationalSearchServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ConversationalSearchServiceClient).get_transport_class, type(ConversationalSearchServiceClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ConversationalSearchServiceTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the conversational search 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 (Union[str, ~.ConversationalSearchServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = ConversationalSearchServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def converse_conversation(self, - request: Optional[Union[conversational_search_service.ConverseConversationRequest, dict]] = None, - *, - name: Optional[str] = None, - query: Optional[conversation.TextInput] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversational_search_service.ConverseConversationResponse: - r"""Converses 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 discoveryengine_v1alpha - - async def sample_converse_conversation(): - # Create a client - client = discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.ConverseConversationRequest( - name="name_value", - ) - - # Make the request - response = await client.converse_conversation(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.ConverseConversationRequest, dict]]): - The request object. Request message for - [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1alpha.ConversationalSearchService.ConverseConversation] - method. - name (:class:`str`): - Required. The resource name of the Conversation to get. - Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}``. - Use - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/-`` - to activate auto session mode, which automatically - creates a new conversation inside a ConverseConversation - session. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - query (:class:`google.cloud.discoveryengine_v1alpha.types.TextInput`): - Required. Current user input. - This corresponds to the ``query`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1alpha.types.ConverseConversationResponse: - Response message for - [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1alpha.ConversationalSearchService.ConverseConversation] - method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, query]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = conversational_search_service.ConverseConversationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if query is not None: - request.query = query - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.converse_conversation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_conversation(self, - request: Optional[Union[conversational_search_service.CreateConversationRequest, dict]] = None, - *, - parent: Optional[str] = None, - conversation: Optional[gcd_conversation.Conversation] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_conversation.Conversation: - r"""Creates a Conversation. - - If the - [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] - to create already exists, an ALREADY_EXISTS error is returned. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - async def sample_create_conversation(): - # Create a client - client = discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.CreateConversationRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_conversation(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.CreateConversationRequest, dict]]): - The request object. Request for CreateConversation - method. - parent (:class:`str`): - Required. Full resource name of parent data store. - Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - conversation (:class:`google.cloud.discoveryengine_v1alpha.types.Conversation`): - Required. The conversation to create. - This corresponds to the ``conversation`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1alpha.types.Conversation: - External conversation proto - definition. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, conversation]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = conversational_search_service.CreateConversationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if conversation is not None: - request.conversation = conversation - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_conversation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_conversation(self, - request: Optional[Union[conversational_search_service.DeleteConversationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a Conversation. - - If the - [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] - to delete does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - async def sample_delete_conversation(): - # Create a client - client = discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.DeleteConversationRequest( - name="name_value", - ) - - # Make the request - await client.delete_conversation(request=request) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.DeleteConversationRequest, dict]]): - The request object. Request for DeleteConversation - method. - name (:class:`str`): - Required. The resource name of the Conversation to - delete. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = conversational_search_service.DeleteConversationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_conversation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def update_conversation(self, - request: Optional[Union[conversational_search_service.UpdateConversationRequest, dict]] = None, - *, - conversation: Optional[gcd_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, str]] = (), - ) -> gcd_conversation.Conversation: - r"""Updates a Conversation. - - [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] - action type cannot be changed. If the - [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] - to update does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - async def sample_update_conversation(): - # Create a client - client = discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.UpdateConversationRequest( - ) - - # Make the request - response = await client.update_conversation(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.UpdateConversationRequest, dict]]): - The request object. Request for UpdateConversation - method. - conversation (:class:`google.cloud.discoveryengine_v1alpha.types.Conversation`): - Required. The Conversation to update. - 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`): - Indicates which fields in the provided - [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] - to update. The following are NOT supported: - - - [conversation.name][] - - If not set or empty, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1alpha.types.Conversation: - External conversation proto - definition. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([conversation, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = conversational_search_service.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 = gapic_v1.method_async.wrap_method( - self._client._transport.update_conversation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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), - )), - ) - - # 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[conversational_search_service.GetConversationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation.Conversation: - r"""Gets 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 discoveryengine_v1alpha - - async def sample_get_conversation(): - # Create a client - client = discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.GetConversationRequest( - name="name_value", - ) - - # Make the request - response = await client.get_conversation(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.GetConversationRequest, dict]]): - The request object. Request for GetConversation method. - name (:class:`str`): - Required. The resource name of the Conversation to get. - Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1alpha.types.Conversation: - External conversation proto - definition. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = conversational_search_service.GetConversationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_conversation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_conversations(self, - request: Optional[Union[conversational_search_service.ListConversationsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListConversationsAsyncPager: - r"""Lists all Conversations by their parent - [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - async def sample_list_conversations(): - # Create a client - client = discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.ListConversationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversations(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.ListConversationsRequest, dict]]): - The request object. Request for ListConversations method. - parent (:class:`str`): - Required. The data store resource name. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1alpha.services.conversational_search_service.pagers.ListConversationsAsyncPager: - Response for ListConversations - method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = conversational_search_service.ListConversationsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_conversations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListConversationsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "ConversationalSearchServiceAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "ConversationalSearchServiceAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/client.py deleted file mode 100644 index ede7ea5403a0..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/client.py +++ /dev/null @@ -1,1205 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.discoveryengine_v1alpha import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.discoveryengine_v1alpha.services.conversational_search_service import pagers -from google.cloud.discoveryengine_v1alpha.types import conversation -from google.cloud.discoveryengine_v1alpha.types import conversation as gcd_conversation -from google.cloud.discoveryengine_v1alpha.types import conversational_search_service -from google.cloud.discoveryengine_v1alpha.types import search_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import ConversationalSearchServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ConversationalSearchServiceGrpcTransport -from .transports.grpc_asyncio import ConversationalSearchServiceGrpcAsyncIOTransport -from .transports.rest import ConversationalSearchServiceRestTransport - - -class ConversationalSearchServiceClientMeta(type): - """Metaclass for the ConversationalSearchService 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[ConversationalSearchServiceTransport]] - _transport_registry["grpc"] = ConversationalSearchServiceGrpcTransport - _transport_registry["grpc_asyncio"] = ConversationalSearchServiceGrpcAsyncIOTransport - _transport_registry["rest"] = ConversationalSearchServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[ConversationalSearchServiceTransport]: - """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 ConversationalSearchServiceClient(metaclass=ConversationalSearchServiceClientMeta): - """Service for conversational search.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ConversationalSearchServiceClient: 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: - ConversationalSearchServiceClient: 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) -> ConversationalSearchServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ConversationalSearchServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def conversation_path(project: str,location: str,data_store: str,conversation: str,) -> str: - """Returns a fully-qualified conversation string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}/conversations/{conversation}".format(project=project, location=location, data_store=data_store, conversation=conversation, ) - - @staticmethod - def parse_conversation_path(path: str) -> Dict[str,str]: - """Parses a conversation path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/conversations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def data_store_path(project: str,location: str,data_store: str,) -> str: - """Returns a fully-qualified data_store string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) - - @staticmethod - def parse_data_store_path(path: str) -> Dict[str,str]: - """Parses a data_store path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def document_path(project: str,location: str,data_store: str,branch: str,document: str,) -> str: - """Returns a fully-qualified document string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) - - @staticmethod - def parse_document_path(path: str) -> Dict[str,str]: - """Parses a document path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)/documents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def serving_config_path(project: str,location: str,data_store: str,serving_config: str,) -> str: - """Returns a fully-qualified serving_config string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}/servingConfigs/{serving_config}".format(project=project, location=location, data_store=data_store, serving_config=serving_config, ) - - @staticmethod - def parse_serving_config_path(path: str) -> Dict[str,str]: - """Parses a serving_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/servingConfigs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ConversationalSearchServiceTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the conversational search 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 (Union[str, ConversationalSearchServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ConversationalSearchServiceTransport): - # transport is a ConversationalSearchServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def converse_conversation(self, - request: Optional[Union[conversational_search_service.ConverseConversationRequest, dict]] = None, - *, - name: Optional[str] = None, - query: Optional[conversation.TextInput] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversational_search_service.ConverseConversationResponse: - r"""Converses 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 discoveryengine_v1alpha - - def sample_converse_conversation(): - # Create a client - client = discoveryengine_v1alpha.ConversationalSearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.ConverseConversationRequest( - name="name_value", - ) - - # Make the request - response = client.converse_conversation(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1alpha.types.ConverseConversationRequest, dict]): - The request object. Request message for - [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1alpha.ConversationalSearchService.ConverseConversation] - method. - name (str): - Required. The resource name of the Conversation to get. - Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}``. - Use - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/-`` - to activate auto session mode, which automatically - creates a new conversation inside a ConverseConversation - session. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - query (google.cloud.discoveryengine_v1alpha.types.TextInput): - Required. Current user input. - This corresponds to the ``query`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1alpha.types.ConverseConversationResponse: - Response message for - [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1alpha.ConversationalSearchService.ConverseConversation] - method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, query]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a conversational_search_service.ConverseConversationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, conversational_search_service.ConverseConversationRequest): - request = conversational_search_service.ConverseConversationRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if query is not None: - request.query = query - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.converse_conversation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_conversation(self, - request: Optional[Union[conversational_search_service.CreateConversationRequest, dict]] = None, - *, - parent: Optional[str] = None, - conversation: Optional[gcd_conversation.Conversation] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_conversation.Conversation: - r"""Creates a Conversation. - - If the - [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] - to create already exists, an ALREADY_EXISTS error is returned. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - def sample_create_conversation(): - # Create a client - client = discoveryengine_v1alpha.ConversationalSearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.CreateConversationRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_conversation(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1alpha.types.CreateConversationRequest, dict]): - The request object. Request for CreateConversation - method. - parent (str): - Required. Full resource name of parent data store. - Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - conversation (google.cloud.discoveryengine_v1alpha.types.Conversation): - Required. The conversation to create. - This corresponds to the ``conversation`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1alpha.types.Conversation: - External conversation proto - definition. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, conversation]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a conversational_search_service.CreateConversationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, conversational_search_service.CreateConversationRequest): - request = conversational_search_service.CreateConversationRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if conversation is not None: - request.conversation = conversation - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_conversation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_conversation(self, - request: Optional[Union[conversational_search_service.DeleteConversationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a Conversation. - - If the - [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] - to delete does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - def sample_delete_conversation(): - # Create a client - client = discoveryengine_v1alpha.ConversationalSearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.DeleteConversationRequest( - name="name_value", - ) - - # Make the request - client.delete_conversation(request=request) - - Args: - request (Union[google.cloud.discoveryengine_v1alpha.types.DeleteConversationRequest, dict]): - The request object. Request for DeleteConversation - method. - name (str): - Required. The resource name of the Conversation to - delete. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a conversational_search_service.DeleteConversationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, conversational_search_service.DeleteConversationRequest): - request = conversational_search_service.DeleteConversationRequest(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_conversation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def update_conversation(self, - request: Optional[Union[conversational_search_service.UpdateConversationRequest, dict]] = None, - *, - conversation: Optional[gcd_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, str]] = (), - ) -> gcd_conversation.Conversation: - r"""Updates a Conversation. - - [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] - action type cannot be changed. If the - [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] - to update does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - def sample_update_conversation(): - # Create a client - client = discoveryengine_v1alpha.ConversationalSearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.UpdateConversationRequest( - ) - - # Make the request - response = client.update_conversation(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1alpha.types.UpdateConversationRequest, dict]): - The request object. Request for UpdateConversation - method. - conversation (google.cloud.discoveryengine_v1alpha.types.Conversation): - Required. The Conversation to update. - 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): - Indicates which fields in the provided - [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] - to update. The following are NOT supported: - - - [conversation.name][] - - If not set or empty, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1alpha.types.Conversation: - External conversation proto - definition. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([conversation, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a conversational_search_service.UpdateConversationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, conversational_search_service.UpdateConversationRequest): - request = conversational_search_service.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), - )), - ) - - # 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[conversational_search_service.GetConversationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation.Conversation: - r"""Gets 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 discoveryengine_v1alpha - - def sample_get_conversation(): - # Create a client - client = discoveryengine_v1alpha.ConversationalSearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.GetConversationRequest( - name="name_value", - ) - - # Make the request - response = client.get_conversation(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1alpha.types.GetConversationRequest, dict]): - The request object. Request for GetConversation method. - name (str): - Required. The resource name of the Conversation to get. - Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1alpha.types.Conversation: - External conversation proto - definition. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a conversational_search_service.GetConversationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, conversational_search_service.GetConversationRequest): - request = conversational_search_service.GetConversationRequest(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_conversation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_conversations(self, - request: Optional[Union[conversational_search_service.ListConversationsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListConversationsPager: - r"""Lists all Conversations by their parent - [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - def sample_list_conversations(): - # Create a client - client = discoveryengine_v1alpha.ConversationalSearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.ListConversationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversations(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1alpha.types.ListConversationsRequest, dict]): - The request object. Request for ListConversations method. - parent (str): - Required. The data store resource name. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1alpha.services.conversational_search_service.pagers.ListConversationsPager: - Response for ListConversations - method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a conversational_search_service.ListConversationsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, conversational_search_service.ListConversationsRequest): - request = conversational_search_service.ListConversationsRequest(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_conversations] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListConversationsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "ConversationalSearchServiceClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - - - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "ConversationalSearchServiceClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/pagers.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/pagers.py deleted file mode 100644 index f67122114630..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.discoveryengine_v1alpha.types import conversation -from google.cloud.discoveryengine_v1alpha.types import conversational_search_service - - -class ListConversationsPager: - """A pager for iterating through ``list_conversations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.discoveryengine_v1alpha.types.ListConversationsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``conversations`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListConversations`` requests and continue to iterate - through the ``conversations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.discoveryengine_v1alpha.types.ListConversationsResponse` - 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[..., conversational_search_service.ListConversationsResponse], - request: conversational_search_service.ListConversationsRequest, - response: conversational_search_service.ListConversationsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.discoveryengine_v1alpha.types.ListConversationsRequest): - The initial request object. - response (google.cloud.discoveryengine_v1alpha.types.ListConversationsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = conversational_search_service.ListConversationsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[conversational_search_service.ListConversationsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[conversation.Conversation]: - for page in self.pages: - yield from page.conversations - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListConversationsAsyncPager: - """A pager for iterating through ``list_conversations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.discoveryengine_v1alpha.types.ListConversationsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``conversations`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListConversations`` requests and continue to iterate - through the ``conversations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.discoveryengine_v1alpha.types.ListConversationsResponse` - 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[conversational_search_service.ListConversationsResponse]], - request: conversational_search_service.ListConversationsRequest, - response: conversational_search_service.ListConversationsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.discoveryengine_v1alpha.types.ListConversationsRequest): - The initial request object. - response (google.cloud.discoveryengine_v1alpha.types.ListConversationsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = conversational_search_service.ListConversationsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[conversational_search_service.ListConversationsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[conversation.Conversation]: - async def async_generator(): - async for page in self.pages: - for response in page.conversations: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/__init__.py deleted file mode 100644 index f49b63e4b6cd..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import ConversationalSearchServiceTransport -from .grpc import ConversationalSearchServiceGrpcTransport -from .grpc_asyncio import ConversationalSearchServiceGrpcAsyncIOTransport -from .rest import ConversationalSearchServiceRestTransport -from .rest import ConversationalSearchServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ConversationalSearchServiceTransport]] -_transport_registry['grpc'] = ConversationalSearchServiceGrpcTransport -_transport_registry['grpc_asyncio'] = ConversationalSearchServiceGrpcAsyncIOTransport -_transport_registry['rest'] = ConversationalSearchServiceRestTransport - -__all__ = ( - 'ConversationalSearchServiceTransport', - 'ConversationalSearchServiceGrpcTransport', - 'ConversationalSearchServiceGrpcAsyncIOTransport', - 'ConversationalSearchServiceRestTransport', - 'ConversationalSearchServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/base.py deleted file mode 100644 index 6de3058bf8e2..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/base.py +++ /dev/null @@ -1,241 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.discoveryengine_v1alpha import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.discoveryengine_v1alpha.types import conversation -from google.cloud.discoveryengine_v1alpha.types import conversation as gcd_conversation -from google.cloud.discoveryengine_v1alpha.types import conversational_search_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class ConversationalSearchServiceTransport(abc.ABC): - """Abstract transport class for ConversationalSearchService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'discoveryengine.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.converse_conversation: gapic_v1.method.wrap_method( - self.converse_conversation, - default_timeout=None, - client_info=client_info, - ), - self.create_conversation: gapic_v1.method.wrap_method( - self.create_conversation, - default_timeout=None, - client_info=client_info, - ), - self.delete_conversation: gapic_v1.method.wrap_method( - self.delete_conversation, - 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, - client_info=client_info, - ), - self.list_conversations: gapic_v1.method.wrap_method( - self.list_conversations, - 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 converse_conversation(self) -> Callable[ - [conversational_search_service.ConverseConversationRequest], - Union[ - conversational_search_service.ConverseConversationResponse, - Awaitable[conversational_search_service.ConverseConversationResponse] - ]]: - raise NotImplementedError() - - @property - def create_conversation(self) -> Callable[ - [conversational_search_service.CreateConversationRequest], - Union[ - gcd_conversation.Conversation, - Awaitable[gcd_conversation.Conversation] - ]]: - raise NotImplementedError() - - @property - def delete_conversation(self) -> Callable[ - [conversational_search_service.DeleteConversationRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def update_conversation(self) -> Callable[ - [conversational_search_service.UpdateConversationRequest], - Union[ - gcd_conversation.Conversation, - Awaitable[gcd_conversation.Conversation] - ]]: - raise NotImplementedError() - - @property - def get_conversation(self) -> Callable[ - [conversational_search_service.GetConversationRequest], - Union[ - conversation.Conversation, - Awaitable[conversation.Conversation] - ]]: - raise NotImplementedError() - - @property - def list_conversations(self) -> Callable[ - [conversational_search_service.ListConversationsRequest], - Union[ - conversational_search_service.ListConversationsResponse, - Awaitable[conversational_search_service.ListConversationsResponse] - ]]: - 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 kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ConversationalSearchServiceTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/grpc.py deleted file mode 100644 index ac7ac7baaceb..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/grpc.py +++ /dev/null @@ -1,449 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.discoveryengine_v1alpha.types import conversation -from google.cloud.discoveryengine_v1alpha.types import conversation as gcd_conversation -from google.cloud.discoveryengine_v1alpha.types import conversational_search_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import ConversationalSearchServiceTransport, DEFAULT_CLIENT_INFO - - -class ConversationalSearchServiceGrpcTransport(ConversationalSearchServiceTransport): - """gRPC backend transport for ConversationalSearchService. - - Service for conversational search. - - 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def converse_conversation(self) -> Callable[ - [conversational_search_service.ConverseConversationRequest], - conversational_search_service.ConverseConversationResponse]: - r"""Return a callable for the converse conversation method over gRPC. - - Converses a conversation. - - Returns: - Callable[[~.ConverseConversationRequest], - ~.ConverseConversationResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'converse_conversation' not in self._stubs: - self._stubs['converse_conversation'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.ConversationalSearchService/ConverseConversation', - request_serializer=conversational_search_service.ConverseConversationRequest.serialize, - response_deserializer=conversational_search_service.ConverseConversationResponse.deserialize, - ) - return self._stubs['converse_conversation'] - - @property - def create_conversation(self) -> Callable[ - [conversational_search_service.CreateConversationRequest], - gcd_conversation.Conversation]: - r"""Return a callable for the create conversation method over gRPC. - - Creates a Conversation. - - If the - [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] - to create already exists, an ALREADY_EXISTS error is returned. - - Returns: - Callable[[~.CreateConversationRequest], - ~.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 'create_conversation' not in self._stubs: - self._stubs['create_conversation'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.ConversationalSearchService/CreateConversation', - request_serializer=conversational_search_service.CreateConversationRequest.serialize, - response_deserializer=gcd_conversation.Conversation.deserialize, - ) - return self._stubs['create_conversation'] - - @property - def delete_conversation(self) -> Callable[ - [conversational_search_service.DeleteConversationRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete conversation method over gRPC. - - Deletes a Conversation. - - If the - [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] - to delete does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.DeleteConversationRequest], - ~.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_conversation' not in self._stubs: - self._stubs['delete_conversation'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.ConversationalSearchService/DeleteConversation', - request_serializer=conversational_search_service.DeleteConversationRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_conversation'] - - @property - def update_conversation(self) -> Callable[ - [conversational_search_service.UpdateConversationRequest], - gcd_conversation.Conversation]: - r"""Return a callable for the update conversation method over gRPC. - - Updates a Conversation. - - [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] - action type cannot be changed. If the - [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] - to update does not exist, a NOT_FOUND error is returned. - - 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.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.ConversationalSearchService/UpdateConversation', - request_serializer=conversational_search_service.UpdateConversationRequest.serialize, - response_deserializer=gcd_conversation.Conversation.deserialize, - ) - return self._stubs['update_conversation'] - - @property - def get_conversation(self) -> Callable[ - [conversational_search_service.GetConversationRequest], - conversation.Conversation]: - r"""Return a callable for the get conversation method over gRPC. - - Gets a Conversation. - - Returns: - Callable[[~.GetConversationRequest], - ~.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 'get_conversation' not in self._stubs: - self._stubs['get_conversation'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.ConversationalSearchService/GetConversation', - request_serializer=conversational_search_service.GetConversationRequest.serialize, - response_deserializer=conversation.Conversation.deserialize, - ) - return self._stubs['get_conversation'] - - @property - def list_conversations(self) -> Callable[ - [conversational_search_service.ListConversationsRequest], - conversational_search_service.ListConversationsResponse]: - r"""Return a callable for the list conversations method over gRPC. - - Lists all Conversations by their parent - [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]. - - Returns: - Callable[[~.ListConversationsRequest], - ~.ListConversationsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_conversations' not in self._stubs: - self._stubs['list_conversations'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.ConversationalSearchService/ListConversations', - request_serializer=conversational_search_service.ListConversationsRequest.serialize, - response_deserializer=conversational_search_service.ListConversationsResponse.deserialize, - ) - return self._stubs['list_conversations'] - - def close(self): - self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ConversationalSearchServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/grpc_asyncio.py deleted file mode 100644 index 5e84d9e5019c..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,448 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.discoveryengine_v1alpha.types import conversation -from google.cloud.discoveryengine_v1alpha.types import conversation as gcd_conversation -from google.cloud.discoveryengine_v1alpha.types import conversational_search_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import ConversationalSearchServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import ConversationalSearchServiceGrpcTransport - - -class ConversationalSearchServiceGrpcAsyncIOTransport(ConversationalSearchServiceTransport): - """gRPC AsyncIO backend transport for ConversationalSearchService. - - Service for conversational search. - - 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def converse_conversation(self) -> Callable[ - [conversational_search_service.ConverseConversationRequest], - Awaitable[conversational_search_service.ConverseConversationResponse]]: - r"""Return a callable for the converse conversation method over gRPC. - - Converses a conversation. - - Returns: - Callable[[~.ConverseConversationRequest], - Awaitable[~.ConverseConversationResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'converse_conversation' not in self._stubs: - self._stubs['converse_conversation'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.ConversationalSearchService/ConverseConversation', - request_serializer=conversational_search_service.ConverseConversationRequest.serialize, - response_deserializer=conversational_search_service.ConverseConversationResponse.deserialize, - ) - return self._stubs['converse_conversation'] - - @property - def create_conversation(self) -> Callable[ - [conversational_search_service.CreateConversationRequest], - Awaitable[gcd_conversation.Conversation]]: - r"""Return a callable for the create conversation method over gRPC. - - Creates a Conversation. - - If the - [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] - to create already exists, an ALREADY_EXISTS error is returned. - - Returns: - Callable[[~.CreateConversationRequest], - 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 'create_conversation' not in self._stubs: - self._stubs['create_conversation'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.ConversationalSearchService/CreateConversation', - request_serializer=conversational_search_service.CreateConversationRequest.serialize, - response_deserializer=gcd_conversation.Conversation.deserialize, - ) - return self._stubs['create_conversation'] - - @property - def delete_conversation(self) -> Callable[ - [conversational_search_service.DeleteConversationRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete conversation method over gRPC. - - Deletes a Conversation. - - If the - [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] - to delete does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.DeleteConversationRequest], - 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_conversation' not in self._stubs: - self._stubs['delete_conversation'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.ConversationalSearchService/DeleteConversation', - request_serializer=conversational_search_service.DeleteConversationRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_conversation'] - - @property - def update_conversation(self) -> Callable[ - [conversational_search_service.UpdateConversationRequest], - Awaitable[gcd_conversation.Conversation]]: - r"""Return a callable for the update conversation method over gRPC. - - Updates a Conversation. - - [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] - action type cannot be changed. If the - [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] - to update does not exist, a NOT_FOUND error is returned. - - 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.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.ConversationalSearchService/UpdateConversation', - request_serializer=conversational_search_service.UpdateConversationRequest.serialize, - response_deserializer=gcd_conversation.Conversation.deserialize, - ) - return self._stubs['update_conversation'] - - @property - def get_conversation(self) -> Callable[ - [conversational_search_service.GetConversationRequest], - Awaitable[conversation.Conversation]]: - r"""Return a callable for the get conversation method over gRPC. - - Gets a Conversation. - - Returns: - Callable[[~.GetConversationRequest], - 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 'get_conversation' not in self._stubs: - self._stubs['get_conversation'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.ConversationalSearchService/GetConversation', - request_serializer=conversational_search_service.GetConversationRequest.serialize, - response_deserializer=conversation.Conversation.deserialize, - ) - return self._stubs['get_conversation'] - - @property - def list_conversations(self) -> Callable[ - [conversational_search_service.ListConversationsRequest], - Awaitable[conversational_search_service.ListConversationsResponse]]: - r"""Return a callable for the list conversations method over gRPC. - - Lists all Conversations by their parent - [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]. - - Returns: - Callable[[~.ListConversationsRequest], - Awaitable[~.ListConversationsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_conversations' not in self._stubs: - self._stubs['list_conversations'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.ConversationalSearchService/ListConversations', - request_serializer=conversational_search_service.ListConversationsRequest.serialize, - response_deserializer=conversational_search_service.ListConversationsResponse.deserialize, - ) - return self._stubs['list_conversations'] - - def close(self): - return self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - -__all__ = ( - 'ConversationalSearchServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/rest.py deleted file mode 100644 index 5aae353bd084..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/conversational_search_service/transports/rest.py +++ /dev/null @@ -1,1156 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.cloud.location import locations_pb2 # type: ignore -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.discoveryengine_v1alpha.types import conversation -from google.cloud.discoveryengine_v1alpha.types import conversation as gcd_conversation -from google.cloud.discoveryengine_v1alpha.types import conversational_search_service -from google.protobuf import empty_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from .base import ConversationalSearchServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class ConversationalSearchServiceRestInterceptor: - """Interceptor for ConversationalSearchService. - - 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 ConversationalSearchServiceRestTransport. - - .. code-block:: python - class MyCustomConversationalSearchServiceInterceptor(ConversationalSearchServiceRestInterceptor): - def pre_converse_conversation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_converse_conversation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_conversation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_conversation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_conversation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_conversation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_conversation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_conversations(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_conversations(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 = ConversationalSearchServiceRestTransport(interceptor=MyCustomConversationalSearchServiceInterceptor()) - client = ConversationalSearchServiceClient(transport=transport) - - - """ - def pre_converse_conversation(self, request: conversational_search_service.ConverseConversationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversational_search_service.ConverseConversationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for converse_conversation - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationalSearchService server. - """ - return request, metadata - - def post_converse_conversation(self, response: conversational_search_service.ConverseConversationResponse) -> conversational_search_service.ConverseConversationResponse: - """Post-rpc interceptor for converse_conversation - - Override in a subclass to manipulate the response - after it is returned by the ConversationalSearchService server but before - it is returned to user code. - """ - return response - def pre_create_conversation(self, request: conversational_search_service.CreateConversationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversational_search_service.CreateConversationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_conversation - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationalSearchService server. - """ - return request, metadata - - def post_create_conversation(self, response: gcd_conversation.Conversation) -> gcd_conversation.Conversation: - """Post-rpc interceptor for create_conversation - - Override in a subclass to manipulate the response - after it is returned by the ConversationalSearchService server but before - it is returned to user code. - """ - return response - def pre_delete_conversation(self, request: conversational_search_service.DeleteConversationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversational_search_service.DeleteConversationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_conversation - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationalSearchService server. - """ - return request, metadata - - def pre_get_conversation(self, request: conversational_search_service.GetConversationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversational_search_service.GetConversationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_conversation - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationalSearchService server. - """ - return request, metadata - - def post_get_conversation(self, response: conversation.Conversation) -> conversation.Conversation: - """Post-rpc interceptor for get_conversation - - Override in a subclass to manipulate the response - after it is returned by the ConversationalSearchService server but before - it is returned to user code. - """ - return response - def pre_list_conversations(self, request: conversational_search_service.ListConversationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversational_search_service.ListConversationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_conversations - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationalSearchService server. - """ - return request, metadata - - def post_list_conversations(self, response: conversational_search_service.ListConversationsResponse) -> conversational_search_service.ListConversationsResponse: - """Post-rpc interceptor for list_conversations - - Override in a subclass to manipulate the response - after it is returned by the ConversationalSearchService server but before - it is returned to user code. - """ - return response - def pre_update_conversation(self, request: conversational_search_service.UpdateConversationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversational_search_service.UpdateConversationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_conversation - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationalSearchService server. - """ - return request, metadata - - def post_update_conversation(self, response: gcd_conversation.Conversation) -> gcd_conversation.Conversation: - """Post-rpc interceptor for update_conversation - - Override in a subclass to manipulate the response - after it is returned by the ConversationalSearchService server but before - it is returned to user code. - """ - return response - - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationalSearchService 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 ConversationalSearchService server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationalSearchService 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 ConversationalSearchService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class ConversationalSearchServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: ConversationalSearchServiceRestInterceptor - - -class ConversationalSearchServiceRestTransport(ConversationalSearchServiceTransport): - """REST backend transport for ConversationalSearchService. - - Service for conversational search. - - 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 = 'discoveryengine.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[ConversationalSearchServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or ConversationalSearchServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _ConverseConversation(ConversationalSearchServiceRestStub): - def __hash__(self): - return hash("ConverseConversation") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversational_search_service.ConverseConversationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> conversational_search_service.ConverseConversationResponse: - r"""Call the converse conversation method over HTTP. - - Args: - request (~.conversational_search_service.ConverseConversationRequest): - The request object. Request message for - [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1alpha.ConversationalSearchService.ConverseConversation] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.conversational_search_service.ConverseConversationResponse: - Response message for - [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1alpha.ConversationalSearchService.ConverseConversation] - method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/conversations/*}:converse', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/conversations/*}:converse', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_converse_conversation(request, metadata) - pb_request = conversational_search_service.ConverseConversationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = conversational_search_service.ConverseConversationResponse() - pb_resp = conversational_search_service.ConverseConversationResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_converse_conversation(resp) - return resp - - class _CreateConversation(ConversationalSearchServiceRestStub): - def __hash__(self): - return hash("CreateConversation") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversational_search_service.CreateConversationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_conversation.Conversation: - r"""Call the create conversation method over HTTP. - - Args: - request (~.conversational_search_service.CreateConversationRequest): - The request object. Request for CreateConversation - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcd_conversation.Conversation: - External conversation proto - definition. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1alpha/{parent=projects/*/locations/*/dataStores/*}/conversations', - 'body': 'conversation', - }, -{ - 'method': 'post', - 'uri': '/v1alpha/{parent=projects/*/locations/*/collections/*/dataStores/*}/conversations', - 'body': 'conversation', - }, - ] - request, metadata = self._interceptor.pre_create_conversation(request, metadata) - pb_request = conversational_search_service.CreateConversationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_conversation.Conversation() - pb_resp = gcd_conversation.Conversation.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_conversation(resp) - return resp - - class _DeleteConversation(ConversationalSearchServiceRestStub): - def __hash__(self): - return hash("DeleteConversation") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversational_search_service.DeleteConversationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete conversation method over HTTP. - - Args: - request (~.conversational_search_service.DeleteConversationRequest): - The request object. Request for DeleteConversation - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/conversations/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/conversations/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_conversation(request, metadata) - pb_request = conversational_search_service.DeleteConversationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _GetConversation(ConversationalSearchServiceRestStub): - def __hash__(self): - return hash("GetConversation") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversational_search_service.GetConversationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> conversation.Conversation: - r"""Call the get conversation method over HTTP. - - Args: - request (~.conversational_search_service.GetConversationRequest): - The request object. Request for GetConversation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.conversation.Conversation: - External conversation proto - definition. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/conversations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/conversations/*}', - }, - ] - request, metadata = self._interceptor.pre_get_conversation(request, metadata) - pb_request = conversational_search_service.GetConversationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = conversation.Conversation() - pb_resp = conversation.Conversation.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_conversation(resp) - return resp - - class _ListConversations(ConversationalSearchServiceRestStub): - def __hash__(self): - return hash("ListConversations") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversational_search_service.ListConversationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> conversational_search_service.ListConversationsResponse: - r"""Call the list conversations method over HTTP. - - Args: - request (~.conversational_search_service.ListConversationsRequest): - The request object. Request for ListConversations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.conversational_search_service.ListConversationsResponse: - Response for ListConversations - method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{parent=projects/*/locations/*/dataStores/*}/conversations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{parent=projects/*/locations/*/collections/*/dataStores/*}/conversations', - }, - ] - request, metadata = self._interceptor.pre_list_conversations(request, metadata) - pb_request = conversational_search_service.ListConversationsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = conversational_search_service.ListConversationsResponse() - pb_resp = conversational_search_service.ListConversationsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_conversations(resp) - return resp - - class _UpdateConversation(ConversationalSearchServiceRestStub): - def __hash__(self): - return hash("UpdateConversation") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversational_search_service.UpdateConversationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_conversation.Conversation: - r"""Call the update conversation method over HTTP. - - Args: - request (~.conversational_search_service.UpdateConversationRequest): - The request object. Request for UpdateConversation - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcd_conversation.Conversation: - External conversation proto - definition. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1alpha/{conversation.name=projects/*/locations/*/dataStores/*/conversations/*}', - 'body': 'conversation', - }, -{ - 'method': 'patch', - 'uri': '/v1alpha/{conversation.name=projects/*/locations/*/collections/*/dataStores/*/conversations/*}', - 'body': 'conversation', - }, - ] - request, metadata = self._interceptor.pre_update_conversation(request, metadata) - pb_request = conversational_search_service.UpdateConversationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_conversation.Conversation() - pb_resp = gcd_conversation.Conversation.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_conversation(resp) - return resp - - @property - def converse_conversation(self) -> Callable[ - [conversational_search_service.ConverseConversationRequest], - conversational_search_service.ConverseConversationResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ConverseConversation(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_conversation(self) -> Callable[ - [conversational_search_service.CreateConversationRequest], - gcd_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._CreateConversation(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_conversation(self) -> Callable[ - [conversational_search_service.DeleteConversationRequest], - 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._DeleteConversation(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_conversation(self) -> Callable[ - [conversational_search_service.GetConversationRequest], - 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._GetConversation(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_conversations(self) -> Callable[ - [conversational_search_service.ListConversationsRequest], - conversational_search_service.ListConversationsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListConversations(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_conversation(self) -> Callable[ - [conversational_search_service.UpdateConversationRequest], - gcd_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_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(ConversationalSearchServiceRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(ConversationalSearchServiceRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'ConversationalSearchServiceRestTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/__init__.py deleted file mode 100644 index e4f0b808a498..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import DocumentServiceClient -from .async_client import DocumentServiceAsyncClient - -__all__ = ( - 'DocumentServiceClient', - 'DocumentServiceAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/async_client.py deleted file mode 100644 index 95fcb6bd4e65..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/async_client.py +++ /dev/null @@ -1,1113 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.discoveryengine_v1alpha import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.discoveryengine_v1alpha.services.document_service import pagers -from google.cloud.discoveryengine_v1alpha.types import document -from google.cloud.discoveryengine_v1alpha.types import document as gcd_document -from google.cloud.discoveryengine_v1alpha.types import document_service -from google.cloud.discoveryengine_v1alpha.types import import_config -from google.cloud.discoveryengine_v1alpha.types import purge_config -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from .transports.base import DocumentServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import DocumentServiceGrpcAsyncIOTransport -from .client import DocumentServiceClient - - -class DocumentServiceAsyncClient: - """Service for ingesting - [Document][google.cloud.discoveryengine.v1alpha.Document] - information of the customer's website. - """ - - _client: DocumentServiceClient - - DEFAULT_ENDPOINT = DocumentServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = DocumentServiceClient.DEFAULT_MTLS_ENDPOINT - - branch_path = staticmethod(DocumentServiceClient.branch_path) - parse_branch_path = staticmethod(DocumentServiceClient.parse_branch_path) - document_path = staticmethod(DocumentServiceClient.document_path) - parse_document_path = staticmethod(DocumentServiceClient.parse_document_path) - common_billing_account_path = staticmethod(DocumentServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(DocumentServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(DocumentServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(DocumentServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(DocumentServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(DocumentServiceClient.parse_common_organization_path) - common_project_path = staticmethod(DocumentServiceClient.common_project_path) - parse_common_project_path = staticmethod(DocumentServiceClient.parse_common_project_path) - common_location_path = staticmethod(DocumentServiceClient.common_location_path) - parse_common_location_path = staticmethod(DocumentServiceClient.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: - DocumentServiceAsyncClient: The constructed client. - """ - return DocumentServiceClient.from_service_account_info.__func__(DocumentServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DocumentServiceAsyncClient: The constructed client. - """ - return DocumentServiceClient.from_service_account_file.__func__(DocumentServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return DocumentServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> DocumentServiceTransport: - """Returns the transport used by the client instance. - - Returns: - DocumentServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(DocumentServiceClient).get_transport_class, type(DocumentServiceClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, DocumentServiceTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the document 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 (Union[str, ~.DocumentServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = DocumentServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def get_document(self, - request: Optional[Union[document_service.GetDocumentRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document.Document: - r"""Gets a - [Document][google.cloud.discoveryengine.v1alpha.Document]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - async def sample_get_document(): - # Create a client - client = discoveryengine_v1alpha.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.GetDocumentRequest( - name="name_value", - ) - - # Make the request - response = await client.get_document(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.GetDocumentRequest, dict]]): - The request object. Request message for - [DocumentService.GetDocument][google.cloud.discoveryengine.v1alpha.DocumentService.GetDocument] - method. - name (:class:`str`): - Required. Full resource name of - [Document][google.cloud.discoveryengine.v1alpha.Document], - such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. - - If the caller does not have permission to access the - [Document][google.cloud.discoveryengine.v1alpha.Document], - regardless of whether or not it exists, a - ``PERMISSION_DENIED`` error is returned. - - If the requested - [Document][google.cloud.discoveryengine.v1alpha.Document] - does not exist, a ``NOT_FOUND`` error is returned. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1alpha.types.Document: - Document captures all raw metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = document_service.GetDocumentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_document, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_documents(self, - request: Optional[Union[document_service.ListDocumentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDocumentsAsyncPager: - r"""Gets a list of - [Document][google.cloud.discoveryengine.v1alpha.Document]s. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - async def sample_list_documents(): - # Create a client - client = discoveryengine_v1alpha.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.ListDocumentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_documents(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.ListDocumentsRequest, dict]]): - The request object. Request message for - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.ListDocuments] - method. - parent (:class:`str`): - Required. The parent branch resource name, such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. - Use ``default_branch`` as the branch ID, to list - documents under the default branch. - - If the caller does not have permission to list - [Document][google.cloud.discoveryengine.v1alpha.Document]s - under this branch, regardless of whether or not this - branch exists, a ``PERMISSION_DENIED`` error is - returned. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1alpha.services.document_service.pagers.ListDocumentsAsyncPager: - Response message for - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.ListDocuments] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = document_service.ListDocumentsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_documents, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListDocumentsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_document(self, - request: Optional[Union[document_service.CreateDocumentRequest, dict]] = None, - *, - parent: Optional[str] = None, - document: Optional[gcd_document.Document] = None, - document_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_document.Document: - r"""Creates a - [Document][google.cloud.discoveryengine.v1alpha.Document]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - async def sample_create_document(): - # Create a client - client = discoveryengine_v1alpha.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.CreateDocumentRequest( - parent="parent_value", - document_id="document_id_value", - ) - - # Make the request - response = await client.create_document(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.CreateDocumentRequest, dict]]): - The request object. Request message for - [DocumentService.CreateDocument][google.cloud.discoveryengine.v1alpha.DocumentService.CreateDocument] - method. - parent (:class:`str`): - Required. The parent resource name, such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - document (:class:`google.cloud.discoveryengine_v1alpha.types.Document`): - Required. The - [Document][google.cloud.discoveryengine.v1alpha.Document] - to create. - - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - document_id (:class:`str`): - Required. The ID to use for the - [Document][google.cloud.discoveryengine.v1alpha.Document], - which will become the final component of the - [Document.name][google.cloud.discoveryengine.v1alpha.Document.name]. - - If the caller does not have permission to create the - [Document][google.cloud.discoveryengine.v1alpha.Document], - regardless of whether or not it exists, a - ``PERMISSION_DENIED`` error is returned. - - This field must be unique among all - [Document][google.cloud.discoveryengine.v1alpha.Document]s - with the same - [parent][google.cloud.discoveryengine.v1alpha.CreateDocumentRequest.parent]. - Otherwise, an ``ALREADY_EXISTS`` error is returned. - - This field must conform to - `RFC-1034 `__ - standard with a length limit of 63 characters. - Otherwise, an ``INVALID_ARGUMENT`` error is returned. - - This corresponds to the ``document_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1alpha.types.Document: - Document captures all raw metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, document, document_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = document_service.CreateDocumentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if document is not None: - request.document = document - if document_id is not None: - request.document_id = document_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_document, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_document(self, - request: Optional[Union[document_service.UpdateDocumentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document.Document: - r"""Updates a - [Document][google.cloud.discoveryengine.v1alpha.Document]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - async def sample_update_document(): - # Create a client - client = discoveryengine_v1alpha.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.UpdateDocumentRequest( - ) - - # Make the request - response = await client.update_document(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.UpdateDocumentRequest, dict]]): - The request object. Request message for - [DocumentService.UpdateDocument][google.cloud.discoveryengine.v1alpha.DocumentService.UpdateDocument] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1alpha.types.Document: - Document captures all raw metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - request = document_service.UpdateDocumentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_document, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("document.name", request.document.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_document(self, - request: Optional[Union[document_service.DeleteDocumentRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a - [Document][google.cloud.discoveryengine.v1alpha.Document]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - async def sample_delete_document(): - # Create a client - client = discoveryengine_v1alpha.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.DeleteDocumentRequest( - name="name_value", - ) - - # Make the request - await client.delete_document(request=request) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.DeleteDocumentRequest, dict]]): - The request object. Request message for - [DocumentService.DeleteDocument][google.cloud.discoveryengine.v1alpha.DocumentService.DeleteDocument] - method. - name (:class:`str`): - Required. Full resource name of - [Document][google.cloud.discoveryengine.v1alpha.Document], - such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. - - If the caller does not have permission to delete the - [Document][google.cloud.discoveryengine.v1alpha.Document], - regardless of whether or not it exists, a - ``PERMISSION_DENIED`` error is returned. - - If the - [Document][google.cloud.discoveryengine.v1alpha.Document] - to delete does not exist, a ``NOT_FOUND`` error is - returned. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = document_service.DeleteDocumentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_document, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def import_documents(self, - request: Optional[Union[import_config.ImportDocumentsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Bulk import of multiple - [Document][google.cloud.discoveryengine.v1alpha.Document]s. - Request processing may be synchronous. Non-existing items will - be created. - - Note: It is possible for a subset of the - [Document][google.cloud.discoveryengine.v1alpha.Document]s to be - successfully updated. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - async def sample_import_documents(): - # Create a client - client = discoveryengine_v1alpha.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.ImportDocumentsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.import_documents(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.ImportDocumentsRequest, dict]]): - The request object. Request message for Import methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.discoveryengine_v1alpha.types.ImportDocumentsResponse` Response of the - [ImportDocumentsRequest][google.cloud.discoveryengine.v1alpha.ImportDocumentsRequest]. - If the long running operation is done, then this - message is returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - request = import_config.ImportDocumentsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_documents, - default_retry=retries.Retry( -initial=1.0,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=300.0, - ), - default_timeout=300.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - import_config.ImportDocumentsResponse, - metadata_type=import_config.ImportDocumentsMetadata, - ) - - # Done; return the response. - return response - - async def purge_documents(self, - request: Optional[Union[purge_config.PurgeDocumentsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Permanently deletes all selected - [Document][google.cloud.discoveryengine.v1alpha.Document]s in a - branch. - - This process is asynchronous. Depending on the number of - [Document][google.cloud.discoveryengine.v1alpha.Document]s to be - deleted, this operation can take hours to complete. Before the - delete operation completes, some - [Document][google.cloud.discoveryengine.v1alpha.Document]s might - still be returned by - [DocumentService.GetDocument][google.cloud.discoveryengine.v1alpha.DocumentService.GetDocument] - or - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.ListDocuments]. - - To get a list of the - [Document][google.cloud.discoveryengine.v1alpha.Document]s to be - deleted, set - [PurgeDocumentsRequest.force][google.cloud.discoveryengine.v1alpha.PurgeDocumentsRequest.force] - to false. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - async def sample_purge_documents(): - # Create a client - client = discoveryengine_v1alpha.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.PurgeDocumentsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_documents(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.PurgeDocumentsRequest, dict]]): - The request object. Request message for - [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.PurgeDocuments] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.discoveryengine_v1alpha.types.PurgeDocumentsResponse` Response message for - [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.PurgeDocuments] - method. If the long running operation is successfully - done, then this message is returned by the - google.longrunning.Operations.response field. - - """ - # Create or coerce a protobuf request object. - request = purge_config.PurgeDocumentsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.purge_documents, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - purge_config.PurgeDocumentsResponse, - metadata_type=purge_config.PurgeDocumentsMetadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "DocumentServiceAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "DocumentServiceAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/client.py deleted file mode 100644 index 25859a535026..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/client.py +++ /dev/null @@ -1,1326 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.discoveryengine_v1alpha import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.discoveryengine_v1alpha.services.document_service import pagers -from google.cloud.discoveryengine_v1alpha.types import document -from google.cloud.discoveryengine_v1alpha.types import document as gcd_document -from google.cloud.discoveryengine_v1alpha.types import document_service -from google.cloud.discoveryengine_v1alpha.types import import_config -from google.cloud.discoveryengine_v1alpha.types import purge_config -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from .transports.base import DocumentServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import DocumentServiceGrpcTransport -from .transports.grpc_asyncio import DocumentServiceGrpcAsyncIOTransport -from .transports.rest import DocumentServiceRestTransport - - -class DocumentServiceClientMeta(type): - """Metaclass for the DocumentService 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[DocumentServiceTransport]] - _transport_registry["grpc"] = DocumentServiceGrpcTransport - _transport_registry["grpc_asyncio"] = DocumentServiceGrpcAsyncIOTransport - _transport_registry["rest"] = DocumentServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[DocumentServiceTransport]: - """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 DocumentServiceClient(metaclass=DocumentServiceClientMeta): - """Service for ingesting - [Document][google.cloud.discoveryengine.v1alpha.Document] - information of the customer's website. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DocumentServiceClient: 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: - DocumentServiceClient: 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) -> DocumentServiceTransport: - """Returns the transport used by the client instance. - - Returns: - DocumentServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def branch_path(project: str,location: str,data_store: str,branch: str,) -> str: - """Returns a fully-qualified branch string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}".format(project=project, location=location, data_store=data_store, branch=branch, ) - - @staticmethod - def parse_branch_path(path: str) -> Dict[str,str]: - """Parses a branch path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def document_path(project: str,location: str,data_store: str,branch: str,document: str,) -> str: - """Returns a fully-qualified document string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) - - @staticmethod - def parse_document_path(path: str) -> Dict[str,str]: - """Parses a document path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)/documents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, DocumentServiceTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the document 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 (Union[str, DocumentServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, DocumentServiceTransport): - # transport is a DocumentServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def get_document(self, - request: Optional[Union[document_service.GetDocumentRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document.Document: - r"""Gets a - [Document][google.cloud.discoveryengine.v1alpha.Document]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - def sample_get_document(): - # Create a client - client = discoveryengine_v1alpha.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.GetDocumentRequest( - name="name_value", - ) - - # Make the request - response = client.get_document(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1alpha.types.GetDocumentRequest, dict]): - The request object. Request message for - [DocumentService.GetDocument][google.cloud.discoveryengine.v1alpha.DocumentService.GetDocument] - method. - name (str): - Required. Full resource name of - [Document][google.cloud.discoveryengine.v1alpha.Document], - such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. - - If the caller does not have permission to access the - [Document][google.cloud.discoveryengine.v1alpha.Document], - regardless of whether or not it exists, a - ``PERMISSION_DENIED`` error is returned. - - If the requested - [Document][google.cloud.discoveryengine.v1alpha.Document] - does not exist, a ``NOT_FOUND`` error is returned. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1alpha.types.Document: - Document captures all raw metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a document_service.GetDocumentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, document_service.GetDocumentRequest): - request = document_service.GetDocumentRequest(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_document] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_documents(self, - request: Optional[Union[document_service.ListDocumentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDocumentsPager: - r"""Gets a list of - [Document][google.cloud.discoveryengine.v1alpha.Document]s. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - def sample_list_documents(): - # Create a client - client = discoveryengine_v1alpha.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.ListDocumentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_documents(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1alpha.types.ListDocumentsRequest, dict]): - The request object. Request message for - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.ListDocuments] - method. - parent (str): - Required. The parent branch resource name, such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. - Use ``default_branch`` as the branch ID, to list - documents under the default branch. - - If the caller does not have permission to list - [Document][google.cloud.discoveryengine.v1alpha.Document]s - under this branch, regardless of whether or not this - branch exists, a ``PERMISSION_DENIED`` error is - returned. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1alpha.services.document_service.pagers.ListDocumentsPager: - Response message for - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.ListDocuments] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a document_service.ListDocumentsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, document_service.ListDocumentsRequest): - request = document_service.ListDocumentsRequest(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_documents] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListDocumentsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_document(self, - request: Optional[Union[document_service.CreateDocumentRequest, dict]] = None, - *, - parent: Optional[str] = None, - document: Optional[gcd_document.Document] = None, - document_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_document.Document: - r"""Creates a - [Document][google.cloud.discoveryengine.v1alpha.Document]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - def sample_create_document(): - # Create a client - client = discoveryengine_v1alpha.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.CreateDocumentRequest( - parent="parent_value", - document_id="document_id_value", - ) - - # Make the request - response = client.create_document(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1alpha.types.CreateDocumentRequest, dict]): - The request object. Request message for - [DocumentService.CreateDocument][google.cloud.discoveryengine.v1alpha.DocumentService.CreateDocument] - method. - parent (str): - Required. The parent resource name, such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - document (google.cloud.discoveryengine_v1alpha.types.Document): - Required. The - [Document][google.cloud.discoveryengine.v1alpha.Document] - to create. - - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - document_id (str): - Required. The ID to use for the - [Document][google.cloud.discoveryengine.v1alpha.Document], - which will become the final component of the - [Document.name][google.cloud.discoveryengine.v1alpha.Document.name]. - - If the caller does not have permission to create the - [Document][google.cloud.discoveryengine.v1alpha.Document], - regardless of whether or not it exists, a - ``PERMISSION_DENIED`` error is returned. - - This field must be unique among all - [Document][google.cloud.discoveryengine.v1alpha.Document]s - with the same - [parent][google.cloud.discoveryengine.v1alpha.CreateDocumentRequest.parent]. - Otherwise, an ``ALREADY_EXISTS`` error is returned. - - This field must conform to - `RFC-1034 `__ - standard with a length limit of 63 characters. - Otherwise, an ``INVALID_ARGUMENT`` error is returned. - - This corresponds to the ``document_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1alpha.types.Document: - Document captures all raw metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, document, document_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a document_service.CreateDocumentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, document_service.CreateDocumentRequest): - request = document_service.CreateDocumentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if document is not None: - request.document = document - if document_id is not None: - request.document_id = document_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_document] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_document(self, - request: Optional[Union[document_service.UpdateDocumentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document.Document: - r"""Updates a - [Document][google.cloud.discoveryengine.v1alpha.Document]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - def sample_update_document(): - # Create a client - client = discoveryengine_v1alpha.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.UpdateDocumentRequest( - ) - - # Make the request - response = client.update_document(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1alpha.types.UpdateDocumentRequest, dict]): - The request object. Request message for - [DocumentService.UpdateDocument][google.cloud.discoveryengine.v1alpha.DocumentService.UpdateDocument] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1alpha.types.Document: - Document captures all raw metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a document_service.UpdateDocumentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, document_service.UpdateDocumentRequest): - request = document_service.UpdateDocumentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_document] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("document.name", request.document.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_document(self, - request: Optional[Union[document_service.DeleteDocumentRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a - [Document][google.cloud.discoveryengine.v1alpha.Document]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - def sample_delete_document(): - # Create a client - client = discoveryengine_v1alpha.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.DeleteDocumentRequest( - name="name_value", - ) - - # Make the request - client.delete_document(request=request) - - Args: - request (Union[google.cloud.discoveryengine_v1alpha.types.DeleteDocumentRequest, dict]): - The request object. Request message for - [DocumentService.DeleteDocument][google.cloud.discoveryengine.v1alpha.DocumentService.DeleteDocument] - method. - name (str): - Required. Full resource name of - [Document][google.cloud.discoveryengine.v1alpha.Document], - such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. - - If the caller does not have permission to delete the - [Document][google.cloud.discoveryengine.v1alpha.Document], - regardless of whether or not it exists, a - ``PERMISSION_DENIED`` error is returned. - - If the - [Document][google.cloud.discoveryengine.v1alpha.Document] - to delete does not exist, a ``NOT_FOUND`` error is - returned. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a document_service.DeleteDocumentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, document_service.DeleteDocumentRequest): - request = document_service.DeleteDocumentRequest(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_document] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def import_documents(self, - request: Optional[Union[import_config.ImportDocumentsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Bulk import of multiple - [Document][google.cloud.discoveryengine.v1alpha.Document]s. - Request processing may be synchronous. Non-existing items will - be created. - - Note: It is possible for a subset of the - [Document][google.cloud.discoveryengine.v1alpha.Document]s to be - successfully updated. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - def sample_import_documents(): - # Create a client - client = discoveryengine_v1alpha.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.ImportDocumentsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.import_documents(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1alpha.types.ImportDocumentsRequest, dict]): - The request object. Request message for Import methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.discoveryengine_v1alpha.types.ImportDocumentsResponse` Response of the - [ImportDocumentsRequest][google.cloud.discoveryengine.v1alpha.ImportDocumentsRequest]. - If the long running operation is done, then this - message is returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a import_config.ImportDocumentsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, import_config.ImportDocumentsRequest): - request = import_config.ImportDocumentsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_documents] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - import_config.ImportDocumentsResponse, - metadata_type=import_config.ImportDocumentsMetadata, - ) - - # Done; return the response. - return response - - def purge_documents(self, - request: Optional[Union[purge_config.PurgeDocumentsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Permanently deletes all selected - [Document][google.cloud.discoveryengine.v1alpha.Document]s in a - branch. - - This process is asynchronous. Depending on the number of - [Document][google.cloud.discoveryengine.v1alpha.Document]s to be - deleted, this operation can take hours to complete. Before the - delete operation completes, some - [Document][google.cloud.discoveryengine.v1alpha.Document]s might - still be returned by - [DocumentService.GetDocument][google.cloud.discoveryengine.v1alpha.DocumentService.GetDocument] - or - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.ListDocuments]. - - To get a list of the - [Document][google.cloud.discoveryengine.v1alpha.Document]s to be - deleted, set - [PurgeDocumentsRequest.force][google.cloud.discoveryengine.v1alpha.PurgeDocumentsRequest.force] - to false. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - def sample_purge_documents(): - # Create a client - client = discoveryengine_v1alpha.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.PurgeDocumentsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_documents(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1alpha.types.PurgeDocumentsRequest, dict]): - The request object. Request message for - [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.PurgeDocuments] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.discoveryengine_v1alpha.types.PurgeDocumentsResponse` Response message for - [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.PurgeDocuments] - method. If the long running operation is successfully - done, then this message is returned by the - google.longrunning.Operations.response field. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a purge_config.PurgeDocumentsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, purge_config.PurgeDocumentsRequest): - request = purge_config.PurgeDocumentsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.purge_documents] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - purge_config.PurgeDocumentsResponse, - metadata_type=purge_config.PurgeDocumentsMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "DocumentServiceClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - - - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "DocumentServiceClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/pagers.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/pagers.py deleted file mode 100644 index c85996e0b84b..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.discoveryengine_v1alpha.types import document -from google.cloud.discoveryengine_v1alpha.types import document_service - - -class ListDocumentsPager: - """A pager for iterating through ``list_documents`` requests. - - This class thinly wraps an initial - :class:`google.cloud.discoveryengine_v1alpha.types.ListDocumentsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``documents`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListDocuments`` requests and continue to iterate - through the ``documents`` field on the - corresponding responses. - - All the usual :class:`google.cloud.discoveryengine_v1alpha.types.ListDocumentsResponse` - 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[..., document_service.ListDocumentsResponse], - request: document_service.ListDocumentsRequest, - response: document_service.ListDocumentsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.discoveryengine_v1alpha.types.ListDocumentsRequest): - The initial request object. - response (google.cloud.discoveryengine_v1alpha.types.ListDocumentsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = document_service.ListDocumentsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[document_service.ListDocumentsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[document.Document]: - for page in self.pages: - yield from page.documents - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListDocumentsAsyncPager: - """A pager for iterating through ``list_documents`` requests. - - This class thinly wraps an initial - :class:`google.cloud.discoveryengine_v1alpha.types.ListDocumentsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``documents`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListDocuments`` requests and continue to iterate - through the ``documents`` field on the - corresponding responses. - - All the usual :class:`google.cloud.discoveryengine_v1alpha.types.ListDocumentsResponse` - 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[document_service.ListDocumentsResponse]], - request: document_service.ListDocumentsRequest, - response: document_service.ListDocumentsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.discoveryengine_v1alpha.types.ListDocumentsRequest): - The initial request object. - response (google.cloud.discoveryengine_v1alpha.types.ListDocumentsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = document_service.ListDocumentsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[document_service.ListDocumentsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[document.Document]: - async def async_generator(): - async for page in self.pages: - for response in page.documents: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/__init__.py deleted file mode 100644 index fb08db02f32c..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import DocumentServiceTransport -from .grpc import DocumentServiceGrpcTransport -from .grpc_asyncio import DocumentServiceGrpcAsyncIOTransport -from .rest import DocumentServiceRestTransport -from .rest import DocumentServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[DocumentServiceTransport]] -_transport_registry['grpc'] = DocumentServiceGrpcTransport -_transport_registry['grpc_asyncio'] = DocumentServiceGrpcAsyncIOTransport -_transport_registry['rest'] = DocumentServiceRestTransport - -__all__ = ( - 'DocumentServiceTransport', - 'DocumentServiceGrpcTransport', - 'DocumentServiceGrpcAsyncIOTransport', - 'DocumentServiceRestTransport', - 'DocumentServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/base.py deleted file mode 100644 index 3d8e5687bd47..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/base.py +++ /dev/null @@ -1,269 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.discoveryengine_v1alpha import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.discoveryengine_v1alpha.types import document -from google.cloud.discoveryengine_v1alpha.types import document as gcd_document -from google.cloud.discoveryengine_v1alpha.types import document_service -from google.cloud.discoveryengine_v1alpha.types import import_config -from google.cloud.discoveryengine_v1alpha.types import purge_config -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class DocumentServiceTransport(abc.ABC): - """Abstract transport class for DocumentService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'discoveryengine.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.get_document: gapic_v1.method.wrap_method( - self.get_document, - default_timeout=None, - client_info=client_info, - ), - self.list_documents: gapic_v1.method.wrap_method( - self.list_documents, - default_timeout=None, - client_info=client_info, - ), - self.create_document: gapic_v1.method.wrap_method( - self.create_document, - default_timeout=None, - client_info=client_info, - ), - self.update_document: gapic_v1.method.wrap_method( - self.update_document, - default_timeout=None, - client_info=client_info, - ), - self.delete_document: gapic_v1.method.wrap_method( - self.delete_document, - default_timeout=None, - client_info=client_info, - ), - self.import_documents: gapic_v1.method.wrap_method( - self.import_documents, - default_retry=retries.Retry( -initial=1.0,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=300.0, - ), - default_timeout=300.0, - client_info=client_info, - ), - self.purge_documents: gapic_v1.method.wrap_method( - self.purge_documents, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def get_document(self) -> Callable[ - [document_service.GetDocumentRequest], - Union[ - document.Document, - Awaitable[document.Document] - ]]: - raise NotImplementedError() - - @property - def list_documents(self) -> Callable[ - [document_service.ListDocumentsRequest], - Union[ - document_service.ListDocumentsResponse, - Awaitable[document_service.ListDocumentsResponse] - ]]: - raise NotImplementedError() - - @property - def create_document(self) -> Callable[ - [document_service.CreateDocumentRequest], - Union[ - gcd_document.Document, - Awaitable[gcd_document.Document] - ]]: - raise NotImplementedError() - - @property - def update_document(self) -> Callable[ - [document_service.UpdateDocumentRequest], - Union[ - document.Document, - Awaitable[document.Document] - ]]: - raise NotImplementedError() - - @property - def delete_document(self) -> Callable[ - [document_service.DeleteDocumentRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def import_documents(self) -> Callable[ - [import_config.ImportDocumentsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def purge_documents(self) -> Callable[ - [purge_config.PurgeDocumentsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'DocumentServiceTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/grpc.py deleted file mode 100644 index 96c8692508a2..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/grpc.py +++ /dev/null @@ -1,513 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.discoveryengine_v1alpha.types import document -from google.cloud.discoveryengine_v1alpha.types import document as gcd_document -from google.cloud.discoveryengine_v1alpha.types import document_service -from google.cloud.discoveryengine_v1alpha.types import import_config -from google.cloud.discoveryengine_v1alpha.types import purge_config -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import DocumentServiceTransport, DEFAULT_CLIENT_INFO - - -class DocumentServiceGrpcTransport(DocumentServiceTransport): - """gRPC backend transport for DocumentService. - - Service for ingesting - [Document][google.cloud.discoveryengine.v1alpha.Document] - information of the customer's website. - - 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def get_document(self) -> Callable[ - [document_service.GetDocumentRequest], - document.Document]: - r"""Return a callable for the get document method over gRPC. - - Gets a - [Document][google.cloud.discoveryengine.v1alpha.Document]. - - Returns: - Callable[[~.GetDocumentRequest], - ~.Document]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_document' not in self._stubs: - self._stubs['get_document'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.DocumentService/GetDocument', - request_serializer=document_service.GetDocumentRequest.serialize, - response_deserializer=document.Document.deserialize, - ) - return self._stubs['get_document'] - - @property - def list_documents(self) -> Callable[ - [document_service.ListDocumentsRequest], - document_service.ListDocumentsResponse]: - r"""Return a callable for the list documents method over gRPC. - - Gets a list of - [Document][google.cloud.discoveryengine.v1alpha.Document]s. - - Returns: - Callable[[~.ListDocumentsRequest], - ~.ListDocumentsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_documents' not in self._stubs: - self._stubs['list_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.DocumentService/ListDocuments', - request_serializer=document_service.ListDocumentsRequest.serialize, - response_deserializer=document_service.ListDocumentsResponse.deserialize, - ) - return self._stubs['list_documents'] - - @property - def create_document(self) -> Callable[ - [document_service.CreateDocumentRequest], - gcd_document.Document]: - r"""Return a callable for the create document method over gRPC. - - Creates a - [Document][google.cloud.discoveryengine.v1alpha.Document]. - - Returns: - Callable[[~.CreateDocumentRequest], - ~.Document]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_document' not in self._stubs: - self._stubs['create_document'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.DocumentService/CreateDocument', - request_serializer=document_service.CreateDocumentRequest.serialize, - response_deserializer=gcd_document.Document.deserialize, - ) - return self._stubs['create_document'] - - @property - def update_document(self) -> Callable[ - [document_service.UpdateDocumentRequest], - document.Document]: - r"""Return a callable for the update document method over gRPC. - - Updates a - [Document][google.cloud.discoveryengine.v1alpha.Document]. - - Returns: - Callable[[~.UpdateDocumentRequest], - ~.Document]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_document' not in self._stubs: - self._stubs['update_document'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.DocumentService/UpdateDocument', - request_serializer=document_service.UpdateDocumentRequest.serialize, - response_deserializer=document.Document.deserialize, - ) - return self._stubs['update_document'] - - @property - def delete_document(self) -> Callable[ - [document_service.DeleteDocumentRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete document method over gRPC. - - Deletes a - [Document][google.cloud.discoveryengine.v1alpha.Document]. - - Returns: - Callable[[~.DeleteDocumentRequest], - ~.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_document' not in self._stubs: - self._stubs['delete_document'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.DocumentService/DeleteDocument', - request_serializer=document_service.DeleteDocumentRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_document'] - - @property - def import_documents(self) -> Callable[ - [import_config.ImportDocumentsRequest], - operations_pb2.Operation]: - r"""Return a callable for the import documents method over gRPC. - - Bulk import of multiple - [Document][google.cloud.discoveryengine.v1alpha.Document]s. - Request processing may be synchronous. Non-existing items will - be created. - - Note: It is possible for a subset of the - [Document][google.cloud.discoveryengine.v1alpha.Document]s to be - successfully updated. - - Returns: - Callable[[~.ImportDocumentsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_documents' not in self._stubs: - self._stubs['import_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.DocumentService/ImportDocuments', - request_serializer=import_config.ImportDocumentsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_documents'] - - @property - def purge_documents(self) -> Callable[ - [purge_config.PurgeDocumentsRequest], - operations_pb2.Operation]: - r"""Return a callable for the purge documents method over gRPC. - - Permanently deletes all selected - [Document][google.cloud.discoveryengine.v1alpha.Document]s in a - branch. - - This process is asynchronous. Depending on the number of - [Document][google.cloud.discoveryengine.v1alpha.Document]s to be - deleted, this operation can take hours to complete. Before the - delete operation completes, some - [Document][google.cloud.discoveryengine.v1alpha.Document]s might - still be returned by - [DocumentService.GetDocument][google.cloud.discoveryengine.v1alpha.DocumentService.GetDocument] - or - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.ListDocuments]. - - To get a list of the - [Document][google.cloud.discoveryengine.v1alpha.Document]s to be - deleted, set - [PurgeDocumentsRequest.force][google.cloud.discoveryengine.v1alpha.PurgeDocumentsRequest.force] - to false. - - Returns: - Callable[[~.PurgeDocumentsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'purge_documents' not in self._stubs: - self._stubs['purge_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.DocumentService/PurgeDocuments', - request_serializer=purge_config.PurgeDocumentsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['purge_documents'] - - def close(self): - self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'DocumentServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/grpc_asyncio.py deleted file mode 100644 index e15ed17c3f75..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,512 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.discoveryengine_v1alpha.types import document -from google.cloud.discoveryengine_v1alpha.types import document as gcd_document -from google.cloud.discoveryengine_v1alpha.types import document_service -from google.cloud.discoveryengine_v1alpha.types import import_config -from google.cloud.discoveryengine_v1alpha.types import purge_config -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import DocumentServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import DocumentServiceGrpcTransport - - -class DocumentServiceGrpcAsyncIOTransport(DocumentServiceTransport): - """gRPC AsyncIO backend transport for DocumentService. - - Service for ingesting - [Document][google.cloud.discoveryengine.v1alpha.Document] - information of the customer's website. - - 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def get_document(self) -> Callable[ - [document_service.GetDocumentRequest], - Awaitable[document.Document]]: - r"""Return a callable for the get document method over gRPC. - - Gets a - [Document][google.cloud.discoveryengine.v1alpha.Document]. - - Returns: - Callable[[~.GetDocumentRequest], - Awaitable[~.Document]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_document' not in self._stubs: - self._stubs['get_document'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.DocumentService/GetDocument', - request_serializer=document_service.GetDocumentRequest.serialize, - response_deserializer=document.Document.deserialize, - ) - return self._stubs['get_document'] - - @property - def list_documents(self) -> Callable[ - [document_service.ListDocumentsRequest], - Awaitable[document_service.ListDocumentsResponse]]: - r"""Return a callable for the list documents method over gRPC. - - Gets a list of - [Document][google.cloud.discoveryengine.v1alpha.Document]s. - - Returns: - Callable[[~.ListDocumentsRequest], - Awaitable[~.ListDocumentsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_documents' not in self._stubs: - self._stubs['list_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.DocumentService/ListDocuments', - request_serializer=document_service.ListDocumentsRequest.serialize, - response_deserializer=document_service.ListDocumentsResponse.deserialize, - ) - return self._stubs['list_documents'] - - @property - def create_document(self) -> Callable[ - [document_service.CreateDocumentRequest], - Awaitable[gcd_document.Document]]: - r"""Return a callable for the create document method over gRPC. - - Creates a - [Document][google.cloud.discoveryengine.v1alpha.Document]. - - Returns: - Callable[[~.CreateDocumentRequest], - Awaitable[~.Document]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_document' not in self._stubs: - self._stubs['create_document'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.DocumentService/CreateDocument', - request_serializer=document_service.CreateDocumentRequest.serialize, - response_deserializer=gcd_document.Document.deserialize, - ) - return self._stubs['create_document'] - - @property - def update_document(self) -> Callable[ - [document_service.UpdateDocumentRequest], - Awaitable[document.Document]]: - r"""Return a callable for the update document method over gRPC. - - Updates a - [Document][google.cloud.discoveryengine.v1alpha.Document]. - - Returns: - Callable[[~.UpdateDocumentRequest], - Awaitable[~.Document]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_document' not in self._stubs: - self._stubs['update_document'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.DocumentService/UpdateDocument', - request_serializer=document_service.UpdateDocumentRequest.serialize, - response_deserializer=document.Document.deserialize, - ) - return self._stubs['update_document'] - - @property - def delete_document(self) -> Callable[ - [document_service.DeleteDocumentRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete document method over gRPC. - - Deletes a - [Document][google.cloud.discoveryengine.v1alpha.Document]. - - Returns: - Callable[[~.DeleteDocumentRequest], - 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_document' not in self._stubs: - self._stubs['delete_document'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.DocumentService/DeleteDocument', - request_serializer=document_service.DeleteDocumentRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_document'] - - @property - def import_documents(self) -> Callable[ - [import_config.ImportDocumentsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import documents method over gRPC. - - Bulk import of multiple - [Document][google.cloud.discoveryengine.v1alpha.Document]s. - Request processing may be synchronous. Non-existing items will - be created. - - Note: It is possible for a subset of the - [Document][google.cloud.discoveryengine.v1alpha.Document]s to be - successfully updated. - - Returns: - Callable[[~.ImportDocumentsRequest], - 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 'import_documents' not in self._stubs: - self._stubs['import_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.DocumentService/ImportDocuments', - request_serializer=import_config.ImportDocumentsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_documents'] - - @property - def purge_documents(self) -> Callable[ - [purge_config.PurgeDocumentsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the purge documents method over gRPC. - - Permanently deletes all selected - [Document][google.cloud.discoveryengine.v1alpha.Document]s in a - branch. - - This process is asynchronous. Depending on the number of - [Document][google.cloud.discoveryengine.v1alpha.Document]s to be - deleted, this operation can take hours to complete. Before the - delete operation completes, some - [Document][google.cloud.discoveryengine.v1alpha.Document]s might - still be returned by - [DocumentService.GetDocument][google.cloud.discoveryengine.v1alpha.DocumentService.GetDocument] - or - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.ListDocuments]. - - To get a list of the - [Document][google.cloud.discoveryengine.v1alpha.Document]s to be - deleted, set - [PurgeDocumentsRequest.force][google.cloud.discoveryengine.v1alpha.PurgeDocumentsRequest.force] - to false. - - Returns: - Callable[[~.PurgeDocumentsRequest], - 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 'purge_documents' not in self._stubs: - self._stubs['purge_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.DocumentService/PurgeDocuments', - request_serializer=purge_config.PurgeDocumentsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['purge_documents'] - - def close(self): - return self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - -__all__ = ( - 'DocumentServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/rest.py deleted file mode 100644 index 7595268f0392..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/document_service/transports/rest.py +++ /dev/null @@ -1,1429 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.cloud.location import locations_pb2 # type: ignore -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.discoveryengine_v1alpha.types import document -from google.cloud.discoveryengine_v1alpha.types import document as gcd_document -from google.cloud.discoveryengine_v1alpha.types import document_service -from google.cloud.discoveryengine_v1alpha.types import import_config -from google.cloud.discoveryengine_v1alpha.types import purge_config -from google.protobuf import empty_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from .base import DocumentServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class DocumentServiceRestInterceptor: - """Interceptor for DocumentService. - - 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 DocumentServiceRestTransport. - - .. code-block:: python - class MyCustomDocumentServiceInterceptor(DocumentServiceRestInterceptor): - def pre_create_document(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_document(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_document(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_document(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_document(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_import_documents(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_import_documents(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_documents(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_documents(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_purge_documents(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_purge_documents(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_document(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_document(self, response): - logging.log(f"Received response: {response}") - return response - - transport = DocumentServiceRestTransport(interceptor=MyCustomDocumentServiceInterceptor()) - client = DocumentServiceClient(transport=transport) - - - """ - def pre_create_document(self, request: document_service.CreateDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_service.CreateDocumentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_document - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService server. - """ - return request, metadata - - def post_create_document(self, response: gcd_document.Document) -> gcd_document.Document: - """Post-rpc interceptor for create_document - - Override in a subclass to manipulate the response - after it is returned by the DocumentService server but before - it is returned to user code. - """ - return response - def pre_delete_document(self, request: document_service.DeleteDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_service.DeleteDocumentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_document - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService server. - """ - return request, metadata - - def pre_get_document(self, request: document_service.GetDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_service.GetDocumentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_document - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService server. - """ - return request, metadata - - def post_get_document(self, response: document.Document) -> document.Document: - """Post-rpc interceptor for get_document - - Override in a subclass to manipulate the response - after it is returned by the DocumentService server but before - it is returned to user code. - """ - return response - def pre_import_documents(self, request: import_config.ImportDocumentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[import_config.ImportDocumentsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for import_documents - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService server. - """ - return request, metadata - - def post_import_documents(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for import_documents - - Override in a subclass to manipulate the response - after it is returned by the DocumentService server but before - it is returned to user code. - """ - return response - def pre_list_documents(self, request: document_service.ListDocumentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_service.ListDocumentsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_documents - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService server. - """ - return request, metadata - - def post_list_documents(self, response: document_service.ListDocumentsResponse) -> document_service.ListDocumentsResponse: - """Post-rpc interceptor for list_documents - - Override in a subclass to manipulate the response - after it is returned by the DocumentService server but before - it is returned to user code. - """ - return response - def pre_purge_documents(self, request: purge_config.PurgeDocumentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[purge_config.PurgeDocumentsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for purge_documents - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService server. - """ - return request, metadata - - def post_purge_documents(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for purge_documents - - Override in a subclass to manipulate the response - after it is returned by the DocumentService server but before - it is returned to user code. - """ - return response - def pre_update_document(self, request: document_service.UpdateDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_service.UpdateDocumentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_document - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService server. - """ - return request, metadata - - def post_update_document(self, response: document.Document) -> document.Document: - """Post-rpc interceptor for update_document - - Override in a subclass to manipulate the response - after it is returned by the DocumentService server but before - it is returned to user code. - """ - return response - - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService 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 DocumentService server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService 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 DocumentService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class DocumentServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: DocumentServiceRestInterceptor - - -class DocumentServiceRestTransport(DocumentServiceTransport): - """REST backend transport for DocumentService. - - Service for ingesting - [Document][google.cloud.discoveryengine.v1alpha.Document] - information of the customer's website. - - 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 = 'discoveryengine.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[DocumentServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or DocumentServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*}/operations', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1alpha") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _CreateDocument(DocumentServiceRestStub): - def __hash__(self): - return hash("CreateDocument") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "documentId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_service.CreateDocumentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_document.Document: - r"""Call the create document method over HTTP. - - Args: - request (~.document_service.CreateDocumentRequest): - The request object. Request message for - [DocumentService.CreateDocument][google.cloud.discoveryengine.v1alpha.DocumentService.CreateDocument] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcd_document.Document: - Document captures all raw metadata - information of items to be recommended - or searched. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1alpha/{parent=projects/*/locations/*/dataStores/*/branches/*}/documents', - 'body': 'document', - }, -{ - 'method': 'post', - 'uri': '/v1alpha/{parent=projects/*/locations/*/collections/*/dataStores/*/branches/*}/documents', - 'body': 'document', - }, - ] - request, metadata = self._interceptor.pre_create_document(request, metadata) - pb_request = document_service.CreateDocumentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_document.Document() - pb_resp = gcd_document.Document.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_document(resp) - return resp - - class _DeleteDocument(DocumentServiceRestStub): - def __hash__(self): - return hash("DeleteDocument") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_service.DeleteDocumentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete document method over HTTP. - - Args: - request (~.document_service.DeleteDocumentRequest): - The request object. Request message for - [DocumentService.DeleteDocument][google.cloud.discoveryengine.v1alpha.DocumentService.DeleteDocument] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/documents/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/documents/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_document(request, metadata) - pb_request = document_service.DeleteDocumentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _GetDocument(DocumentServiceRestStub): - def __hash__(self): - return hash("GetDocument") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_service.GetDocumentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document.Document: - r"""Call the get document method over HTTP. - - Args: - request (~.document_service.GetDocumentRequest): - The request object. Request message for - [DocumentService.GetDocument][google.cloud.discoveryengine.v1alpha.DocumentService.GetDocument] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.document.Document: - Document captures all raw metadata - information of items to be recommended - or searched. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/documents/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/documents/*}', - }, - ] - request, metadata = self._interceptor.pre_get_document(request, metadata) - pb_request = document_service.GetDocumentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document.Document() - pb_resp = document.Document.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_document(resp) - return resp - - class _ImportDocuments(DocumentServiceRestStub): - def __hash__(self): - return hash("ImportDocuments") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: import_config.ImportDocumentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the import documents method over HTTP. - - Args: - request (~.import_config.ImportDocumentsRequest): - The request object. Request message for Import methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1alpha/{parent=projects/*/locations/*/dataStores/*/branches/*}/documents:import', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1alpha/{parent=projects/*/locations/*/collections/*/dataStores/*/branches/*}/documents:import', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_import_documents(request, metadata) - pb_request = import_config.ImportDocumentsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_import_documents(resp) - return resp - - class _ListDocuments(DocumentServiceRestStub): - def __hash__(self): - return hash("ListDocuments") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_service.ListDocumentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document_service.ListDocumentsResponse: - r"""Call the list documents method over HTTP. - - Args: - request (~.document_service.ListDocumentsRequest): - The request object. Request message for - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.ListDocuments] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.document_service.ListDocumentsResponse: - Response message for - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.ListDocuments] - method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{parent=projects/*/locations/*/dataStores/*/branches/*}/documents', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{parent=projects/*/locations/*/collections/*/dataStores/*/branches/*}/documents', - }, - ] - request, metadata = self._interceptor.pre_list_documents(request, metadata) - pb_request = document_service.ListDocumentsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document_service.ListDocumentsResponse() - pb_resp = document_service.ListDocumentsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_documents(resp) - return resp - - class _PurgeDocuments(DocumentServiceRestStub): - def __hash__(self): - return hash("PurgeDocuments") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: purge_config.PurgeDocumentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the purge documents method over HTTP. - - Args: - request (~.purge_config.PurgeDocumentsRequest): - The request object. Request message for - [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.PurgeDocuments] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1alpha/{parent=projects/*/locations/*/dataStores/*/branches/*}/documents:purge', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1alpha/{parent=projects/*/locations/*/collections/*/dataStores/*/branches/*}/documents:purge', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_purge_documents(request, metadata) - pb_request = purge_config.PurgeDocumentsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_purge_documents(resp) - return resp - - class _UpdateDocument(DocumentServiceRestStub): - def __hash__(self): - return hash("UpdateDocument") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_service.UpdateDocumentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document.Document: - r"""Call the update document method over HTTP. - - Args: - request (~.document_service.UpdateDocumentRequest): - The request object. Request message for - [DocumentService.UpdateDocument][google.cloud.discoveryengine.v1alpha.DocumentService.UpdateDocument] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.document.Document: - Document captures all raw metadata - information of items to be recommended - or searched. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1alpha/{document.name=projects/*/locations/*/dataStores/*/branches/*/documents/*}', - 'body': 'document', - }, -{ - 'method': 'patch', - 'uri': '/v1alpha/{document.name=projects/*/locations/*/collections/*/dataStores/*/branches/*/documents/*}', - 'body': 'document', - }, - ] - request, metadata = self._interceptor.pre_update_document(request, metadata) - pb_request = document_service.UpdateDocumentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document.Document() - pb_resp = document.Document.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_document(resp) - return resp - - @property - def create_document(self) -> Callable[ - [document_service.CreateDocumentRequest], - gcd_document.Document]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateDocument(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_document(self) -> Callable[ - [document_service.DeleteDocumentRequest], - 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._DeleteDocument(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_document(self) -> Callable[ - [document_service.GetDocumentRequest], - document.Document]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetDocument(self._session, self._host, self._interceptor) # type: ignore - - @property - def import_documents(self) -> Callable[ - [import_config.ImportDocumentsRequest], - 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._ImportDocuments(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_documents(self) -> Callable[ - [document_service.ListDocumentsRequest], - document_service.ListDocumentsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListDocuments(self._session, self._host, self._interceptor) # type: ignore - - @property - def purge_documents(self) -> Callable[ - [purge_config.PurgeDocumentsRequest], - 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._PurgeDocuments(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_document(self) -> Callable[ - [document_service.UpdateDocumentRequest], - document.Document]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateDocument(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(DocumentServiceRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(DocumentServiceRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'DocumentServiceRestTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/__init__.py deleted file mode 100644 index ad8f24a9e055..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import RecommendationServiceClient -from .async_client import RecommendationServiceAsyncClient - -__all__ = ( - 'RecommendationServiceClient', - 'RecommendationServiceAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/async_client.py deleted file mode 100644 index 33cfc476e3a6..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/async_client.py +++ /dev/null @@ -1,389 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.discoveryengine_v1alpha import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.discoveryengine_v1alpha.types import recommendation_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .transports.base import RecommendationServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import RecommendationServiceGrpcAsyncIOTransport -from .client import RecommendationServiceClient - - -class RecommendationServiceAsyncClient: - """Service for making recommendations.""" - - _client: RecommendationServiceClient - - DEFAULT_ENDPOINT = RecommendationServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = RecommendationServiceClient.DEFAULT_MTLS_ENDPOINT - - document_path = staticmethod(RecommendationServiceClient.document_path) - parse_document_path = staticmethod(RecommendationServiceClient.parse_document_path) - serving_config_path = staticmethod(RecommendationServiceClient.serving_config_path) - parse_serving_config_path = staticmethod(RecommendationServiceClient.parse_serving_config_path) - common_billing_account_path = staticmethod(RecommendationServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(RecommendationServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(RecommendationServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(RecommendationServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(RecommendationServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(RecommendationServiceClient.parse_common_organization_path) - common_project_path = staticmethod(RecommendationServiceClient.common_project_path) - parse_common_project_path = staticmethod(RecommendationServiceClient.parse_common_project_path) - common_location_path = staticmethod(RecommendationServiceClient.common_location_path) - parse_common_location_path = staticmethod(RecommendationServiceClient.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: - RecommendationServiceAsyncClient: The constructed client. - """ - return RecommendationServiceClient.from_service_account_info.__func__(RecommendationServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RecommendationServiceAsyncClient: The constructed client. - """ - return RecommendationServiceClient.from_service_account_file.__func__(RecommendationServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return RecommendationServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> RecommendationServiceTransport: - """Returns the transport used by the client instance. - - Returns: - RecommendationServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(RecommendationServiceClient).get_transport_class, type(RecommendationServiceClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, RecommendationServiceTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the recommendation 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 (Union[str, ~.RecommendationServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = RecommendationServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def recommend(self, - request: Optional[Union[recommendation_service.RecommendRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> recommendation_service.RecommendResponse: - r"""Makes a recommendation, which requires a contextual - user event. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - async def sample_recommend(): - # Create a client - client = discoveryengine_v1alpha.RecommendationServiceAsyncClient() - - # Initialize request argument(s) - user_event = discoveryengine_v1alpha.UserEvent() - user_event.event_type = "event_type_value" - user_event.user_pseudo_id = "user_pseudo_id_value" - - request = discoveryengine_v1alpha.RecommendRequest( - serving_config="serving_config_value", - user_event=user_event, - ) - - # Make the request - response = await client.recommend(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.RecommendRequest, dict]]): - The request object. Request message for Recommend method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1alpha.types.RecommendResponse: - Response message for Recommend - method. - - """ - # Create or coerce a protobuf request object. - request = recommendation_service.RecommendRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.recommend, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config", request.serving_config), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "RecommendationServiceAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "RecommendationServiceAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/client.py deleted file mode 100644 index 9fd6b59e83b4..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/client.py +++ /dev/null @@ -1,606 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.discoveryengine_v1alpha import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.discoveryengine_v1alpha.types import recommendation_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .transports.base import RecommendationServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import RecommendationServiceGrpcTransport -from .transports.grpc_asyncio import RecommendationServiceGrpcAsyncIOTransport -from .transports.rest import RecommendationServiceRestTransport - - -class RecommendationServiceClientMeta(type): - """Metaclass for the RecommendationService 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[RecommendationServiceTransport]] - _transport_registry["grpc"] = RecommendationServiceGrpcTransport - _transport_registry["grpc_asyncio"] = RecommendationServiceGrpcAsyncIOTransport - _transport_registry["rest"] = RecommendationServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[RecommendationServiceTransport]: - """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 RecommendationServiceClient(metaclass=RecommendationServiceClientMeta): - """Service for making recommendations.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RecommendationServiceClient: 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: - RecommendationServiceClient: 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) -> RecommendationServiceTransport: - """Returns the transport used by the client instance. - - Returns: - RecommendationServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def document_path(project: str,location: str,data_store: str,branch: str,document: str,) -> str: - """Returns a fully-qualified document string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) - - @staticmethod - def parse_document_path(path: str) -> Dict[str,str]: - """Parses a document path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)/documents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def serving_config_path(project: str,location: str,data_store: str,serving_config: str,) -> str: - """Returns a fully-qualified serving_config string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}/servingConfigs/{serving_config}".format(project=project, location=location, data_store=data_store, serving_config=serving_config, ) - - @staticmethod - def parse_serving_config_path(path: str) -> Dict[str,str]: - """Parses a serving_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/servingConfigs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, RecommendationServiceTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the recommendation 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 (Union[str, RecommendationServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, RecommendationServiceTransport): - # transport is a RecommendationServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def recommend(self, - request: Optional[Union[recommendation_service.RecommendRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> recommendation_service.RecommendResponse: - r"""Makes a recommendation, which requires a contextual - user event. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - def sample_recommend(): - # Create a client - client = discoveryengine_v1alpha.RecommendationServiceClient() - - # Initialize request argument(s) - user_event = discoveryengine_v1alpha.UserEvent() - user_event.event_type = "event_type_value" - user_event.user_pseudo_id = "user_pseudo_id_value" - - request = discoveryengine_v1alpha.RecommendRequest( - serving_config="serving_config_value", - user_event=user_event, - ) - - # Make the request - response = client.recommend(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1alpha.types.RecommendRequest, dict]): - The request object. Request message for Recommend method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1alpha.types.RecommendResponse: - Response message for Recommend - method. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a recommendation_service.RecommendRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, recommendation_service.RecommendRequest): - request = recommendation_service.RecommendRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.recommend] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config", request.serving_config), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "RecommendationServiceClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - - - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "RecommendationServiceClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/__init__.py deleted file mode 100644 index ce9f9edfd346..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import RecommendationServiceTransport -from .grpc import RecommendationServiceGrpcTransport -from .grpc_asyncio import RecommendationServiceGrpcAsyncIOTransport -from .rest import RecommendationServiceRestTransport -from .rest import RecommendationServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[RecommendationServiceTransport]] -_transport_registry['grpc'] = RecommendationServiceGrpcTransport -_transport_registry['grpc_asyncio'] = RecommendationServiceGrpcAsyncIOTransport -_transport_registry['rest'] = RecommendationServiceRestTransport - -__all__ = ( - 'RecommendationServiceTransport', - 'RecommendationServiceGrpcTransport', - 'RecommendationServiceGrpcAsyncIOTransport', - 'RecommendationServiceRestTransport', - 'RecommendationServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/base.py deleted file mode 100644 index d351956c74c7..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/base.py +++ /dev/null @@ -1,168 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.discoveryengine_v1alpha import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.discoveryengine_v1alpha.types import recommendation_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class RecommendationServiceTransport(abc.ABC): - """Abstract transport class for RecommendationService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'discoveryengine.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.recommend: gapic_v1.method.wrap_method( - self.recommend, - 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 recommend(self) -> Callable[ - [recommendation_service.RecommendRequest], - Union[ - recommendation_service.RecommendResponse, - Awaitable[recommendation_service.RecommendResponse] - ]]: - 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 kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'RecommendationServiceTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/grpc.py deleted file mode 100644 index 98c679fa7058..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/grpc.py +++ /dev/null @@ -1,303 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.discoveryengine_v1alpha.types import recommendation_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import RecommendationServiceTransport, DEFAULT_CLIENT_INFO - - -class RecommendationServiceGrpcTransport(RecommendationServiceTransport): - """gRPC backend transport for RecommendationService. - - Service for making recommendations. - - 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def recommend(self) -> Callable[ - [recommendation_service.RecommendRequest], - recommendation_service.RecommendResponse]: - r"""Return a callable for the recommend method over gRPC. - - Makes a recommendation, which requires a contextual - user event. - - Returns: - Callable[[~.RecommendRequest], - ~.RecommendResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'recommend' not in self._stubs: - self._stubs['recommend'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.RecommendationService/Recommend', - request_serializer=recommendation_service.RecommendRequest.serialize, - response_deserializer=recommendation_service.RecommendResponse.deserialize, - ) - return self._stubs['recommend'] - - def close(self): - self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'RecommendationServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/grpc_asyncio.py deleted file mode 100644 index 3045bfc4e95a..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,302 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.discoveryengine_v1alpha.types import recommendation_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import RecommendationServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import RecommendationServiceGrpcTransport - - -class RecommendationServiceGrpcAsyncIOTransport(RecommendationServiceTransport): - """gRPC AsyncIO backend transport for RecommendationService. - - Service for making recommendations. - - 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def recommend(self) -> Callable[ - [recommendation_service.RecommendRequest], - Awaitable[recommendation_service.RecommendResponse]]: - r"""Return a callable for the recommend method over gRPC. - - Makes a recommendation, which requires a contextual - user event. - - Returns: - Callable[[~.RecommendRequest], - Awaitable[~.RecommendResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'recommend' not in self._stubs: - self._stubs['recommend'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.RecommendationService/Recommend', - request_serializer=recommendation_service.RecommendRequest.serialize, - response_deserializer=recommendation_service.RecommendResponse.deserialize, - ) - return self._stubs['recommend'] - - def close(self): - return self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - -__all__ = ( - 'RecommendationServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/rest.py deleted file mode 100644 index 10eeeb90c39f..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/recommendation_service/transports/rest.py +++ /dev/null @@ -1,578 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.cloud.location import locations_pb2 # type: ignore -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.discoveryengine_v1alpha.types import recommendation_service -from google.longrunning import operations_pb2 # type: ignore - -from .base import RecommendationServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class RecommendationServiceRestInterceptor: - """Interceptor for RecommendationService. - - 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 RecommendationServiceRestTransport. - - .. code-block:: python - class MyCustomRecommendationServiceInterceptor(RecommendationServiceRestInterceptor): - def pre_recommend(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_recommend(self, response): - logging.log(f"Received response: {response}") - return response - - transport = RecommendationServiceRestTransport(interceptor=MyCustomRecommendationServiceInterceptor()) - client = RecommendationServiceClient(transport=transport) - - - """ - def pre_recommend(self, request: recommendation_service.RecommendRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[recommendation_service.RecommendRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for recommend - - Override in a subclass to manipulate the request or metadata - before they are sent to the RecommendationService server. - """ - return request, metadata - - def post_recommend(self, response: recommendation_service.RecommendResponse) -> recommendation_service.RecommendResponse: - """Post-rpc interceptor for recommend - - Override in a subclass to manipulate the response - after it is returned by the RecommendationService server but before - it is returned to user code. - """ - return response - - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the RecommendationService 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 RecommendationService server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the RecommendationService 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 RecommendationService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class RecommendationServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: RecommendationServiceRestInterceptor - - -class RecommendationServiceRestTransport(RecommendationServiceTransport): - """REST backend transport for RecommendationService. - - Service for making recommendations. - - 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 = 'discoveryengine.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[RecommendationServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or RecommendationServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _Recommend(RecommendationServiceRestStub): - def __hash__(self): - return hash("Recommend") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: recommendation_service.RecommendRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> recommendation_service.RecommendResponse: - r"""Call the recommend method over HTTP. - - Args: - request (~.recommendation_service.RecommendRequest): - The request object. Request message for Recommend method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.recommendation_service.RecommendResponse: - Response message for Recommend - method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1alpha/{serving_config=projects/*/locations/*/dataStores/*/servingConfigs/*}:recommend', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1alpha/{serving_config=projects/*/locations/*/collections/*/dataStores/*/servingConfigs/*}:recommend', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1alpha/{serving_config=projects/*/locations/*/collections/*/engines/*/servingConfigs/*}:recommend', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_recommend(request, metadata) - pb_request = recommendation_service.RecommendRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = recommendation_service.RecommendResponse() - pb_resp = recommendation_service.RecommendResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_recommend(resp) - return resp - - @property - def recommend(self) -> Callable[ - [recommendation_service.RecommendRequest], - recommendation_service.RecommendResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._Recommend(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(RecommendationServiceRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(RecommendationServiceRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'RecommendationServiceRestTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/__init__.py deleted file mode 100644 index 4e9455a921b6..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import SchemaServiceClient -from .async_client import SchemaServiceAsyncClient - -__all__ = ( - 'SchemaServiceClient', - 'SchemaServiceAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/async_client.py deleted file mode 100644 index d31db699cf92..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/async_client.py +++ /dev/null @@ -1,902 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.discoveryengine_v1alpha import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.discoveryengine_v1alpha.services.schema_service import pagers -from google.cloud.discoveryengine_v1alpha.types import schema -from google.cloud.discoveryengine_v1alpha.types import schema as gcd_schema -from google.cloud.discoveryengine_v1alpha.types import schema_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from .transports.base import SchemaServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import SchemaServiceGrpcAsyncIOTransport -from .client import SchemaServiceClient - - -class SchemaServiceAsyncClient: - """Service for managing - [Schema][google.cloud.discoveryengine.v1alpha.Schema]s. - """ - - _client: SchemaServiceClient - - DEFAULT_ENDPOINT = SchemaServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SchemaServiceClient.DEFAULT_MTLS_ENDPOINT - - data_store_path = staticmethod(SchemaServiceClient.data_store_path) - parse_data_store_path = staticmethod(SchemaServiceClient.parse_data_store_path) - schema_path = staticmethod(SchemaServiceClient.schema_path) - parse_schema_path = staticmethod(SchemaServiceClient.parse_schema_path) - common_billing_account_path = staticmethod(SchemaServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(SchemaServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(SchemaServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(SchemaServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(SchemaServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(SchemaServiceClient.parse_common_organization_path) - common_project_path = staticmethod(SchemaServiceClient.common_project_path) - parse_common_project_path = staticmethod(SchemaServiceClient.parse_common_project_path) - common_location_path = staticmethod(SchemaServiceClient.common_location_path) - parse_common_location_path = staticmethod(SchemaServiceClient.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: - SchemaServiceAsyncClient: The constructed client. - """ - return SchemaServiceClient.from_service_account_info.__func__(SchemaServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SchemaServiceAsyncClient: The constructed client. - """ - return SchemaServiceClient.from_service_account_file.__func__(SchemaServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return SchemaServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> SchemaServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SchemaServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(SchemaServiceClient).get_transport_class, type(SchemaServiceClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, SchemaServiceTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the schema 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 (Union[str, ~.SchemaServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = SchemaServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def get_schema(self, - request: Optional[Union[schema_service.GetSchemaRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> schema.Schema: - r"""Gets a [Schema][google.cloud.discoveryengine.v1alpha.Schema]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - async def sample_get_schema(): - # Create a client - client = discoveryengine_v1alpha.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.GetSchemaRequest( - name="name_value", - ) - - # Make the request - response = await client.get_schema(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.GetSchemaRequest, dict]]): - The request object. Request message for - [SchemaService.GetSchema][google.cloud.discoveryengine.v1alpha.SchemaService.GetSchema] - method. - name (:class:`str`): - Required. The full resource name of the schema, in the - format of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1alpha.types.Schema: - Defines the structure and layout of a - type of document data. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = schema_service.GetSchemaRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_schema, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_schemas(self, - request: Optional[Union[schema_service.ListSchemasRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSchemasAsyncPager: - r"""Gets a list of - [Schema][google.cloud.discoveryengine.v1alpha.Schema]s. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - async def sample_list_schemas(): - # Create a client - client = discoveryengine_v1alpha.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.ListSchemasRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_schemas(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.ListSchemasRequest, dict]]): - The request object. Request message for - [SchemaService.ListSchemas][google.cloud.discoveryengine.v1alpha.SchemaService.ListSchemas] - method. - parent (:class:`str`): - Required. The parent data store resource name, in the - format of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1alpha.services.schema_service.pagers.ListSchemasAsyncPager: - Response message for - [SchemaService.ListSchemas][google.cloud.discoveryengine.v1alpha.SchemaService.ListSchemas] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = schema_service.ListSchemasRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_schemas, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListSchemasAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_schema(self, - request: Optional[Union[schema_service.CreateSchemaRequest, dict]] = None, - *, - parent: Optional[str] = None, - schema: Optional[gcd_schema.Schema] = None, - schema_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a [Schema][google.cloud.discoveryengine.v1alpha.Schema]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - async def sample_create_schema(): - # Create a client - client = discoveryengine_v1alpha.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.CreateSchemaRequest( - parent="parent_value", - schema_id="schema_id_value", - ) - - # Make the request - operation = client.create_schema(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.CreateSchemaRequest, dict]]): - The request object. Request message for - [SchemaService.CreateSchema][google.cloud.discoveryengine.v1alpha.SchemaService.CreateSchema] - method. - parent (:class:`str`): - Required. The parent data store resource name, in the - format of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - schema (:class:`google.cloud.discoveryengine_v1alpha.types.Schema`): - Required. The - [Schema][google.cloud.discoveryengine.v1alpha.Schema] to - create. - - This corresponds to the ``schema`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - schema_id (:class:`str`): - Required. The ID to use for the - [Schema][google.cloud.discoveryengine.v1alpha.Schema], - which will become the final component of the - [Schema.name][google.cloud.discoveryengine.v1alpha.Schema.name]. - - This field should conform to - `RFC-1034 `__ - standard with a length limit of 63 characters. - - This corresponds to the ``schema_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.discoveryengine_v1alpha.types.Schema` - Defines the structure and layout of a type of document - data. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, schema, schema_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = schema_service.CreateSchemaRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if schema is not None: - request.schema = schema - if schema_id is not None: - request.schema_id = schema_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_schema, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - gcd_schema.Schema, - metadata_type=schema_service.CreateSchemaMetadata, - ) - - # Done; return the response. - return response - - async def update_schema(self, - request: Optional[Union[schema_service.UpdateSchemaRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates a [Schema][google.cloud.discoveryengine.v1alpha.Schema]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - async def sample_update_schema(): - # Create a client - client = discoveryengine_v1alpha.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.UpdateSchemaRequest( - ) - - # Make the request - operation = client.update_schema(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.UpdateSchemaRequest, dict]]): - The request object. Request message for - [SchemaService.UpdateSchema][google.cloud.discoveryengine.v1alpha.SchemaService.UpdateSchema] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.discoveryengine_v1alpha.types.Schema` - Defines the structure and layout of a type of document - data. - - """ - # Create or coerce a protobuf request object. - request = schema_service.UpdateSchemaRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_schema, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("schema.name", request.schema.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - schema.Schema, - metadata_type=schema_service.UpdateSchemaMetadata, - ) - - # Done; return the response. - return response - - async def delete_schema(self, - request: Optional[Union[schema_service.DeleteSchemaRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a [Schema][google.cloud.discoveryengine.v1alpha.Schema]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - async def sample_delete_schema(): - # Create a client - client = discoveryengine_v1alpha.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.DeleteSchemaRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_schema(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.DeleteSchemaRequest, dict]]): - The request object. Request message for - [SchemaService.DeleteSchema][google.cloud.discoveryengine.v1alpha.SchemaService.DeleteSchema] - method. - name (:class:`str`): - Required. The full resource name of the schema, in the - format of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = schema_service.DeleteSchemaRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_schema, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=schema_service.DeleteSchemaMetadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "SchemaServiceAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "SchemaServiceAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/client.py deleted file mode 100644 index 760fb509e9f3..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/client.py +++ /dev/null @@ -1,1119 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.discoveryengine_v1alpha import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.discoveryengine_v1alpha.services.schema_service import pagers -from google.cloud.discoveryengine_v1alpha.types import schema -from google.cloud.discoveryengine_v1alpha.types import schema as gcd_schema -from google.cloud.discoveryengine_v1alpha.types import schema_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from .transports.base import SchemaServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SchemaServiceGrpcTransport -from .transports.grpc_asyncio import SchemaServiceGrpcAsyncIOTransport -from .transports.rest import SchemaServiceRestTransport - - -class SchemaServiceClientMeta(type): - """Metaclass for the SchemaService 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[SchemaServiceTransport]] - _transport_registry["grpc"] = SchemaServiceGrpcTransport - _transport_registry["grpc_asyncio"] = SchemaServiceGrpcAsyncIOTransport - _transport_registry["rest"] = SchemaServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[SchemaServiceTransport]: - """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 SchemaServiceClient(metaclass=SchemaServiceClientMeta): - """Service for managing - [Schema][google.cloud.discoveryengine.v1alpha.Schema]s. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SchemaServiceClient: 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: - SchemaServiceClient: 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) -> SchemaServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SchemaServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def data_store_path(project: str,location: str,data_store: str,) -> str: - """Returns a fully-qualified data_store string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) - - @staticmethod - def parse_data_store_path(path: str) -> Dict[str,str]: - """Parses a data_store path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def schema_path(project: str,location: str,data_store: str,schema: str,) -> str: - """Returns a fully-qualified schema string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}/schemas/{schema}".format(project=project, location=location, data_store=data_store, schema=schema, ) - - @staticmethod - def parse_schema_path(path: str) -> Dict[str,str]: - """Parses a schema path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/schemas/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, SchemaServiceTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the schema 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 (Union[str, SchemaServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, SchemaServiceTransport): - # transport is a SchemaServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def get_schema(self, - request: Optional[Union[schema_service.GetSchemaRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> schema.Schema: - r"""Gets a [Schema][google.cloud.discoveryengine.v1alpha.Schema]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - def sample_get_schema(): - # Create a client - client = discoveryengine_v1alpha.SchemaServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.GetSchemaRequest( - name="name_value", - ) - - # Make the request - response = client.get_schema(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1alpha.types.GetSchemaRequest, dict]): - The request object. Request message for - [SchemaService.GetSchema][google.cloud.discoveryengine.v1alpha.SchemaService.GetSchema] - method. - name (str): - Required. The full resource name of the schema, in the - format of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1alpha.types.Schema: - Defines the structure and layout of a - type of document data. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a schema_service.GetSchemaRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, schema_service.GetSchemaRequest): - request = schema_service.GetSchemaRequest(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_schema] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_schemas(self, - request: Optional[Union[schema_service.ListSchemasRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSchemasPager: - r"""Gets a list of - [Schema][google.cloud.discoveryengine.v1alpha.Schema]s. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - def sample_list_schemas(): - # Create a client - client = discoveryengine_v1alpha.SchemaServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.ListSchemasRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_schemas(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1alpha.types.ListSchemasRequest, dict]): - The request object. Request message for - [SchemaService.ListSchemas][google.cloud.discoveryengine.v1alpha.SchemaService.ListSchemas] - method. - parent (str): - Required. The parent data store resource name, in the - format of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1alpha.services.schema_service.pagers.ListSchemasPager: - Response message for - [SchemaService.ListSchemas][google.cloud.discoveryengine.v1alpha.SchemaService.ListSchemas] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a schema_service.ListSchemasRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, schema_service.ListSchemasRequest): - request = schema_service.ListSchemasRequest(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_schemas] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListSchemasPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_schema(self, - request: Optional[Union[schema_service.CreateSchemaRequest, dict]] = None, - *, - parent: Optional[str] = None, - schema: Optional[gcd_schema.Schema] = None, - schema_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a [Schema][google.cloud.discoveryengine.v1alpha.Schema]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - def sample_create_schema(): - # Create a client - client = discoveryengine_v1alpha.SchemaServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.CreateSchemaRequest( - parent="parent_value", - schema_id="schema_id_value", - ) - - # Make the request - operation = client.create_schema(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1alpha.types.CreateSchemaRequest, dict]): - The request object. Request message for - [SchemaService.CreateSchema][google.cloud.discoveryengine.v1alpha.SchemaService.CreateSchema] - method. - parent (str): - Required. The parent data store resource name, in the - format of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - schema (google.cloud.discoveryengine_v1alpha.types.Schema): - Required. The - [Schema][google.cloud.discoveryengine.v1alpha.Schema] to - create. - - This corresponds to the ``schema`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - schema_id (str): - Required. The ID to use for the - [Schema][google.cloud.discoveryengine.v1alpha.Schema], - which will become the final component of the - [Schema.name][google.cloud.discoveryengine.v1alpha.Schema.name]. - - This field should conform to - `RFC-1034 `__ - standard with a length limit of 63 characters. - - This corresponds to the ``schema_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.discoveryengine_v1alpha.types.Schema` - Defines the structure and layout of a type of document - data. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, schema, schema_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a schema_service.CreateSchemaRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, schema_service.CreateSchemaRequest): - request = schema_service.CreateSchemaRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if schema is not None: - request.schema = schema - if schema_id is not None: - request.schema_id = schema_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_schema] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - gcd_schema.Schema, - metadata_type=schema_service.CreateSchemaMetadata, - ) - - # Done; return the response. - return response - - def update_schema(self, - request: Optional[Union[schema_service.UpdateSchemaRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates a [Schema][google.cloud.discoveryengine.v1alpha.Schema]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - def sample_update_schema(): - # Create a client - client = discoveryengine_v1alpha.SchemaServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.UpdateSchemaRequest( - ) - - # Make the request - operation = client.update_schema(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1alpha.types.UpdateSchemaRequest, dict]): - The request object. Request message for - [SchemaService.UpdateSchema][google.cloud.discoveryengine.v1alpha.SchemaService.UpdateSchema] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.discoveryengine_v1alpha.types.Schema` - Defines the structure and layout of a type of document - data. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a schema_service.UpdateSchemaRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, schema_service.UpdateSchemaRequest): - request = schema_service.UpdateSchemaRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_schema] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("schema.name", request.schema.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - schema.Schema, - metadata_type=schema_service.UpdateSchemaMetadata, - ) - - # Done; return the response. - return response - - def delete_schema(self, - request: Optional[Union[schema_service.DeleteSchemaRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes a [Schema][google.cloud.discoveryengine.v1alpha.Schema]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - def sample_delete_schema(): - # Create a client - client = discoveryengine_v1alpha.SchemaServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.DeleteSchemaRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_schema(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1alpha.types.DeleteSchemaRequest, dict]): - The request object. Request message for - [SchemaService.DeleteSchema][google.cloud.discoveryengine.v1alpha.SchemaService.DeleteSchema] - method. - name (str): - Required. The full resource name of the schema, in the - format of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a schema_service.DeleteSchemaRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, schema_service.DeleteSchemaRequest): - request = schema_service.DeleteSchemaRequest(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_schema] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=schema_service.DeleteSchemaMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "SchemaServiceClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - - - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "SchemaServiceClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/pagers.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/pagers.py deleted file mode 100644 index 34de8e6acea7..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.discoveryengine_v1alpha.types import schema -from google.cloud.discoveryengine_v1alpha.types import schema_service - - -class ListSchemasPager: - """A pager for iterating through ``list_schemas`` requests. - - This class thinly wraps an initial - :class:`google.cloud.discoveryengine_v1alpha.types.ListSchemasResponse` object, and - provides an ``__iter__`` method to iterate through its - ``schemas`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListSchemas`` requests and continue to iterate - through the ``schemas`` field on the - corresponding responses. - - All the usual :class:`google.cloud.discoveryengine_v1alpha.types.ListSchemasResponse` - 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[..., schema_service.ListSchemasResponse], - request: schema_service.ListSchemasRequest, - response: schema_service.ListSchemasResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.discoveryengine_v1alpha.types.ListSchemasRequest): - The initial request object. - response (google.cloud.discoveryengine_v1alpha.types.ListSchemasResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = schema_service.ListSchemasRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[schema_service.ListSchemasResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[schema.Schema]: - for page in self.pages: - yield from page.schemas - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSchemasAsyncPager: - """A pager for iterating through ``list_schemas`` requests. - - This class thinly wraps an initial - :class:`google.cloud.discoveryengine_v1alpha.types.ListSchemasResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``schemas`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListSchemas`` requests and continue to iterate - through the ``schemas`` field on the - corresponding responses. - - All the usual :class:`google.cloud.discoveryengine_v1alpha.types.ListSchemasResponse` - 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[schema_service.ListSchemasResponse]], - request: schema_service.ListSchemasRequest, - response: schema_service.ListSchemasResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.discoveryengine_v1alpha.types.ListSchemasRequest): - The initial request object. - response (google.cloud.discoveryengine_v1alpha.types.ListSchemasResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = schema_service.ListSchemasRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[schema_service.ListSchemasResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[schema.Schema]: - async def async_generator(): - async for page in self.pages: - for response in page.schemas: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/__init__.py deleted file mode 100644 index d5ebd14e657b..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import SchemaServiceTransport -from .grpc import SchemaServiceGrpcTransport -from .grpc_asyncio import SchemaServiceGrpcAsyncIOTransport -from .rest import SchemaServiceRestTransport -from .rest import SchemaServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SchemaServiceTransport]] -_transport_registry['grpc'] = SchemaServiceGrpcTransport -_transport_registry['grpc_asyncio'] = SchemaServiceGrpcAsyncIOTransport -_transport_registry['rest'] = SchemaServiceRestTransport - -__all__ = ( - 'SchemaServiceTransport', - 'SchemaServiceGrpcTransport', - 'SchemaServiceGrpcAsyncIOTransport', - 'SchemaServiceRestTransport', - 'SchemaServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/base.py deleted file mode 100644 index 74feb3ddf1e2..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/base.py +++ /dev/null @@ -1,231 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.discoveryengine_v1alpha import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.discoveryengine_v1alpha.types import schema -from google.cloud.discoveryengine_v1alpha.types import schema_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class SchemaServiceTransport(abc.ABC): - """Abstract transport class for SchemaService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'discoveryengine.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.get_schema: gapic_v1.method.wrap_method( - self.get_schema, - default_timeout=None, - client_info=client_info, - ), - self.list_schemas: gapic_v1.method.wrap_method( - self.list_schemas, - default_timeout=None, - client_info=client_info, - ), - self.create_schema: gapic_v1.method.wrap_method( - self.create_schema, - default_timeout=None, - client_info=client_info, - ), - self.update_schema: gapic_v1.method.wrap_method( - self.update_schema, - default_timeout=None, - client_info=client_info, - ), - self.delete_schema: gapic_v1.method.wrap_method( - self.delete_schema, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def get_schema(self) -> Callable[ - [schema_service.GetSchemaRequest], - Union[ - schema.Schema, - Awaitable[schema.Schema] - ]]: - raise NotImplementedError() - - @property - def list_schemas(self) -> Callable[ - [schema_service.ListSchemasRequest], - Union[ - schema_service.ListSchemasResponse, - Awaitable[schema_service.ListSchemasResponse] - ]]: - raise NotImplementedError() - - @property - def create_schema(self) -> Callable[ - [schema_service.CreateSchemaRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_schema(self) -> Callable[ - [schema_service.UpdateSchemaRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_schema(self) -> Callable[ - [schema_service.DeleteSchemaRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'SchemaServiceTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/grpc.py deleted file mode 100644 index caa7905828f2..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/grpc.py +++ /dev/null @@ -1,427 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.discoveryengine_v1alpha.types import schema -from google.cloud.discoveryengine_v1alpha.types import schema_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import SchemaServiceTransport, DEFAULT_CLIENT_INFO - - -class SchemaServiceGrpcTransport(SchemaServiceTransport): - """gRPC backend transport for SchemaService. - - Service for managing - [Schema][google.cloud.discoveryengine.v1alpha.Schema]s. - - 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def get_schema(self) -> Callable[ - [schema_service.GetSchemaRequest], - schema.Schema]: - r"""Return a callable for the get schema method over gRPC. - - Gets a [Schema][google.cloud.discoveryengine.v1alpha.Schema]. - - Returns: - Callable[[~.GetSchemaRequest], - ~.Schema]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_schema' not in self._stubs: - self._stubs['get_schema'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.SchemaService/GetSchema', - request_serializer=schema_service.GetSchemaRequest.serialize, - response_deserializer=schema.Schema.deserialize, - ) - return self._stubs['get_schema'] - - @property - def list_schemas(self) -> Callable[ - [schema_service.ListSchemasRequest], - schema_service.ListSchemasResponse]: - r"""Return a callable for the list schemas method over gRPC. - - Gets a list of - [Schema][google.cloud.discoveryengine.v1alpha.Schema]s. - - Returns: - Callable[[~.ListSchemasRequest], - ~.ListSchemasResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_schemas' not in self._stubs: - self._stubs['list_schemas'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.SchemaService/ListSchemas', - request_serializer=schema_service.ListSchemasRequest.serialize, - response_deserializer=schema_service.ListSchemasResponse.deserialize, - ) - return self._stubs['list_schemas'] - - @property - def create_schema(self) -> Callable[ - [schema_service.CreateSchemaRequest], - operations_pb2.Operation]: - r"""Return a callable for the create schema method over gRPC. - - Creates a [Schema][google.cloud.discoveryengine.v1alpha.Schema]. - - Returns: - Callable[[~.CreateSchemaRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_schema' not in self._stubs: - self._stubs['create_schema'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.SchemaService/CreateSchema', - request_serializer=schema_service.CreateSchemaRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_schema'] - - @property - def update_schema(self) -> Callable[ - [schema_service.UpdateSchemaRequest], - operations_pb2.Operation]: - r"""Return a callable for the update schema method over gRPC. - - Updates a [Schema][google.cloud.discoveryengine.v1alpha.Schema]. - - Returns: - Callable[[~.UpdateSchemaRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_schema' not in self._stubs: - self._stubs['update_schema'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.SchemaService/UpdateSchema', - request_serializer=schema_service.UpdateSchemaRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_schema'] - - @property - def delete_schema(self) -> Callable[ - [schema_service.DeleteSchemaRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete schema method over gRPC. - - Deletes a [Schema][google.cloud.discoveryengine.v1alpha.Schema]. - - Returns: - Callable[[~.DeleteSchemaRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_schema' not in self._stubs: - self._stubs['delete_schema'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.SchemaService/DeleteSchema', - request_serializer=schema_service.DeleteSchemaRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_schema'] - - def close(self): - self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'SchemaServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/grpc_asyncio.py deleted file mode 100644 index ded95061acb4..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,426 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.discoveryengine_v1alpha.types import schema -from google.cloud.discoveryengine_v1alpha.types import schema_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import SchemaServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import SchemaServiceGrpcTransport - - -class SchemaServiceGrpcAsyncIOTransport(SchemaServiceTransport): - """gRPC AsyncIO backend transport for SchemaService. - - Service for managing - [Schema][google.cloud.discoveryengine.v1alpha.Schema]s. - - 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def get_schema(self) -> Callable[ - [schema_service.GetSchemaRequest], - Awaitable[schema.Schema]]: - r"""Return a callable for the get schema method over gRPC. - - Gets a [Schema][google.cloud.discoveryengine.v1alpha.Schema]. - - Returns: - Callable[[~.GetSchemaRequest], - Awaitable[~.Schema]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_schema' not in self._stubs: - self._stubs['get_schema'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.SchemaService/GetSchema', - request_serializer=schema_service.GetSchemaRequest.serialize, - response_deserializer=schema.Schema.deserialize, - ) - return self._stubs['get_schema'] - - @property - def list_schemas(self) -> Callable[ - [schema_service.ListSchemasRequest], - Awaitable[schema_service.ListSchemasResponse]]: - r"""Return a callable for the list schemas method over gRPC. - - Gets a list of - [Schema][google.cloud.discoveryengine.v1alpha.Schema]s. - - Returns: - Callable[[~.ListSchemasRequest], - Awaitable[~.ListSchemasResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_schemas' not in self._stubs: - self._stubs['list_schemas'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.SchemaService/ListSchemas', - request_serializer=schema_service.ListSchemasRequest.serialize, - response_deserializer=schema_service.ListSchemasResponse.deserialize, - ) - return self._stubs['list_schemas'] - - @property - def create_schema(self) -> Callable[ - [schema_service.CreateSchemaRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create schema method over gRPC. - - Creates a [Schema][google.cloud.discoveryengine.v1alpha.Schema]. - - Returns: - Callable[[~.CreateSchemaRequest], - 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_schema' not in self._stubs: - self._stubs['create_schema'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.SchemaService/CreateSchema', - request_serializer=schema_service.CreateSchemaRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_schema'] - - @property - def update_schema(self) -> Callable[ - [schema_service.UpdateSchemaRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update schema method over gRPC. - - Updates a [Schema][google.cloud.discoveryengine.v1alpha.Schema]. - - Returns: - Callable[[~.UpdateSchemaRequest], - 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_schema' not in self._stubs: - self._stubs['update_schema'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.SchemaService/UpdateSchema', - request_serializer=schema_service.UpdateSchemaRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_schema'] - - @property - def delete_schema(self) -> Callable[ - [schema_service.DeleteSchemaRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete schema method over gRPC. - - Deletes a [Schema][google.cloud.discoveryengine.v1alpha.Schema]. - - Returns: - Callable[[~.DeleteSchemaRequest], - 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_schema' not in self._stubs: - self._stubs['delete_schema'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.SchemaService/DeleteSchema', - request_serializer=schema_service.DeleteSchemaRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_schema'] - - def close(self): - return self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - -__all__ = ( - 'SchemaServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/rest.py deleted file mode 100644 index 717527b50048..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/schema_service/transports/rest.py +++ /dev/null @@ -1,1192 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.cloud.location import locations_pb2 # type: ignore -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.discoveryengine_v1alpha.types import schema -from google.cloud.discoveryengine_v1alpha.types import schema_service -from google.longrunning import operations_pb2 # type: ignore - -from .base import SchemaServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class SchemaServiceRestInterceptor: - """Interceptor for SchemaService. - - 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 SchemaServiceRestTransport. - - .. code-block:: python - class MyCustomSchemaServiceInterceptor(SchemaServiceRestInterceptor): - def pre_create_schema(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_schema(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_schema(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_schema(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_schema(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_schema(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_schemas(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_schemas(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_schema(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_schema(self, response): - logging.log(f"Received response: {response}") - return response - - transport = SchemaServiceRestTransport(interceptor=MyCustomSchemaServiceInterceptor()) - client = SchemaServiceClient(transport=transport) - - - """ - def pre_create_schema(self, request: schema_service.CreateSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[schema_service.CreateSchemaRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_schema - - Override in a subclass to manipulate the request or metadata - before they are sent to the SchemaService server. - """ - return request, metadata - - def post_create_schema(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_schema - - Override in a subclass to manipulate the response - after it is returned by the SchemaService server but before - it is returned to user code. - """ - return response - def pre_delete_schema(self, request: schema_service.DeleteSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[schema_service.DeleteSchemaRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_schema - - Override in a subclass to manipulate the request or metadata - before they are sent to the SchemaService server. - """ - return request, metadata - - def post_delete_schema(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_schema - - Override in a subclass to manipulate the response - after it is returned by the SchemaService server but before - it is returned to user code. - """ - return response - def pre_get_schema(self, request: schema_service.GetSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[schema_service.GetSchemaRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_schema - - Override in a subclass to manipulate the request or metadata - before they are sent to the SchemaService server. - """ - return request, metadata - - def post_get_schema(self, response: schema.Schema) -> schema.Schema: - """Post-rpc interceptor for get_schema - - Override in a subclass to manipulate the response - after it is returned by the SchemaService server but before - it is returned to user code. - """ - return response - def pre_list_schemas(self, request: schema_service.ListSchemasRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[schema_service.ListSchemasRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_schemas - - Override in a subclass to manipulate the request or metadata - before they are sent to the SchemaService server. - """ - return request, metadata - - def post_list_schemas(self, response: schema_service.ListSchemasResponse) -> schema_service.ListSchemasResponse: - """Post-rpc interceptor for list_schemas - - Override in a subclass to manipulate the response - after it is returned by the SchemaService server but before - it is returned to user code. - """ - return response - def pre_update_schema(self, request: schema_service.UpdateSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[schema_service.UpdateSchemaRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_schema - - Override in a subclass to manipulate the request or metadata - before they are sent to the SchemaService server. - """ - return request, metadata - - def post_update_schema(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_schema - - Override in a subclass to manipulate the response - after it is returned by the SchemaService server but before - it is returned to user code. - """ - return response - - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the SchemaService 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 SchemaService server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the SchemaService 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 SchemaService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class SchemaServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: SchemaServiceRestInterceptor - - -class SchemaServiceRestTransport(SchemaServiceTransport): - """REST backend transport for SchemaService. - - Service for managing - [Schema][google.cloud.discoveryengine.v1alpha.Schema]s. - - 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 = 'discoveryengine.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[SchemaServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or SchemaServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*}/operations', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1alpha") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _CreateSchema(SchemaServiceRestStub): - def __hash__(self): - return hash("CreateSchema") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "schemaId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: schema_service.CreateSchemaRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create schema method over HTTP. - - Args: - request (~.schema_service.CreateSchemaRequest): - The request object. Request message for - [SchemaService.CreateSchema][google.cloud.discoveryengine.v1alpha.SchemaService.CreateSchema] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1alpha/{parent=projects/*/locations/*/dataStores/*}/schemas', - 'body': 'schema', - }, -{ - 'method': 'post', - 'uri': '/v1alpha/{parent=projects/*/locations/*/collections/*/dataStores/*}/schemas', - 'body': 'schema', - }, - ] - request, metadata = self._interceptor.pre_create_schema(request, metadata) - pb_request = schema_service.CreateSchemaRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_schema(resp) - return resp - - class _DeleteSchema(SchemaServiceRestStub): - def __hash__(self): - return hash("DeleteSchema") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: schema_service.DeleteSchemaRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete schema method over HTTP. - - Args: - request (~.schema_service.DeleteSchemaRequest): - The request object. Request message for - [SchemaService.DeleteSchema][google.cloud.discoveryengine.v1alpha.SchemaService.DeleteSchema] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/schemas/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_schema(request, metadata) - pb_request = schema_service.DeleteSchemaRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_schema(resp) - return resp - - class _GetSchema(SchemaServiceRestStub): - def __hash__(self): - return hash("GetSchema") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: schema_service.GetSchemaRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> schema.Schema: - r"""Call the get schema method over HTTP. - - Args: - request (~.schema_service.GetSchemaRequest): - The request object. Request message for - [SchemaService.GetSchema][google.cloud.discoveryengine.v1alpha.SchemaService.GetSchema] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.schema.Schema: - Defines the structure and layout of a - type of document data. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/schemas/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}', - }, - ] - request, metadata = self._interceptor.pre_get_schema(request, metadata) - pb_request = schema_service.GetSchemaRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = schema.Schema() - pb_resp = schema.Schema.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_schema(resp) - return resp - - class _ListSchemas(SchemaServiceRestStub): - def __hash__(self): - return hash("ListSchemas") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: schema_service.ListSchemasRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> schema_service.ListSchemasResponse: - r"""Call the list schemas method over HTTP. - - Args: - request (~.schema_service.ListSchemasRequest): - The request object. Request message for - [SchemaService.ListSchemas][google.cloud.discoveryengine.v1alpha.SchemaService.ListSchemas] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.schema_service.ListSchemasResponse: - Response message for - [SchemaService.ListSchemas][google.cloud.discoveryengine.v1alpha.SchemaService.ListSchemas] - method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{parent=projects/*/locations/*/dataStores/*}/schemas', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{parent=projects/*/locations/*/collections/*/dataStores/*}/schemas', - }, - ] - request, metadata = self._interceptor.pre_list_schemas(request, metadata) - pb_request = schema_service.ListSchemasRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = schema_service.ListSchemasResponse() - pb_resp = schema_service.ListSchemasResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_schemas(resp) - return resp - - class _UpdateSchema(SchemaServiceRestStub): - def __hash__(self): - return hash("UpdateSchema") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: schema_service.UpdateSchemaRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update schema method over HTTP. - - Args: - request (~.schema_service.UpdateSchemaRequest): - The request object. Request message for - [SchemaService.UpdateSchema][google.cloud.discoveryengine.v1alpha.SchemaService.UpdateSchema] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1alpha/{schema.name=projects/*/locations/*/dataStores/*/schemas/*}', - 'body': 'schema', - }, -{ - 'method': 'patch', - 'uri': '/v1alpha/{schema.name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}', - 'body': 'schema', - }, - ] - request, metadata = self._interceptor.pre_update_schema(request, metadata) - pb_request = schema_service.UpdateSchemaRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_schema(resp) - return resp - - @property - def create_schema(self) -> Callable[ - [schema_service.CreateSchemaRequest], - 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._CreateSchema(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_schema(self) -> Callable[ - [schema_service.DeleteSchemaRequest], - 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._DeleteSchema(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_schema(self) -> Callable[ - [schema_service.GetSchemaRequest], - schema.Schema]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetSchema(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_schemas(self) -> Callable[ - [schema_service.ListSchemasRequest], - schema_service.ListSchemasResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListSchemas(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_schema(self) -> Callable[ - [schema_service.UpdateSchemaRequest], - 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._UpdateSchema(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(SchemaServiceRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(SchemaServiceRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'SchemaServiceRestTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/__init__.py deleted file mode 100644 index 0355170e3569..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import SearchServiceClient -from .async_client import SearchServiceAsyncClient - -__all__ = ( - 'SearchServiceClient', - 'SearchServiceAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/async_client.py deleted file mode 100644 index ec796c60b958..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/async_client.py +++ /dev/null @@ -1,402 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.discoveryengine_v1alpha import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.discoveryengine_v1alpha.services.search_service import pagers -from google.cloud.discoveryengine_v1alpha.types import search_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport -from .client import SearchServiceClient - - -class SearchServiceAsyncClient: - """Service for search.""" - - _client: SearchServiceClient - - DEFAULT_ENDPOINT = SearchServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SearchServiceClient.DEFAULT_MTLS_ENDPOINT - - branch_path = staticmethod(SearchServiceClient.branch_path) - parse_branch_path = staticmethod(SearchServiceClient.parse_branch_path) - document_path = staticmethod(SearchServiceClient.document_path) - parse_document_path = staticmethod(SearchServiceClient.parse_document_path) - serving_config_path = staticmethod(SearchServiceClient.serving_config_path) - parse_serving_config_path = staticmethod(SearchServiceClient.parse_serving_config_path) - common_billing_account_path = staticmethod(SearchServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(SearchServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(SearchServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(SearchServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(SearchServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(SearchServiceClient.parse_common_organization_path) - common_project_path = staticmethod(SearchServiceClient.common_project_path) - parse_common_project_path = staticmethod(SearchServiceClient.parse_common_project_path) - common_location_path = staticmethod(SearchServiceClient.common_location_path) - parse_common_location_path = staticmethod(SearchServiceClient.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: - SearchServiceAsyncClient: The constructed client. - """ - return SearchServiceClient.from_service_account_info.__func__(SearchServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceAsyncClient: The constructed client. - """ - return SearchServiceClient.from_service_account_file.__func__(SearchServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return SearchServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> SearchServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SearchServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(SearchServiceClient).get_transport_class, type(SearchServiceClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, SearchServiceTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the search 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 (Union[str, ~.SearchServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = SearchServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def search(self, - request: Optional[Union[search_service.SearchRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchAsyncPager: - r"""Performs a search. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - async def sample_search(): - # Create a client - client = discoveryengine_v1alpha.SearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.SearchRequest( - serving_config="serving_config_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.SearchRequest, dict]]): - The request object. Request message for - [SearchService.Search][google.cloud.discoveryengine.v1alpha.SearchService.Search] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1alpha.services.search_service.pagers.SearchAsyncPager: - Response message for - [SearchService.Search][google.cloud.discoveryengine.v1alpha.SearchService.Search] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - request = search_service.SearchRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.search, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config", request.serving_config), - )), - ) - - # 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.SearchAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "SearchServiceAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "SearchServiceAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/client.py deleted file mode 100644 index b2fba548a734..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/client.py +++ /dev/null @@ -1,628 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.discoveryengine_v1alpha import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.discoveryengine_v1alpha.services.search_service import pagers -from google.cloud.discoveryengine_v1alpha.types import search_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SearchServiceGrpcTransport -from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport -from .transports.rest import SearchServiceRestTransport - - -class SearchServiceClientMeta(type): - """Metaclass for the SearchService 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[SearchServiceTransport]] - _transport_registry["grpc"] = SearchServiceGrpcTransport - _transport_registry["grpc_asyncio"] = SearchServiceGrpcAsyncIOTransport - _transport_registry["rest"] = SearchServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[SearchServiceTransport]: - """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 SearchServiceClient(metaclass=SearchServiceClientMeta): - """Service for search.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceClient: 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: - SearchServiceClient: 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) -> SearchServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SearchServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def branch_path(project: str,location: str,data_store: str,branch: str,) -> str: - """Returns a fully-qualified branch string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}".format(project=project, location=location, data_store=data_store, branch=branch, ) - - @staticmethod - def parse_branch_path(path: str) -> Dict[str,str]: - """Parses a branch path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def document_path(project: str,location: str,data_store: str,branch: str,document: str,) -> str: - """Returns a fully-qualified document string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) - - @staticmethod - def parse_document_path(path: str) -> Dict[str,str]: - """Parses a document path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)/documents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def serving_config_path(project: str,location: str,data_store: str,serving_config: str,) -> str: - """Returns a fully-qualified serving_config string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}/servingConfigs/{serving_config}".format(project=project, location=location, data_store=data_store, serving_config=serving_config, ) - - @staticmethod - def parse_serving_config_path(path: str) -> Dict[str,str]: - """Parses a serving_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/servingConfigs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, SearchServiceTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the search 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 (Union[str, SearchServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, SearchServiceTransport): - # transport is a SearchServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def search(self, - request: Optional[Union[search_service.SearchRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchPager: - r"""Performs a search. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - def sample_search(): - # Create a client - client = discoveryengine_v1alpha.SearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.SearchRequest( - serving_config="serving_config_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1alpha.types.SearchRequest, dict]): - The request object. Request message for - [SearchService.Search][google.cloud.discoveryengine.v1alpha.SearchService.Search] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1alpha.services.search_service.pagers.SearchPager: - Response message for - [SearchService.Search][google.cloud.discoveryengine.v1alpha.SearchService.Search] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a search_service.SearchRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, search_service.SearchRequest): - request = search_service.SearchRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.search] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config", request.serving_config), - )), - ) - - # 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.SearchPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "SearchServiceClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - - - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "SearchServiceClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/pagers.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/pagers.py deleted file mode 100644 index 40e9766339a0..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.discoveryengine_v1alpha.types import search_service - - -class SearchPager: - """A pager for iterating through ``search`` requests. - - This class thinly wraps an initial - :class:`google.cloud.discoveryengine_v1alpha.types.SearchResponse` object, and - provides an ``__iter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``Search`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.discoveryengine_v1alpha.types.SearchResponse` - 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[..., search_service.SearchResponse], - request: search_service.SearchRequest, - response: search_service.SearchResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.discoveryengine_v1alpha.types.SearchRequest): - The initial request object. - response (google.cloud.discoveryengine_v1alpha.types.SearchResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = search_service.SearchRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[search_service.SearchResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[search_service.SearchResponse.SearchResult]: - for page in self.pages: - yield from page.results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class SearchAsyncPager: - """A pager for iterating through ``search`` requests. - - This class thinly wraps an initial - :class:`google.cloud.discoveryengine_v1alpha.types.SearchResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``Search`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.discoveryengine_v1alpha.types.SearchResponse` - 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[search_service.SearchResponse]], - request: search_service.SearchRequest, - response: search_service.SearchResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.discoveryengine_v1alpha.types.SearchRequest): - The initial request object. - response (google.cloud.discoveryengine_v1alpha.types.SearchResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = search_service.SearchRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[search_service.SearchResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[search_service.SearchResponse.SearchResult]: - async def async_generator(): - async for page in self.pages: - for response in page.results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/__init__.py deleted file mode 100644 index 4282aef080e3..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import SearchServiceTransport -from .grpc import SearchServiceGrpcTransport -from .grpc_asyncio import SearchServiceGrpcAsyncIOTransport -from .rest import SearchServiceRestTransport -from .rest import SearchServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] -_transport_registry['grpc'] = SearchServiceGrpcTransport -_transport_registry['grpc_asyncio'] = SearchServiceGrpcAsyncIOTransport -_transport_registry['rest'] = SearchServiceRestTransport - -__all__ = ( - 'SearchServiceTransport', - 'SearchServiceGrpcTransport', - 'SearchServiceGrpcAsyncIOTransport', - 'SearchServiceRestTransport', - 'SearchServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/base.py deleted file mode 100644 index c87e6749ded3..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/base.py +++ /dev/null @@ -1,168 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.discoveryengine_v1alpha import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.discoveryengine_v1alpha.types import search_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class SearchServiceTransport(abc.ABC): - """Abstract transport class for SearchService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'discoveryengine.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.search: gapic_v1.method.wrap_method( - self.search, - 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 search(self) -> Callable[ - [search_service.SearchRequest], - Union[ - search_service.SearchResponse, - Awaitable[search_service.SearchResponse] - ]]: - 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 kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'SearchServiceTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/grpc.py deleted file mode 100644 index d71f5df898bc..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/grpc.py +++ /dev/null @@ -1,302 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.discoveryengine_v1alpha.types import search_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO - - -class SearchServiceGrpcTransport(SearchServiceTransport): - """gRPC backend transport for SearchService. - - Service for search. - - 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def search(self) -> Callable[ - [search_service.SearchRequest], - search_service.SearchResponse]: - r"""Return a callable for the search method over gRPC. - - Performs a search. - - Returns: - Callable[[~.SearchRequest], - ~.SearchResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search' not in self._stubs: - self._stubs['search'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.SearchService/Search', - request_serializer=search_service.SearchRequest.serialize, - response_deserializer=search_service.SearchResponse.deserialize, - ) - return self._stubs['search'] - - def close(self): - self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'SearchServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/grpc_asyncio.py deleted file mode 100644 index 91340690816b..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,301 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.discoveryengine_v1alpha.types import search_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import SearchServiceGrpcTransport - - -class SearchServiceGrpcAsyncIOTransport(SearchServiceTransport): - """gRPC AsyncIO backend transport for SearchService. - - Service for search. - - 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def search(self) -> Callable[ - [search_service.SearchRequest], - Awaitable[search_service.SearchResponse]]: - r"""Return a callable for the search method over gRPC. - - Performs a search. - - Returns: - Callable[[~.SearchRequest], - Awaitable[~.SearchResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search' not in self._stubs: - self._stubs['search'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.SearchService/Search', - request_serializer=search_service.SearchRequest.serialize, - response_deserializer=search_service.SearchResponse.deserialize, - ) - return self._stubs['search'] - - def close(self): - return self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - -__all__ = ( - 'SearchServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/rest.py deleted file mode 100644 index 8e4ca6d4d16e..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/search_service/transports/rest.py +++ /dev/null @@ -1,581 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.cloud.location import locations_pb2 # type: ignore -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.discoveryengine_v1alpha.types import search_service -from google.longrunning import operations_pb2 # type: ignore - -from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class SearchServiceRestInterceptor: - """Interceptor for SearchService. - - 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 SearchServiceRestTransport. - - .. code-block:: python - class MyCustomSearchServiceInterceptor(SearchServiceRestInterceptor): - def pre_search(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_search(self, response): - logging.log(f"Received response: {response}") - return response - - transport = SearchServiceRestTransport(interceptor=MyCustomSearchServiceInterceptor()) - client = SearchServiceClient(transport=transport) - - - """ - def pre_search(self, request: search_service.SearchRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[search_service.SearchRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for search - - Override in a subclass to manipulate the request or metadata - before they are sent to the SearchService server. - """ - return request, metadata - - def post_search(self, response: search_service.SearchResponse) -> search_service.SearchResponse: - """Post-rpc interceptor for search - - Override in a subclass to manipulate the response - after it is returned by the SearchService server but before - it is returned to user code. - """ - return response - - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the SearchService 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 SearchService server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the SearchService 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 SearchService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class SearchServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: SearchServiceRestInterceptor - - -class SearchServiceRestTransport(SearchServiceTransport): - """REST backend transport for SearchService. - - Service for search. - - 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 = 'discoveryengine.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[SearchServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or SearchServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _Search(SearchServiceRestStub): - def __hash__(self): - return hash("Search") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: search_service.SearchRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> search_service.SearchResponse: - r"""Call the search method over HTTP. - - Args: - request (~.search_service.SearchRequest): - The request object. Request message for - [SearchService.Search][google.cloud.discoveryengine.v1alpha.SearchService.Search] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.search_service.SearchResponse: - Response message for - [SearchService.Search][google.cloud.discoveryengine.v1alpha.SearchService.Search] - method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1alpha/{serving_config=projects/*/locations/*/dataStores/*/servingConfigs/*}:search', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1alpha/{serving_config=projects/*/locations/*/collections/*/dataStores/*/servingConfigs/*}:search', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1alpha/{serving_config=projects/*/locations/*/collections/*/engines/*/servingConfigs/*}:search', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_search(request, metadata) - pb_request = search_service.SearchRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = search_service.SearchResponse() - pb_resp = search_service.SearchResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_search(resp) - return resp - - @property - def search(self) -> Callable[ - [search_service.SearchRequest], - search_service.SearchResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._Search(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(SearchServiceRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(SearchServiceRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'SearchServiceRestTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/__init__.py deleted file mode 100644 index f7c959fea4c1..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import SiteSearchEngineServiceClient -from .async_client import SiteSearchEngineServiceAsyncClient - -__all__ = ( - 'SiteSearchEngineServiceClient', - 'SiteSearchEngineServiceAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/async_client.py deleted file mode 100644 index 717467934518..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/async_client.py +++ /dev/null @@ -1,401 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.discoveryengine_v1alpha import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.discoveryengine_v1alpha.types import site_search_engine_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .transports.base import SiteSearchEngineServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import SiteSearchEngineServiceGrpcAsyncIOTransport -from .client import SiteSearchEngineServiceClient - - -class SiteSearchEngineServiceAsyncClient: - """Service for managing site search related resources.""" - - _client: SiteSearchEngineServiceClient - - DEFAULT_ENDPOINT = SiteSearchEngineServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SiteSearchEngineServiceClient.DEFAULT_MTLS_ENDPOINT - - site_search_engine_path = staticmethod(SiteSearchEngineServiceClient.site_search_engine_path) - parse_site_search_engine_path = staticmethod(SiteSearchEngineServiceClient.parse_site_search_engine_path) - common_billing_account_path = staticmethod(SiteSearchEngineServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(SiteSearchEngineServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(SiteSearchEngineServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(SiteSearchEngineServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(SiteSearchEngineServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(SiteSearchEngineServiceClient.parse_common_organization_path) - common_project_path = staticmethod(SiteSearchEngineServiceClient.common_project_path) - parse_common_project_path = staticmethod(SiteSearchEngineServiceClient.parse_common_project_path) - common_location_path = staticmethod(SiteSearchEngineServiceClient.common_location_path) - parse_common_location_path = staticmethod(SiteSearchEngineServiceClient.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: - SiteSearchEngineServiceAsyncClient: The constructed client. - """ - return SiteSearchEngineServiceClient.from_service_account_info.__func__(SiteSearchEngineServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SiteSearchEngineServiceAsyncClient: The constructed client. - """ - return SiteSearchEngineServiceClient.from_service_account_file.__func__(SiteSearchEngineServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return SiteSearchEngineServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> SiteSearchEngineServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SiteSearchEngineServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(SiteSearchEngineServiceClient).get_transport_class, type(SiteSearchEngineServiceClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, SiteSearchEngineServiceTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the site search engine 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 (Union[str, ~.SiteSearchEngineServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = SiteSearchEngineServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def recrawl_uris(self, - request: Optional[Union[site_search_engine_service.RecrawlUrisRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Request on-demand recrawl for a list of URIs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - async def sample_recrawl_uris(): - # Create a client - client = discoveryengine_v1alpha.SiteSearchEngineServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.RecrawlUrisRequest( - site_search_engine="site_search_engine_value", - uris=['uris_value1', 'uris_value2'], - ) - - # Make the request - operation = client.recrawl_uris(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.RecrawlUrisRequest, dict]]): - The request object. Request message for - [SiteSearchEngineService.RecrawlUris][google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.RecrawlUris] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.discoveryengine_v1alpha.types.RecrawlUrisResponse` Response message for - [SiteSearchEngineService.RecrawlUris][google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.RecrawlUris] - method. - - """ - # Create or coerce a protobuf request object. - request = site_search_engine_service.RecrawlUrisRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.recrawl_uris, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("site_search_engine", request.site_search_engine), - )), - ) - - # 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, - site_search_engine_service.RecrawlUrisResponse, - metadata_type=site_search_engine_service.RecrawlUrisMetadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "SiteSearchEngineServiceAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "SiteSearchEngineServiceAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/client.py deleted file mode 100644 index a099d618a771..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/client.py +++ /dev/null @@ -1,609 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.discoveryengine_v1alpha import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.discoveryengine_v1alpha.types import site_search_engine_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .transports.base import SiteSearchEngineServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SiteSearchEngineServiceGrpcTransport -from .transports.grpc_asyncio import SiteSearchEngineServiceGrpcAsyncIOTransport -from .transports.rest import SiteSearchEngineServiceRestTransport - - -class SiteSearchEngineServiceClientMeta(type): - """Metaclass for the SiteSearchEngineService 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[SiteSearchEngineServiceTransport]] - _transport_registry["grpc"] = SiteSearchEngineServiceGrpcTransport - _transport_registry["grpc_asyncio"] = SiteSearchEngineServiceGrpcAsyncIOTransport - _transport_registry["rest"] = SiteSearchEngineServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[SiteSearchEngineServiceTransport]: - """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 SiteSearchEngineServiceClient(metaclass=SiteSearchEngineServiceClientMeta): - """Service for managing site search related resources.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SiteSearchEngineServiceClient: 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: - SiteSearchEngineServiceClient: 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) -> SiteSearchEngineServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SiteSearchEngineServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def site_search_engine_path(project: str,location: str,data_store: str,) -> str: - """Returns a fully-qualified site_search_engine string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}/siteSearchEngine".format(project=project, location=location, data_store=data_store, ) - - @staticmethod - def parse_site_search_engine_path(path: str) -> Dict[str,str]: - """Parses a site_search_engine path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/siteSearchEngine$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, SiteSearchEngineServiceTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the site search engine 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 (Union[str, SiteSearchEngineServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, SiteSearchEngineServiceTransport): - # transport is a SiteSearchEngineServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def recrawl_uris(self, - request: Optional[Union[site_search_engine_service.RecrawlUrisRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Request on-demand recrawl for a list of URIs. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - def sample_recrawl_uris(): - # Create a client - client = discoveryengine_v1alpha.SiteSearchEngineServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.RecrawlUrisRequest( - site_search_engine="site_search_engine_value", - uris=['uris_value1', 'uris_value2'], - ) - - # Make the request - operation = client.recrawl_uris(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1alpha.types.RecrawlUrisRequest, dict]): - The request object. Request message for - [SiteSearchEngineService.RecrawlUris][google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.RecrawlUris] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.discoveryengine_v1alpha.types.RecrawlUrisResponse` Response message for - [SiteSearchEngineService.RecrawlUris][google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.RecrawlUris] - method. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a site_search_engine_service.RecrawlUrisRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, site_search_engine_service.RecrawlUrisRequest): - request = site_search_engine_service.RecrawlUrisRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.recrawl_uris] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("site_search_engine", request.site_search_engine), - )), - ) - - # 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, - site_search_engine_service.RecrawlUrisResponse, - metadata_type=site_search_engine_service.RecrawlUrisMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "SiteSearchEngineServiceClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - - - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "SiteSearchEngineServiceClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/__init__.py deleted file mode 100644 index e5e6e692055c..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import SiteSearchEngineServiceTransport -from .grpc import SiteSearchEngineServiceGrpcTransport -from .grpc_asyncio import SiteSearchEngineServiceGrpcAsyncIOTransport -from .rest import SiteSearchEngineServiceRestTransport -from .rest import SiteSearchEngineServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SiteSearchEngineServiceTransport]] -_transport_registry['grpc'] = SiteSearchEngineServiceGrpcTransport -_transport_registry['grpc_asyncio'] = SiteSearchEngineServiceGrpcAsyncIOTransport -_transport_registry['rest'] = SiteSearchEngineServiceRestTransport - -__all__ = ( - 'SiteSearchEngineServiceTransport', - 'SiteSearchEngineServiceGrpcTransport', - 'SiteSearchEngineServiceGrpcAsyncIOTransport', - 'SiteSearchEngineServiceRestTransport', - 'SiteSearchEngineServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/base.py deleted file mode 100644 index 7dadffd99f94..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/base.py +++ /dev/null @@ -1,174 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.discoveryengine_v1alpha import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.discoveryengine_v1alpha.types import site_search_engine_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class SiteSearchEngineServiceTransport(abc.ABC): - """Abstract transport class for SiteSearchEngineService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'discoveryengine.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.recrawl_uris: gapic_v1.method.wrap_method( - self.recrawl_uris, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def recrawl_uris(self) -> Callable[ - [site_search_engine_service.RecrawlUrisRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'SiteSearchEngineServiceTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/grpc.py deleted file mode 100644 index 0bcfb27fc85a..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/grpc.py +++ /dev/null @@ -1,320 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.discoveryengine_v1alpha.types import site_search_engine_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import SiteSearchEngineServiceTransport, DEFAULT_CLIENT_INFO - - -class SiteSearchEngineServiceGrpcTransport(SiteSearchEngineServiceTransport): - """gRPC backend transport for SiteSearchEngineService. - - Service for managing site search related resources. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def recrawl_uris(self) -> Callable[ - [site_search_engine_service.RecrawlUrisRequest], - operations_pb2.Operation]: - r"""Return a callable for the recrawl uris method over gRPC. - - Request on-demand recrawl for a list of URIs. - - Returns: - Callable[[~.RecrawlUrisRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'recrawl_uris' not in self._stubs: - self._stubs['recrawl_uris'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.SiteSearchEngineService/RecrawlUris', - request_serializer=site_search_engine_service.RecrawlUrisRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['recrawl_uris'] - - def close(self): - self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'SiteSearchEngineServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/grpc_asyncio.py deleted file mode 100644 index 3defab13caed..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,319 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.discoveryengine_v1alpha.types import site_search_engine_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import SiteSearchEngineServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import SiteSearchEngineServiceGrpcTransport - - -class SiteSearchEngineServiceGrpcAsyncIOTransport(SiteSearchEngineServiceTransport): - """gRPC AsyncIO backend transport for SiteSearchEngineService. - - Service for managing site search related resources. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def recrawl_uris(self) -> Callable[ - [site_search_engine_service.RecrawlUrisRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the recrawl uris method over gRPC. - - Request on-demand recrawl for a list of URIs. - - Returns: - Callable[[~.RecrawlUrisRequest], - 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 'recrawl_uris' not in self._stubs: - self._stubs['recrawl_uris'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.SiteSearchEngineService/RecrawlUris', - request_serializer=site_search_engine_service.RecrawlUrisRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['recrawl_uris'] - - def close(self): - return self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - -__all__ = ( - 'SiteSearchEngineServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/rest.py deleted file mode 100644 index 7bb24796a06b..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/site_search_engine_service/transports/rest.py +++ /dev/null @@ -1,709 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.cloud.location import locations_pb2 # type: ignore -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.discoveryengine_v1alpha.types import site_search_engine_service -from google.longrunning import operations_pb2 # type: ignore - -from .base import SiteSearchEngineServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class SiteSearchEngineServiceRestInterceptor: - """Interceptor for SiteSearchEngineService. - - 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 SiteSearchEngineServiceRestTransport. - - .. code-block:: python - class MyCustomSiteSearchEngineServiceInterceptor(SiteSearchEngineServiceRestInterceptor): - def pre_recrawl_uris(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_recrawl_uris(self, response): - logging.log(f"Received response: {response}") - return response - - transport = SiteSearchEngineServiceRestTransport(interceptor=MyCustomSiteSearchEngineServiceInterceptor()) - client = SiteSearchEngineServiceClient(transport=transport) - - - """ - def pre_recrawl_uris(self, request: site_search_engine_service.RecrawlUrisRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[site_search_engine_service.RecrawlUrisRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for recrawl_uris - - Override in a subclass to manipulate the request or metadata - before they are sent to the SiteSearchEngineService server. - """ - return request, metadata - - def post_recrawl_uris(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for recrawl_uris - - Override in a subclass to manipulate the response - after it is returned by the SiteSearchEngineService server but before - it is returned to user code. - """ - return response - - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the SiteSearchEngineService 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 SiteSearchEngineService server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the SiteSearchEngineService 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 SiteSearchEngineService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class SiteSearchEngineServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: SiteSearchEngineServiceRestInterceptor - - -class SiteSearchEngineServiceRestTransport(SiteSearchEngineServiceTransport): - """REST backend transport for SiteSearchEngineService. - - Service for managing site search related resources. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'discoveryengine.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[SiteSearchEngineServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or SiteSearchEngineServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*}/operations', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1alpha") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _RecrawlUris(SiteSearchEngineServiceRestStub): - def __hash__(self): - return hash("RecrawlUris") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: site_search_engine_service.RecrawlUrisRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the recrawl uris method over HTTP. - - Args: - request (~.site_search_engine_service.RecrawlUrisRequest): - The request object. Request message for - [SiteSearchEngineService.RecrawlUris][google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.RecrawlUris] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1alpha/{site_search_engine=projects/*/locations/*/dataStores/*/siteSearchEngine}:recrawlUris', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1alpha/{site_search_engine=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}:recrawlUris', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_recrawl_uris(request, metadata) - pb_request = site_search_engine_service.RecrawlUrisRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_recrawl_uris(resp) - return resp - - @property - def recrawl_uris(self) -> Callable[ - [site_search_engine_service.RecrawlUrisRequest], - 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._RecrawlUris(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(SiteSearchEngineServiceRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(SiteSearchEngineServiceRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'SiteSearchEngineServiceRestTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/__init__.py deleted file mode 100644 index 387c002d1701..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import UserEventServiceClient -from .async_client import UserEventServiceAsyncClient - -__all__ = ( - 'UserEventServiceClient', - 'UserEventServiceAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/async_client.py deleted file mode 100644 index 1542968dbfd3..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/async_client.py +++ /dev/null @@ -1,746 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.discoveryengine_v1alpha import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.discoveryengine_v1alpha.types import common -from google.cloud.discoveryengine_v1alpha.types import import_config -from google.cloud.discoveryengine_v1alpha.types import purge_config -from google.cloud.discoveryengine_v1alpha.types import user_event -from google.cloud.discoveryengine_v1alpha.types import user_event_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport -from .client import UserEventServiceClient - - -class UserEventServiceAsyncClient: - """Service for ingesting end user actions on a website to - Discovery Engine API. - """ - - _client: UserEventServiceClient - - DEFAULT_ENDPOINT = UserEventServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = UserEventServiceClient.DEFAULT_MTLS_ENDPOINT - - data_store_path = staticmethod(UserEventServiceClient.data_store_path) - parse_data_store_path = staticmethod(UserEventServiceClient.parse_data_store_path) - document_path = staticmethod(UserEventServiceClient.document_path) - parse_document_path = staticmethod(UserEventServiceClient.parse_document_path) - common_billing_account_path = staticmethod(UserEventServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(UserEventServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(UserEventServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(UserEventServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(UserEventServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(UserEventServiceClient.parse_common_organization_path) - common_project_path = staticmethod(UserEventServiceClient.common_project_path) - parse_common_project_path = staticmethod(UserEventServiceClient.parse_common_project_path) - common_location_path = staticmethod(UserEventServiceClient.common_location_path) - parse_common_location_path = staticmethod(UserEventServiceClient.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: - UserEventServiceAsyncClient: The constructed client. - """ - return UserEventServiceClient.from_service_account_info.__func__(UserEventServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceAsyncClient: The constructed client. - """ - return UserEventServiceClient.from_service_account_file.__func__(UserEventServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return UserEventServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> UserEventServiceTransport: - """Returns the transport used by the client instance. - - Returns: - UserEventServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(UserEventServiceClient).get_transport_class, type(UserEventServiceClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, UserEventServiceTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the user event 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 (Union[str, ~.UserEventServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = UserEventServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def write_user_event(self, - request: Optional[Union[user_event_service.WriteUserEventRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> user_event.UserEvent: - r"""Writes a single user event. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - async def sample_write_user_event(): - # Create a client - client = discoveryengine_v1alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.WriteUserEventRequest( - parent="parent_value", - ) - - # Make the request - response = await client.write_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.WriteUserEventRequest, dict]]): - The request object. Request message for WriteUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1alpha.types.UserEvent: - UserEvent captures all metadata - information Discovery Engine API needs - to know about how end users interact - with customers' website. - - """ - # Create or coerce a protobuf request object. - request = user_event_service.WriteUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.write_user_event, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def collect_user_event(self, - request: Optional[Union[user_event_service.CollectUserEventRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> httpbody_pb2.HttpBody: - r"""Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a third-party domain. - - This method is used only by the Discovery Engine API - JavaScript pixel and Google Tag Manager. Users should - not call this method directly. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - async def sample_collect_user_event(): - # Create a client - client = discoveryengine_v1alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = await client.collect_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.CollectUserEventRequest, dict]]): - The request object. Request message for CollectUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It should only be used for - payload formats that can't be represented as JSON, - such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as - the response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request - fields and also want access to the raw HTTP body. - - Example: - - message GetResourceRequest { - // A unique request id. string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) - returns (google.api.HttpBody); - - rpc UpdateResource(google.api.HttpBody) - returns (google.protobuf.Empty); - - } - - Example with streaming methods: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - # Create or coerce a protobuf request object. - request = user_event_service.CollectUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.collect_user_event, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def purge_user_events(self, - request: Optional[Union[purge_config.PurgeUserEventsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - async def sample_purge_user_events(): - # Create a client - client = discoveryengine_v1alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.PurgeUserEventsRequest, dict]]): - The request object. Request message for PurgeUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.discoveryengine_v1alpha.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is - successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - """ - # Create or coerce a protobuf request object. - request = purge_config.PurgeUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.purge_user_events, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - purge_config.PurgeUserEventsResponse, - metadata_type=purge_config.PurgeUserEventsMetadata, - ) - - # Done; return the response. - return response - - async def import_user_events(self, - request: Optional[Union[import_config.ImportUserEventsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - async def sample_import_user_events(): - # Create a client - client = discoveryengine_v1alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - inline_source = discoveryengine_v1alpha.InlineSource() - inline_source.user_events.event_type = "event_type_value" - inline_source.user_events.user_pseudo_id = "user_pseudo_id_value" - - request = discoveryengine_v1alpha.ImportUserEventsRequest( - inline_source=inline_source, - parent="parent_value", - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1alpha.types.ImportUserEventsRequest, dict]]): - The request object. Request message for the - ImportUserEvents request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.discoveryengine_v1alpha.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is - returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - request = import_config.ImportUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_user_events, - default_retry=retries.Retry( -initial=1.0,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=300.0, - ), - default_timeout=300.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - import_config.ImportUserEventsResponse, - metadata_type=import_config.ImportUserEventsMetadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "UserEventServiceAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "UserEventServiceAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/client.py deleted file mode 100644 index 5f25fb05ae1d..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/client.py +++ /dev/null @@ -1,960 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.discoveryengine_v1alpha import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.discoveryengine_v1alpha.types import common -from google.cloud.discoveryengine_v1alpha.types import import_config -from google.cloud.discoveryengine_v1alpha.types import purge_config -from google.cloud.discoveryengine_v1alpha.types import user_event -from google.cloud.discoveryengine_v1alpha.types import user_event_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import UserEventServiceGrpcTransport -from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport -from .transports.rest import UserEventServiceRestTransport - - -class UserEventServiceClientMeta(type): - """Metaclass for the UserEventService 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[UserEventServiceTransport]] - _transport_registry["grpc"] = UserEventServiceGrpcTransport - _transport_registry["grpc_asyncio"] = UserEventServiceGrpcAsyncIOTransport - _transport_registry["rest"] = UserEventServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[UserEventServiceTransport]: - """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 UserEventServiceClient(metaclass=UserEventServiceClientMeta): - """Service for ingesting end user actions on a website to - Discovery Engine API. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceClient: 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: - UserEventServiceClient: 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) -> UserEventServiceTransport: - """Returns the transport used by the client instance. - - Returns: - UserEventServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def data_store_path(project: str,location: str,data_store: str,) -> str: - """Returns a fully-qualified data_store string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) - - @staticmethod - def parse_data_store_path(path: str) -> Dict[str,str]: - """Parses a data_store path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def document_path(project: str,location: str,data_store: str,branch: str,document: str,) -> str: - """Returns a fully-qualified document string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) - - @staticmethod - def parse_document_path(path: str) -> Dict[str,str]: - """Parses a document path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)/documents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, UserEventServiceTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the user event 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 (Union[str, UserEventServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, UserEventServiceTransport): - # transport is a UserEventServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def write_user_event(self, - request: Optional[Union[user_event_service.WriteUserEventRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> user_event.UserEvent: - r"""Writes a single user event. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - def sample_write_user_event(): - # Create a client - client = discoveryengine_v1alpha.UserEventServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.WriteUserEventRequest( - parent="parent_value", - ) - - # Make the request - response = client.write_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1alpha.types.WriteUserEventRequest, dict]): - The request object. Request message for WriteUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1alpha.types.UserEvent: - UserEvent captures all metadata - information Discovery Engine API needs - to know about how end users interact - with customers' website. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a user_event_service.WriteUserEventRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, user_event_service.WriteUserEventRequest): - request = user_event_service.WriteUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.write_user_event] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def collect_user_event(self, - request: Optional[Union[user_event_service.CollectUserEventRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> httpbody_pb2.HttpBody: - r"""Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a third-party domain. - - This method is used only by the Discovery Engine API - JavaScript pixel and Google Tag Manager. Users should - not call this method directly. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - def sample_collect_user_event(): - # Create a client - client = discoveryengine_v1alpha.UserEventServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = client.collect_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1alpha.types.CollectUserEventRequest, dict]): - The request object. Request message for CollectUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It should only be used for - payload formats that can't be represented as JSON, - such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as - the response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request - fields and also want access to the raw HTTP body. - - Example: - - message GetResourceRequest { - // A unique request id. string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) - returns (google.api.HttpBody); - - rpc UpdateResource(google.api.HttpBody) - returns (google.protobuf.Empty); - - } - - Example with streaming methods: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a user_event_service.CollectUserEventRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, user_event_service.CollectUserEventRequest): - request = user_event_service.CollectUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.collect_user_event] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def purge_user_events(self, - request: Optional[Union[purge_config.PurgeUserEventsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - def sample_purge_user_events(): - # Create a client - client = discoveryengine_v1alpha.UserEventServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1alpha.types.PurgeUserEventsRequest, dict]): - The request object. Request message for PurgeUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.discoveryengine_v1alpha.types.PurgeUserEventsResponse` Response of the PurgeUserEventsRequest. If the long running operation is - successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a purge_config.PurgeUserEventsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, purge_config.PurgeUserEventsRequest): - request = purge_config.PurgeUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.purge_user_events] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - purge_config.PurgeUserEventsResponse, - metadata_type=purge_config.PurgeUserEventsMetadata, - ) - - # Done; return the response. - return response - - def import_user_events(self, - request: Optional[Union[import_config.ImportUserEventsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1alpha - - def sample_import_user_events(): - # Create a client - client = discoveryengine_v1alpha.UserEventServiceClient() - - # Initialize request argument(s) - inline_source = discoveryengine_v1alpha.InlineSource() - inline_source.user_events.event_type = "event_type_value" - inline_source.user_events.user_pseudo_id = "user_pseudo_id_value" - - request = discoveryengine_v1alpha.ImportUserEventsRequest( - inline_source=inline_source, - parent="parent_value", - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1alpha.types.ImportUserEventsRequest, dict]): - The request object. Request message for the - ImportUserEvents request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.discoveryengine_v1alpha.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is - returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a import_config.ImportUserEventsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, import_config.ImportUserEventsRequest): - request = import_config.ImportUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_user_events] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - import_config.ImportUserEventsResponse, - metadata_type=import_config.ImportUserEventsMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "UserEventServiceClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - - - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "UserEventServiceClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/__init__.py deleted file mode 100644 index bea95d5a9d94..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import UserEventServiceTransport -from .grpc import UserEventServiceGrpcTransport -from .grpc_asyncio import UserEventServiceGrpcAsyncIOTransport -from .rest import UserEventServiceRestTransport -from .rest import UserEventServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] -_transport_registry['grpc'] = UserEventServiceGrpcTransport -_transport_registry['grpc_asyncio'] = UserEventServiceGrpcAsyncIOTransport -_transport_registry['rest'] = UserEventServiceRestTransport - -__all__ = ( - 'UserEventServiceTransport', - 'UserEventServiceGrpcTransport', - 'UserEventServiceGrpcAsyncIOTransport', - 'UserEventServiceRestTransport', - 'UserEventServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/base.py deleted file mode 100644 index da108380c50f..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/base.py +++ /dev/null @@ -1,226 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.discoveryengine_v1alpha import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.discoveryengine_v1alpha.types import import_config -from google.cloud.discoveryengine_v1alpha.types import purge_config -from google.cloud.discoveryengine_v1alpha.types import user_event -from google.cloud.discoveryengine_v1alpha.types import user_event_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class UserEventServiceTransport(abc.ABC): - """Abstract transport class for UserEventService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'discoveryengine.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.write_user_event: gapic_v1.method.wrap_method( - self.write_user_event, - default_timeout=None, - client_info=client_info, - ), - self.collect_user_event: gapic_v1.method.wrap_method( - self.collect_user_event, - default_timeout=None, - client_info=client_info, - ), - self.purge_user_events: gapic_v1.method.wrap_method( - self.purge_user_events, - default_timeout=None, - client_info=client_info, - ), - self.import_user_events: gapic_v1.method.wrap_method( - self.import_user_events, - default_retry=retries.Retry( -initial=1.0,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=300.0, - ), - default_timeout=300.0, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - Union[ - user_event.UserEvent, - Awaitable[user_event.UserEvent] - ]]: - raise NotImplementedError() - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - Union[ - httpbody_pb2.HttpBody, - Awaitable[httpbody_pb2.HttpBody] - ]]: - raise NotImplementedError() - - @property - def purge_user_events(self) -> Callable[ - [purge_config.PurgeUserEventsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'UserEventServiceTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/grpc.py deleted file mode 100644 index 9a9babfa7184..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/grpc.py +++ /dev/null @@ -1,420 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.discoveryengine_v1alpha.types import import_config -from google.cloud.discoveryengine_v1alpha.types import purge_config -from google.cloud.discoveryengine_v1alpha.types import user_event -from google.cloud.discoveryengine_v1alpha.types import user_event_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO - - -class UserEventServiceGrpcTransport(UserEventServiceTransport): - """gRPC backend transport for UserEventService. - - Service for ingesting end user actions on a website to - Discovery Engine 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 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - user_event.UserEvent]: - r"""Return a callable for the write user event method over gRPC. - - Writes a single user event. - - Returns: - Callable[[~.WriteUserEventRequest], - ~.UserEvent]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'write_user_event' not in self._stubs: - self._stubs['write_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.UserEventService/WriteUserEvent', - request_serializer=user_event_service.WriteUserEventRequest.serialize, - response_deserializer=user_event.UserEvent.deserialize, - ) - return self._stubs['write_user_event'] - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - httpbody_pb2.HttpBody]: - r"""Return a callable for the collect user event method over gRPC. - - Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a third-party domain. - - This method is used only by the Discovery Engine API - JavaScript pixel and Google Tag Manager. Users should - not call this method directly. - - Returns: - Callable[[~.CollectUserEventRequest], - ~.HttpBody]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'collect_user_event' not in self._stubs: - self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.UserEventService/CollectUserEvent', - request_serializer=user_event_service.CollectUserEventRequest.serialize, - response_deserializer=httpbody_pb2.HttpBody.FromString, - ) - return self._stubs['collect_user_event'] - - @property - def purge_user_events(self) -> Callable[ - [purge_config.PurgeUserEventsRequest], - operations_pb2.Operation]: - r"""Return a callable for the purge user events method over gRPC. - - Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - Returns: - Callable[[~.PurgeUserEventsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'purge_user_events' not in self._stubs: - self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.UserEventService/PurgeUserEvents', - request_serializer=purge_config.PurgeUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['purge_user_events'] - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - operations_pb2.Operation]: - r"""Return a callable for the import user events method over gRPC. - - Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - Returns: - Callable[[~.ImportUserEventsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_user_events' not in self._stubs: - self._stubs['import_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.UserEventService/ImportUserEvents', - request_serializer=import_config.ImportUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_user_events'] - - def close(self): - self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'UserEventServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/grpc_asyncio.py deleted file mode 100644 index 594d8c6632ee..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,419 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.discoveryengine_v1alpha.types import import_config -from google.cloud.discoveryengine_v1alpha.types import purge_config -from google.cloud.discoveryengine_v1alpha.types import user_event -from google.cloud.discoveryengine_v1alpha.types import user_event_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import UserEventServiceGrpcTransport - - -class UserEventServiceGrpcAsyncIOTransport(UserEventServiceTransport): - """gRPC AsyncIO backend transport for UserEventService. - - Service for ingesting end user actions on a website to - Discovery Engine 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 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - Awaitable[user_event.UserEvent]]: - r"""Return a callable for the write user event method over gRPC. - - Writes a single user event. - - Returns: - Callable[[~.WriteUserEventRequest], - Awaitable[~.UserEvent]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'write_user_event' not in self._stubs: - self._stubs['write_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.UserEventService/WriteUserEvent', - request_serializer=user_event_service.WriteUserEventRequest.serialize, - response_deserializer=user_event.UserEvent.deserialize, - ) - return self._stubs['write_user_event'] - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - Awaitable[httpbody_pb2.HttpBody]]: - r"""Return a callable for the collect user event method over gRPC. - - Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a third-party domain. - - This method is used only by the Discovery Engine API - JavaScript pixel and Google Tag Manager. Users should - not call this method directly. - - Returns: - Callable[[~.CollectUserEventRequest], - Awaitable[~.HttpBody]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'collect_user_event' not in self._stubs: - self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.UserEventService/CollectUserEvent', - request_serializer=user_event_service.CollectUserEventRequest.serialize, - response_deserializer=httpbody_pb2.HttpBody.FromString, - ) - return self._stubs['collect_user_event'] - - @property - def purge_user_events(self) -> Callable[ - [purge_config.PurgeUserEventsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the purge user events method over gRPC. - - Deletes permanently all user events specified by the - filter provided. Depending on the number of events - specified by the filter, this operation could take hours - or days to complete. To test a filter, use the list - command first. - - Returns: - Callable[[~.PurgeUserEventsRequest], - 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 'purge_user_events' not in self._stubs: - self._stubs['purge_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.UserEventService/PurgeUserEvents', - request_serializer=purge_config.PurgeUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['purge_user_events'] - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import user events method over gRPC. - - Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - Returns: - Callable[[~.ImportUserEventsRequest], - 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 'import_user_events' not in self._stubs: - self._stubs['import_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.UserEventService/ImportUserEvents', - request_serializer=import_config.ImportUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_user_events'] - - def close(self): - return self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - -__all__ = ( - 'UserEventServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/rest.py deleted file mode 100644 index 6050744fbd81..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/user_event_service/transports/rest.py +++ /dev/null @@ -1,1132 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.cloud.location import locations_pb2 # type: ignore -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.discoveryengine_v1alpha.types import import_config -from google.cloud.discoveryengine_v1alpha.types import purge_config -from google.cloud.discoveryengine_v1alpha.types import user_event -from google.cloud.discoveryengine_v1alpha.types import user_event_service -from google.longrunning import operations_pb2 # type: ignore - -from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class UserEventServiceRestInterceptor: - """Interceptor for UserEventService. - - 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 UserEventServiceRestTransport. - - .. code-block:: python - class MyCustomUserEventServiceInterceptor(UserEventServiceRestInterceptor): - def pre_collect_user_event(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_collect_user_event(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_import_user_events(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_import_user_events(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_purge_user_events(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_purge_user_events(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_write_user_event(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_write_user_event(self, response): - logging.log(f"Received response: {response}") - return response - - transport = UserEventServiceRestTransport(interceptor=MyCustomUserEventServiceInterceptor()) - client = UserEventServiceClient(transport=transport) - - - """ - def pre_collect_user_event(self, request: user_event_service.CollectUserEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[user_event_service.CollectUserEventRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for collect_user_event - - Override in a subclass to manipulate the request or metadata - before they are sent to the UserEventService server. - """ - return request, metadata - - def post_collect_user_event(self, response: httpbody_pb2.HttpBody) -> httpbody_pb2.HttpBody: - """Post-rpc interceptor for collect_user_event - - Override in a subclass to manipulate the response - after it is returned by the UserEventService server but before - it is returned to user code. - """ - return response - def pre_import_user_events(self, request: import_config.ImportUserEventsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[import_config.ImportUserEventsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for import_user_events - - Override in a subclass to manipulate the request or metadata - before they are sent to the UserEventService server. - """ - return request, metadata - - def post_import_user_events(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for import_user_events - - Override in a subclass to manipulate the response - after it is returned by the UserEventService server but before - it is returned to user code. - """ - return response - def pre_purge_user_events(self, request: purge_config.PurgeUserEventsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[purge_config.PurgeUserEventsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for purge_user_events - - Override in a subclass to manipulate the request or metadata - before they are sent to the UserEventService server. - """ - return request, metadata - - def post_purge_user_events(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for purge_user_events - - Override in a subclass to manipulate the response - after it is returned by the UserEventService server but before - it is returned to user code. - """ - return response - def pre_write_user_event(self, request: user_event_service.WriteUserEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[user_event_service.WriteUserEventRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for write_user_event - - Override in a subclass to manipulate the request or metadata - before they are sent to the UserEventService server. - """ - return request, metadata - - def post_write_user_event(self, response: user_event.UserEvent) -> user_event.UserEvent: - """Post-rpc interceptor for write_user_event - - Override in a subclass to manipulate the response - after it is returned by the UserEventService server but before - it is returned to user code. - """ - return response - - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the UserEventService 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 UserEventService server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the UserEventService 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 UserEventService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class UserEventServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: UserEventServiceRestInterceptor - - -class UserEventServiceRestTransport(UserEventServiceTransport): - """REST backend transport for UserEventService. - - Service for ingesting end user actions on a website to - Discovery Engine 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 = 'discoveryengine.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[UserEventServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or UserEventServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*}/operations', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1alpha") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _CollectUserEvent(UserEventServiceRestStub): - def __hash__(self): - return hash("CollectUserEvent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "userEvent" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: user_event_service.CollectUserEventRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> httpbody_pb2.HttpBody: - r"""Call the collect user event method over HTTP. - - Args: - request (~.user_event_service.CollectUserEventRequest): - The request object. Request message for CollectUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It - should only be used for payload formats that can't be - represented as JSON, such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as the - response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request fields - and also want access to the raw HTTP body. - - Example: - - :: - - message GetResourceRequest { - // A unique request id. - string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) - returns (google.api.HttpBody); - rpc UpdateResource(google.api.HttpBody) - returns (google.protobuf.Empty); - - } - - Example with streaming methods: - - :: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{parent=projects/*/locations/*/dataStores/*}/userEvents:collect', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{parent=projects/*/locations/*/collections/*/dataStores/*}/userEvents:collect', - }, - ] - request, metadata = self._interceptor.pre_collect_user_event(request, metadata) - pb_request = user_event_service.CollectUserEventRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = httpbody_pb2.HttpBody() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_collect_user_event(resp) - return resp - - class _ImportUserEvents(UserEventServiceRestStub): - def __hash__(self): - return hash("ImportUserEvents") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: import_config.ImportUserEventsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the import user events method over HTTP. - - Args: - request (~.import_config.ImportUserEventsRequest): - The request object. Request message for the - ImportUserEvents request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1alpha/{parent=projects/*/locations/*/dataStores/*}/userEvents:import', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1alpha/{parent=projects/*/locations/*/collections/*/dataStores/*}/userEvents:import', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_import_user_events(request, metadata) - pb_request = import_config.ImportUserEventsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_import_user_events(resp) - return resp - - class _PurgeUserEvents(UserEventServiceRestStub): - def __hash__(self): - return hash("PurgeUserEvents") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: purge_config.PurgeUserEventsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the purge user events method over HTTP. - - Args: - request (~.purge_config.PurgeUserEventsRequest): - The request object. Request message for PurgeUserEvents - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1alpha/{parent=projects/*/locations/*/dataStores/*}/userEvents:purge', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1alpha/{parent=projects/*/locations/*/collections/*/dataStores/*}/userEvents:purge', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_purge_user_events(request, metadata) - pb_request = purge_config.PurgeUserEventsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_purge_user_events(resp) - return resp - - class _WriteUserEvent(UserEventServiceRestStub): - def __hash__(self): - return hash("WriteUserEvent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: user_event_service.WriteUserEventRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> user_event.UserEvent: - r"""Call the write user event method over HTTP. - - Args: - request (~.user_event_service.WriteUserEventRequest): - The request object. Request message for WriteUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.user_event.UserEvent: - UserEvent captures all metadata - information Discovery Engine API needs - to know about how end users interact - with customers' website. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1alpha/{parent=projects/*/locations/*/dataStores/*}/userEvents:write', - 'body': 'user_event', - }, -{ - 'method': 'post', - 'uri': '/v1alpha/{parent=projects/*/locations/*/collections/*/dataStores/*}/userEvents:write', - 'body': 'user_event', - }, - ] - request, metadata = self._interceptor.pre_write_user_event(request, metadata) - pb_request = user_event_service.WriteUserEventRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = user_event.UserEvent() - pb_resp = user_event.UserEvent.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_write_user_event(resp) - return resp - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - httpbody_pb2.HttpBody]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CollectUserEvent(self._session, self._host, self._interceptor) # type: ignore - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - 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._ImportUserEvents(self._session, self._host, self._interceptor) # type: ignore - - @property - def purge_user_events(self) -> Callable[ - [purge_config.PurgeUserEventsRequest], - 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._PurgeUserEvents(self._session, self._host, self._interceptor) # type: ignore - - @property - def write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - user_event.UserEvent]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._WriteUserEvent(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(UserEventServiceRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(UserEventServiceRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'UserEventServiceRestTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/__init__.py deleted file mode 100644 index 5b503322068e..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/__init__.py +++ /dev/null @@ -1,248 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .common import ( - CustomAttribute, - DoubleList, - Interval, - UserInfo, - IndustryVertical, - SearchAddOn, - SearchTier, - SolutionType, -) -from .completion_service import ( - CompleteQueryRequest, - CompleteQueryResponse, -) -from .conversation import ( - Conversation, - ConversationContext, - ConversationMessage, - Reply, - TextInput, -) -from .conversational_search_service import ( - ConverseConversationRequest, - ConverseConversationResponse, - CreateConversationRequest, - DeleteConversationRequest, - GetConversationRequest, - ListConversationsRequest, - ListConversationsResponse, - UpdateConversationRequest, -) -from .data_store import ( - DataStore, -) -from .data_store_service import ( - CreateDataStoreMetadata, - CreateDataStoreRequest, - DeleteDataStoreMetadata, - DeleteDataStoreRequest, - GetDataStoreRequest, - ListDataStoresRequest, - ListDataStoresResponse, - UpdateDataStoreRequest, -) -from .document import ( - Document, -) -from .document_service import ( - CreateDocumentRequest, - DeleteDocumentRequest, - GetDocumentRequest, - ListDocumentsRequest, - ListDocumentsResponse, - UpdateDocumentRequest, -) -from .engine import ( - Engine, -) -from .engine_service import ( - CreateEngineMetadata, - CreateEngineRequest, - DeleteEngineMetadata, - DeleteEngineRequest, - GetEngineRequest, - ListEnginesRequest, - ListEnginesResponse, - PauseEngineRequest, - ResumeEngineRequest, - TuneEngineMetadata, - TuneEngineRequest, - TuneEngineResponse, - UpdateEngineRequest, -) -from .import_config import ( - BigQuerySource, - GcsSource, - ImportDocumentsMetadata, - ImportDocumentsRequest, - ImportDocumentsResponse, - ImportErrorConfig, - ImportUserEventsMetadata, - ImportUserEventsRequest, - ImportUserEventsResponse, -) -from .purge_config import ( - PurgeDocumentsMetadata, - PurgeDocumentsRequest, - PurgeDocumentsResponse, - PurgeUserEventsMetadata, - PurgeUserEventsRequest, - PurgeUserEventsResponse, -) -from .recommendation_service import ( - RecommendRequest, - RecommendResponse, -) -from .schema import ( - FieldConfig, - Schema, -) -from .schema_service import ( - CreateSchemaMetadata, - CreateSchemaRequest, - DeleteSchemaMetadata, - DeleteSchemaRequest, - GetSchemaRequest, - ListSchemasRequest, - ListSchemasResponse, - UpdateSchemaMetadata, - UpdateSchemaRequest, -) -from .search_service import ( - SearchRequest, - SearchResponse, -) -from .site_search_engine_service import ( - RecrawlUrisMetadata, - RecrawlUrisRequest, - RecrawlUrisResponse, -) -from .user_event import ( - CompletionInfo, - DocumentInfo, - MediaInfo, - PageInfo, - PanelInfo, - SearchInfo, - TransactionInfo, - UserEvent, -) -from .user_event_service import ( - CollectUserEventRequest, - WriteUserEventRequest, -) - -__all__ = ( - 'CustomAttribute', - 'DoubleList', - 'Interval', - 'UserInfo', - 'IndustryVertical', - 'SearchAddOn', - 'SearchTier', - 'SolutionType', - 'CompleteQueryRequest', - 'CompleteQueryResponse', - 'Conversation', - 'ConversationContext', - 'ConversationMessage', - 'Reply', - 'TextInput', - 'ConverseConversationRequest', - 'ConverseConversationResponse', - 'CreateConversationRequest', - 'DeleteConversationRequest', - 'GetConversationRequest', - 'ListConversationsRequest', - 'ListConversationsResponse', - 'UpdateConversationRequest', - 'DataStore', - 'CreateDataStoreMetadata', - 'CreateDataStoreRequest', - 'DeleteDataStoreMetadata', - 'DeleteDataStoreRequest', - 'GetDataStoreRequest', - 'ListDataStoresRequest', - 'ListDataStoresResponse', - 'UpdateDataStoreRequest', - 'Document', - 'CreateDocumentRequest', - 'DeleteDocumentRequest', - 'GetDocumentRequest', - 'ListDocumentsRequest', - 'ListDocumentsResponse', - 'UpdateDocumentRequest', - 'Engine', - 'CreateEngineMetadata', - 'CreateEngineRequest', - 'DeleteEngineMetadata', - 'DeleteEngineRequest', - 'GetEngineRequest', - 'ListEnginesRequest', - 'ListEnginesResponse', - 'PauseEngineRequest', - 'ResumeEngineRequest', - 'TuneEngineMetadata', - 'TuneEngineRequest', - 'TuneEngineResponse', - 'UpdateEngineRequest', - 'BigQuerySource', - 'GcsSource', - 'ImportDocumentsMetadata', - 'ImportDocumentsRequest', - 'ImportDocumentsResponse', - 'ImportErrorConfig', - 'ImportUserEventsMetadata', - 'ImportUserEventsRequest', - 'ImportUserEventsResponse', - 'PurgeDocumentsMetadata', - 'PurgeDocumentsRequest', - 'PurgeDocumentsResponse', - 'PurgeUserEventsMetadata', - 'PurgeUserEventsRequest', - 'PurgeUserEventsResponse', - 'RecommendRequest', - 'RecommendResponse', - 'FieldConfig', - 'Schema', - 'CreateSchemaMetadata', - 'CreateSchemaRequest', - 'DeleteSchemaMetadata', - 'DeleteSchemaRequest', - 'GetSchemaRequest', - 'ListSchemasRequest', - 'ListSchemasResponse', - 'UpdateSchemaMetadata', - 'UpdateSchemaRequest', - 'SearchRequest', - 'SearchResponse', - 'RecrawlUrisMetadata', - 'RecrawlUrisRequest', - 'RecrawlUrisResponse', - 'CompletionInfo', - 'DocumentInfo', - 'MediaInfo', - 'PageInfo', - 'PanelInfo', - 'SearchInfo', - 'TransactionInfo', - 'UserEvent', - 'CollectUserEventRequest', - 'WriteUserEventRequest', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/common.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/common.py deleted file mode 100644 index 5c52f13db40e..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/common.py +++ /dev/null @@ -1,257 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1alpha', - manifest={ - 'IndustryVertical', - 'SolutionType', - 'SearchTier', - 'SearchAddOn', - 'Interval', - 'CustomAttribute', - 'UserInfo', - 'DoubleList', - }, -) - - -class IndustryVertical(proto.Enum): - r"""The industry vertical associated with the - [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]. - - Values: - INDUSTRY_VERTICAL_UNSPECIFIED (0): - Value used when unset. - GENERIC (1): - The generic vertical for documents that are - not specific to any industry vertical. - MEDIA (2): - The media industry vertical. - """ - INDUSTRY_VERTICAL_UNSPECIFIED = 0 - GENERIC = 1 - MEDIA = 2 - - -class SolutionType(proto.Enum): - r"""The type of solution. - - Values: - SOLUTION_TYPE_UNSPECIFIED (0): - Default value. - SOLUTION_TYPE_RECOMMENDATION (1): - Used for Recommendations AI. - SOLUTION_TYPE_SEARCH (2): - Used for Discovery Search. - SOLUTION_TYPE_CHAT (3): - Used for use cases related to the Generative - AI agent. - """ - SOLUTION_TYPE_UNSPECIFIED = 0 - SOLUTION_TYPE_RECOMMENDATION = 1 - SOLUTION_TYPE_SEARCH = 2 - SOLUTION_TYPE_CHAT = 3 - - -class SearchTier(proto.Enum): - r"""Tiers of search features. Different tiers might have - different pricing. To learn more, please check the pricing - documentation. - - Values: - SEARCH_TIER_UNSPECIFIED (0): - Default value when the enum is unspecified. - This is invalid to use. - SEARCH_TIER_STANDARD (1): - Standard tier. - SEARCH_TIER_ENTERPRISE (2): - Enterprise tier. - """ - SEARCH_TIER_UNSPECIFIED = 0 - SEARCH_TIER_STANDARD = 1 - SEARCH_TIER_ENTERPRISE = 2 - - -class SearchAddOn(proto.Enum): - r"""Add-on that provides additional functionality for search. - - Values: - SEARCH_ADD_ON_UNSPECIFIED (0): - Default value when the enum is unspecified. - This is invalid to use. - SEARCH_ADD_ON_LLM (1): - Large language model add-on. - """ - SEARCH_ADD_ON_UNSPECIFIED = 0 - SEARCH_ADD_ON_LLM = 1 - - -class Interval(proto.Message): - r"""A floating point interval. - - 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: - minimum (float): - Inclusive lower bound. - - This field is a member of `oneof`_ ``min``. - exclusive_minimum (float): - Exclusive lower bound. - - This field is a member of `oneof`_ ``min``. - maximum (float): - Inclusive upper bound. - - This field is a member of `oneof`_ ``max``. - exclusive_maximum (float): - Exclusive upper bound. - - This field is a member of `oneof`_ ``max``. - """ - - minimum: float = proto.Field( - proto.DOUBLE, - number=1, - oneof='min', - ) - exclusive_minimum: float = proto.Field( - proto.DOUBLE, - number=2, - oneof='min', - ) - maximum: float = proto.Field( - proto.DOUBLE, - number=3, - oneof='max', - ) - exclusive_maximum: float = proto.Field( - proto.DOUBLE, - number=4, - oneof='max', - ) - - -class CustomAttribute(proto.Message): - r"""A custom attribute that is not explicitly modeled in a resource, - e.g. [UserEvent][google.cloud.discoveryengine.v1alpha.UserEvent]. - - Attributes: - text (MutableSequence[str]): - The textual values of this custom attribute. For example, - ``["yellow", "green"]`` when the key is "color". - - Empty string is not allowed. Otherwise, an - ``INVALID_ARGUMENT`` error is returned. - - Exactly one of - [CustomAttribute.text][google.cloud.discoveryengine.v1alpha.CustomAttribute.text] - or - [CustomAttribute.numbers][google.cloud.discoveryengine.v1alpha.CustomAttribute.numbers] - should be set. Otherwise, an ``INVALID_ARGUMENT`` error is - returned. - numbers (MutableSequence[float]): - The numerical values of this custom attribute. For example, - ``[2.3, 15.4]`` when the key is "lengths_cm". - - Exactly one of - [CustomAttribute.text][google.cloud.discoveryengine.v1alpha.CustomAttribute.text] - or - [CustomAttribute.numbers][google.cloud.discoveryengine.v1alpha.CustomAttribute.numbers] - should be set. Otherwise, an ``INVALID_ARGUMENT`` error is - returned. - """ - - text: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - numbers: MutableSequence[float] = proto.RepeatedField( - proto.DOUBLE, - number=2, - ) - - -class UserInfo(proto.Message): - r"""Information of an end user. - - Attributes: - user_id (str): - Highly recommended for logged-in users. Unique identifier - for logged-in user, such as a user name. Don't set for - anonymous users. - - Always use a hashed value for this ID. - - Don't set the field to the same fixed ID for different - users. This mixes the event history of those users together, - which results in degraded model quality. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an ``INVALID_ARGUMENT`` error - is returned. - user_agent (str): - User agent as included in the HTTP header. - - The field must be a UTF-8 encoded string with a length limit - of 1,000 characters. Otherwise, an ``INVALID_ARGUMENT`` - error is returned. - - This should not be set when using the client side event - reporting with GTM or JavaScript tag in - [UserEventService.CollectUserEvent][google.cloud.discoveryengine.v1alpha.UserEventService.CollectUserEvent] - or if - [UserEvent.direct_user_request][google.cloud.discoveryengine.v1alpha.UserEvent.direct_user_request] - is set. - """ - - user_id: str = proto.Field( - proto.STRING, - number=1, - ) - user_agent: str = proto.Field( - proto.STRING, - number=2, - ) - - -class DoubleList(proto.Message): - r"""Double list. - - Attributes: - values (MutableSequence[float]): - Double values. - """ - - values: MutableSequence[float] = proto.RepeatedField( - proto.DOUBLE, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/completion_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/completion_service.py deleted file mode 100644 index 796a63969cdf..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/completion_service.py +++ /dev/null @@ -1,169 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1alpha', - manifest={ - 'CompleteQueryRequest', - 'CompleteQueryResponse', - }, -) - - -class CompleteQueryRequest(proto.Message): - r"""Request message for - [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1alpha.CompletionService.CompleteQuery] - method. - - Attributes: - data_store (str): - Required. The parent data store resource name for which the - completion is performed, such as - ``projects/*/locations/global/collections/default_collection/dataStores/default_data_store``. - query (str): - Required. The typeahead input used to fetch - suggestions. Maximum length is 128 characters. - query_model (str): - Selects data model of query suggestions for serving. - Currently supported values: - - - ``document`` - Using suggestions generated from - user-imported documents. - - ``search-history`` - Using suggestions generated from the - past history of - [SearchService.Search][google.cloud.discoveryengine.v1alpha.SearchService.Search] - API calls. Do not use it when there is no traffic for - Search API. - - ``user-event`` - Using suggestions generated from - user-imported search events. - - ``document-completable`` - Using suggestions taken - directly from user-imported document fields marked as - completable. - - Default values: - - - ``document`` is the default model for regular dataStores. - - ``search-history`` is the default model for site search - dataStores. - user_pseudo_id (str): - A unique identifier for tracking visitors. For example, this - could be implemented with an HTTP cookie, which should be - able to uniquely identify a visitor on a single device. This - unique identifier should not change if the visitor logs in - or out of the website. - - This field should NOT have a fixed value such as - ``unknown_visitor``. - - This should be the same identifier as - [UserEvent.user_pseudo_id][google.cloud.discoveryengine.v1alpha.UserEvent.user_pseudo_id] - and - [SearchRequest.user_pseudo_id][google.cloud.discoveryengine.v1alpha.SearchRequest.user_pseudo_id]. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an ``INVALID_ARGUMENT`` error - is returned. - include_tail_suggestions (bool): - Indicates if tail suggestions should be - returned if there are no suggestions that match - the full query. Even if set to true, if there - are suggestions that match the full query, those - are returned and no tail suggestions are - returned. - """ - - data_store: str = proto.Field( - proto.STRING, - number=1, - ) - query: str = proto.Field( - proto.STRING, - number=2, - ) - query_model: str = proto.Field( - proto.STRING, - number=3, - ) - user_pseudo_id: str = proto.Field( - proto.STRING, - number=4, - ) - include_tail_suggestions: bool = proto.Field( - proto.BOOL, - number=5, - ) - - -class CompleteQueryResponse(proto.Message): - r"""Response message for - [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1alpha.CompletionService.CompleteQuery] - method. - - Attributes: - query_suggestions (MutableSequence[google.cloud.discoveryengine_v1alpha.types.CompleteQueryResponse.QuerySuggestion]): - Results of the matched query suggestions. The - result list is ordered and the first result is a - top suggestion. - tail_match_triggered (bool): - True if the returned suggestions are all tail suggestions. - - For tail matching to be triggered, include_tail_suggestions - in the request must be true and there must be no suggestions - that match the full query. - """ - - class QuerySuggestion(proto.Message): - r"""Suggestions as search queries. - - Attributes: - suggestion (str): - The suggestion for the query. - completable_field_paths (MutableSequence[str]): - The unique document field paths that serve as - the source of this suggestion if it was - generated from completable fields. - - This field is only populated for the - document-completable model. - """ - - suggestion: str = proto.Field( - proto.STRING, - number=1, - ) - completable_field_paths: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - query_suggestions: MutableSequence[QuerySuggestion] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=QuerySuggestion, - ) - tail_match_triggered: bool = proto.Field( - proto.BOOL, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/conversation.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/conversation.py deleted file mode 100644 index 61a669ad6236..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/conversation.py +++ /dev/null @@ -1,248 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.discoveryengine_v1alpha.types import search_service -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1alpha', - manifest={ - 'Conversation', - 'Reply', - 'ConversationContext', - 'TextInput', - 'ConversationMessage', - }, -) - - -class Conversation(proto.Message): - r"""External conversation proto definition. - - Attributes: - name (str): - Immutable. Fully qualified name - ``project/*/locations/global/collections/{collection}/dataStore/*/conversations/*`` - state (google.cloud.discoveryengine_v1alpha.types.Conversation.State): - The state of the Conversation. - user_pseudo_id (str): - A unique identifier for tracking users. - messages (MutableSequence[google.cloud.discoveryengine_v1alpha.types.ConversationMessage]): - Conversation messages. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time the conversation - started. - end_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time the conversation - finished. - """ - class State(proto.Enum): - r"""Enumeration of the state of the conversation. - - Values: - STATE_UNSPECIFIED (0): - Unknown. - IN_PROGRESS (1): - Conversation is currently open. - COMPLETED (2): - Conversation has been completed. - """ - STATE_UNSPECIFIED = 0 - IN_PROGRESS = 1 - COMPLETED = 2 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - state: State = proto.Field( - proto.ENUM, - number=2, - enum=State, - ) - user_pseudo_id: str = proto.Field( - proto.STRING, - number=3, - ) - messages: MutableSequence['ConversationMessage'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='ConversationMessage', - ) - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - - -class Reply(proto.Message): - r"""Defines a reply message to user. - - Attributes: - reply (str): - DEPRECATED: use ``summary`` instead. Text reply. - references (MutableSequence[google.cloud.discoveryengine_v1alpha.types.Reply.Reference]): - References in the reply. - summary (google.cloud.discoveryengine_v1alpha.types.SearchResponse.Summary): - Summary based on search results. - """ - - class Reference(proto.Message): - r"""Defines reference in reply. - - Attributes: - uri (str): - URI link reference. - anchor_text (str): - Anchor text. - start (int): - Anchor text start index. - end (int): - Anchor text end index. - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - ) - anchor_text: str = proto.Field( - proto.STRING, - number=2, - ) - start: int = proto.Field( - proto.INT32, - number=3, - ) - end: int = proto.Field( - proto.INT32, - number=4, - ) - - reply: str = proto.Field( - proto.STRING, - number=1, - ) - references: MutableSequence[Reference] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=Reference, - ) - summary: search_service.SearchResponse.Summary = proto.Field( - proto.MESSAGE, - number=3, - message=search_service.SearchResponse.Summary, - ) - - -class ConversationContext(proto.Message): - r"""Defines context of the conversation - - Attributes: - context_documents (MutableSequence[str]): - The current list of documents the user is - seeing. It contains the document resource - references. - active_document (str): - The current active document the user opened. - It contains the document resource reference. - """ - - context_documents: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - active_document: str = proto.Field( - proto.STRING, - number=2, - ) - - -class TextInput(proto.Message): - r"""Defines text input. - - Attributes: - input (str): - Text input. - context (google.cloud.discoveryengine_v1alpha.types.ConversationContext): - Conversation context of the input. - """ - - input: str = proto.Field( - proto.STRING, - number=1, - ) - context: 'ConversationContext' = proto.Field( - proto.MESSAGE, - number=2, - message='ConversationContext', - ) - - -class ConversationMessage(proto.Message): - r"""Defines a conversation 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: - user_input (google.cloud.discoveryengine_v1alpha.types.TextInput): - User text input. - - This field is a member of `oneof`_ ``message``. - reply (google.cloud.discoveryengine_v1alpha.types.Reply): - Search reply. - - This field is a member of `oneof`_ ``message``. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Message creation timestamp. - """ - - user_input: 'TextInput' = proto.Field( - proto.MESSAGE, - number=1, - oneof='message', - message='TextInput', - ) - reply: 'Reply' = proto.Field( - proto.MESSAGE, - number=2, - oneof='message', - message='Reply', - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/conversational_search_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/conversational_search_service.py deleted file mode 100644 index 22d4345b045d..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/conversational_search_service.py +++ /dev/null @@ -1,328 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.discoveryengine_v1alpha.types import conversation as gcd_conversation -from google.cloud.discoveryengine_v1alpha.types import search_service -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1alpha', - manifest={ - 'ConverseConversationRequest', - 'ConverseConversationResponse', - 'CreateConversationRequest', - 'UpdateConversationRequest', - 'DeleteConversationRequest', - 'GetConversationRequest', - 'ListConversationsRequest', - 'ListConversationsResponse', - }, -) - - -class ConverseConversationRequest(proto.Message): - r"""Request message for - [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1alpha.ConversationalSearchService.ConverseConversation] - method. - - Attributes: - name (str): - Required. The resource name of the Conversation to get. - Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}``. - Use - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/-`` - to activate auto session mode, which automatically creates a - new conversation inside a ConverseConversation session. - query (google.cloud.discoveryengine_v1alpha.types.TextInput): - Required. Current user input. - serving_config (str): - The resource name of the Serving Config to use. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/servingConfigs/{serving_config_id}`` - If this is not set, the default serving config will be used. - conversation (google.cloud.discoveryengine_v1alpha.types.Conversation): - The conversation to be used by auto session - only. The name field will be ignored as we - automatically assign new name for the - conversation in auto session. - safe_search (bool): - Whether to turn on safe search. - user_labels (MutableMapping[str, str]): - The user labels applied to a resource must meet the - following requirements: - - - Each resource can have multiple labels, up to a maximum - of 64. - - Each label must be a key-value pair. - - Keys have a minimum length of 1 character and a maximum - length of 63 characters and cannot be empty. Values can - be empty and have a maximum length of 63 characters. - - Keys and values can contain only lowercase letters, - numeric characters, underscores, and dashes. All - characters must use UTF-8 encoding, and international - characters are allowed. - - The key portion of a label must be unique. However, you - can use the same key with multiple resources. - - Keys must start with a lowercase letter or international - character. - - See `Google Cloud - Document `__ - for more details. - summary_spec (google.cloud.discoveryengine_v1alpha.types.SearchRequest.ContentSearchSpec.SummarySpec): - A specification for configuring the summary - returned in the response. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - query: gcd_conversation.TextInput = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_conversation.TextInput, - ) - serving_config: str = proto.Field( - proto.STRING, - number=3, - ) - conversation: gcd_conversation.Conversation = proto.Field( - proto.MESSAGE, - number=5, - message=gcd_conversation.Conversation, - ) - safe_search: bool = proto.Field( - proto.BOOL, - number=6, - ) - user_labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=7, - ) - summary_spec: search_service.SearchRequest.ContentSearchSpec.SummarySpec = proto.Field( - proto.MESSAGE, - number=8, - message=search_service.SearchRequest.ContentSearchSpec.SummarySpec, - ) - - -class ConverseConversationResponse(proto.Message): - r"""Response message for - [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1alpha.ConversationalSearchService.ConverseConversation] - method. - - Attributes: - reply (google.cloud.discoveryengine_v1alpha.types.Reply): - Answer to the current query. - conversation (google.cloud.discoveryengine_v1alpha.types.Conversation): - Updated conversation including the answer. - related_questions (MutableSequence[str]): - Suggested related questions. - search_results (MutableSequence[google.cloud.discoveryengine_v1alpha.types.SearchResponse.SearchResult]): - Search Results. - """ - - reply: gcd_conversation.Reply = proto.Field( - proto.MESSAGE, - number=1, - message=gcd_conversation.Reply, - ) - conversation: gcd_conversation.Conversation = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_conversation.Conversation, - ) - related_questions: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=6, - ) - search_results: MutableSequence[search_service.SearchResponse.SearchResult] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=search_service.SearchResponse.SearchResult, - ) - - -class CreateConversationRequest(proto.Message): - r"""Request for CreateConversation method. - - Attributes: - parent (str): - Required. Full resource name of parent data store. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` - conversation (google.cloud.discoveryengine_v1alpha.types.Conversation): - Required. The conversation to create. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - conversation: gcd_conversation.Conversation = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_conversation.Conversation, - ) - - -class UpdateConversationRequest(proto.Message): - r"""Request for UpdateConversation method. - - Attributes: - conversation (google.cloud.discoveryengine_v1alpha.types.Conversation): - Required. The Conversation to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - [Conversation][google.cloud.discoveryengine.v1alpha.Conversation] - to update. The following are NOT supported: - - - [conversation.name][] - - If not set or empty, all supported fields are updated. - """ - - conversation: gcd_conversation.Conversation = proto.Field( - proto.MESSAGE, - number=1, - message=gcd_conversation.Conversation, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteConversationRequest(proto.Message): - r"""Request for DeleteConversation method. - - Attributes: - name (str): - Required. The resource name of the Conversation to delete. - Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetConversationRequest(proto.Message): - r"""Request for GetConversation method. - - Attributes: - name (str): - Required. The resource name of the Conversation to get. - Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListConversationsRequest(proto.Message): - r"""Request for ListConversations method. - - Attributes: - parent (str): - Required. The data store resource name. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` - page_size (int): - Maximum number of results to return. If - unspecified, defaults to 50. Max allowed value - is 1000. - page_token (str): - A page token, received from a previous ``ListConversations`` - call. Provide this to retrieve the subsequent page. - filter (str): - A filter to apply on the list results. The supported - features are: user_pseudo_id, state. - - Example: "user_pseudo_id = some_id". - order_by (str): - A comma-separated list of fields to order by, sorted in - ascending order. Use "desc" after a field name for - descending. Supported fields: - - - ``update_time`` - - ``create_time`` - - ``conversation_name`` - - Example: "update_time desc" "create_time". - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - order_by: str = proto.Field( - proto.STRING, - number=5, - ) - - -class ListConversationsResponse(proto.Message): - r"""Response for ListConversations method. - - Attributes: - conversations (MutableSequence[google.cloud.discoveryengine_v1alpha.types.Conversation]): - All the Conversations for a given data store. - next_page_token (str): - Pagination token, if not returned indicates - the last page. - """ - - @property - def raw_page(self): - return self - - conversations: MutableSequence[gcd_conversation.Conversation] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcd_conversation.Conversation, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/document.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/document.py deleted file mode 100644 index 3e2c807e54d6..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/document.py +++ /dev/null @@ -1,189 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1alpha', - manifest={ - 'Document', - }, -) - - -class Document(proto.Message): - r"""Document captures all raw metadata information of items to be - recommended or searched. - - 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: - struct_data (google.protobuf.struct_pb2.Struct): - The structured JSON data for the document. It should conform - to the registered - [Schema][google.cloud.discoveryengine.v1alpha.Schema] or an - ``INVALID_ARGUMENT`` error is thrown. - - This field is a member of `oneof`_ ``data``. - json_data (str): - The JSON string representation of the document. It should - conform to the registered - [Schema][google.cloud.discoveryengine.v1alpha.Schema] or an - ``INVALID_ARGUMENT`` error is thrown. - - This field is a member of `oneof`_ ``data``. - name (str): - Immutable. The full resource name of the document. Format: - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document_id}``. - - This field must be a UTF-8 encoded string with a length - limit of 1024 characters. - id (str): - Immutable. The identifier of the document. - - Id should conform to - `RFC-1034 `__ standard - with a length limit of 63 characters. - schema_id (str): - The identifier of the schema located in the - same data store. - content (google.cloud.discoveryengine_v1alpha.types.Document.Content): - The unstructured data linked to this document. Content must - be set if this document is under a ``CONTENT_REQUIRED`` data - store. - parent_document_id (str): - The identifier of the parent document. Currently supports at - most two level document hierarchy. - - Id should conform to - `RFC-1034 `__ standard - with a length limit of 63 characters. - derived_struct_data (google.protobuf.struct_pb2.Struct): - Output only. This field is OUTPUT_ONLY. It contains derived - data that are not in the original input document. - """ - - class Content(proto.Message): - r"""Unstructured data linked to this document. - - 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: - raw_bytes (bytes): - The content represented as a stream of bytes. The maximum - length is 1,000,000 bytes (1 MB / ~0.95 MiB). - - Note: As with all ``bytes`` fields, this field is - represented as pure binary in Protocol Buffers and - base64-encoded string in JSON. For example, - ``abc123!?$*&()'-=@~`` should be represented as - ``YWJjMTIzIT8kKiYoKSctPUB+`` in JSON. See - https://developers.google.com/protocol-buffers/docs/proto3#json. - - This field is a member of `oneof`_ ``content``. - uri (str): - The URI of the content. Only Cloud Storage URIs (e.g. - ``gs://bucket-name/path/to/file``) are supported. The - maximum file size is 100 MB. - - This field is a member of `oneof`_ ``content``. - mime_type (str): - The MIME type of the content. Supported types: - - - ``application/pdf`` (PDF, only native PDFs are supported - for now) - - ``text/html`` (HTML) - - ``application/vnd.openxmlformats-officedocument.wordprocessingml.document`` - (DOCX) - - ``application/vnd.openxmlformats-officedocument.presentationml.presentation`` - (PPTX) - - ``text/plain`` (TXT) - - See - https://www.iana.org/assignments/media-types/media-types.xhtml. - """ - - raw_bytes: bytes = proto.Field( - proto.BYTES, - number=2, - oneof='content', - ) - uri: str = proto.Field( - proto.STRING, - number=3, - oneof='content', - ) - mime_type: str = proto.Field( - proto.STRING, - number=1, - ) - - struct_data: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=4, - oneof='data', - message=struct_pb2.Struct, - ) - json_data: str = proto.Field( - proto.STRING, - number=5, - oneof='data', - ) - name: str = proto.Field( - proto.STRING, - number=1, - ) - id: str = proto.Field( - proto.STRING, - number=2, - ) - schema_id: str = proto.Field( - proto.STRING, - number=3, - ) - content: Content = proto.Field( - proto.MESSAGE, - number=10, - message=Content, - ) - parent_document_id: str = proto.Field( - proto.STRING, - number=7, - ) - derived_struct_data: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=6, - message=struct_pb2.Struct, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/document_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/document_service.py deleted file mode 100644 index 22a55cdb5c53..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/document_service.py +++ /dev/null @@ -1,266 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.discoveryengine_v1alpha.types import document as gcd_document - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1alpha', - manifest={ - 'GetDocumentRequest', - 'ListDocumentsRequest', - 'ListDocumentsResponse', - 'CreateDocumentRequest', - 'UpdateDocumentRequest', - 'DeleteDocumentRequest', - }, -) - - -class GetDocumentRequest(proto.Message): - r"""Request message for - [DocumentService.GetDocument][google.cloud.discoveryengine.v1alpha.DocumentService.GetDocument] - method. - - Attributes: - name (str): - Required. Full resource name of - [Document][google.cloud.discoveryengine.v1alpha.Document], - such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. - - If the caller does not have permission to access the - [Document][google.cloud.discoveryengine.v1alpha.Document], - regardless of whether or not it exists, a - ``PERMISSION_DENIED`` error is returned. - - If the requested - [Document][google.cloud.discoveryengine.v1alpha.Document] - does not exist, a ``NOT_FOUND`` error is returned. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListDocumentsRequest(proto.Message): - r"""Request message for - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.ListDocuments] - method. - - Attributes: - parent (str): - Required. The parent branch resource name, such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. - Use ``default_branch`` as the branch ID, to list documents - under the default branch. - - If the caller does not have permission to list - [Document][google.cloud.discoveryengine.v1alpha.Document]s - under this branch, regardless of whether or not this branch - exists, a ``PERMISSION_DENIED`` error is returned. - page_size (int): - Maximum number of - [Document][google.cloud.discoveryengine.v1alpha.Document]s - to return. If unspecified, defaults to 100. The maximum - allowed value is 1000. Values above 1000 will be coerced to - 1000. - - If this field is negative, an ``INVALID_ARGUMENT`` error is - returned. - page_token (str): - A page token - [ListDocumentsResponse.next_page_token][google.cloud.discoveryengine.v1alpha.ListDocumentsResponse.next_page_token], - received from a previous - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.ListDocuments] - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.ListDocuments] - must match the call that provided the page token. Otherwise, - an ``INVALID_ARGUMENT`` error is returned. - """ - - 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 ListDocumentsResponse(proto.Message): - r"""Response message for - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.ListDocuments] - method. - - Attributes: - documents (MutableSequence[google.cloud.discoveryengine_v1alpha.types.Document]): - The - [Document][google.cloud.discoveryengine.v1alpha.Document]s. - next_page_token (str): - A token that can be sent as - [ListDocumentsRequest.page_token][google.cloud.discoveryengine.v1alpha.ListDocumentsRequest.page_token] - to retrieve the next page. If this field is omitted, there - are no subsequent pages. - """ - - @property - def raw_page(self): - return self - - documents: MutableSequence[gcd_document.Document] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcd_document.Document, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class CreateDocumentRequest(proto.Message): - r"""Request message for - [DocumentService.CreateDocument][google.cloud.discoveryengine.v1alpha.DocumentService.CreateDocument] - method. - - Attributes: - parent (str): - Required. The parent resource name, such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. - document (google.cloud.discoveryengine_v1alpha.types.Document): - Required. The - [Document][google.cloud.discoveryengine.v1alpha.Document] to - create. - document_id (str): - Required. The ID to use for the - [Document][google.cloud.discoveryengine.v1alpha.Document], - which will become the final component of the - [Document.name][google.cloud.discoveryengine.v1alpha.Document.name]. - - If the caller does not have permission to create the - [Document][google.cloud.discoveryengine.v1alpha.Document], - regardless of whether or not it exists, a - ``PERMISSION_DENIED`` error is returned. - - This field must be unique among all - [Document][google.cloud.discoveryengine.v1alpha.Document]s - with the same - [parent][google.cloud.discoveryengine.v1alpha.CreateDocumentRequest.parent]. - Otherwise, an ``ALREADY_EXISTS`` error is returned. - - This field must conform to - `RFC-1034 `__ standard - with a length limit of 63 characters. Otherwise, an - ``INVALID_ARGUMENT`` error is returned. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - document: gcd_document.Document = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_document.Document, - ) - document_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class UpdateDocumentRequest(proto.Message): - r"""Request message for - [DocumentService.UpdateDocument][google.cloud.discoveryengine.v1alpha.DocumentService.UpdateDocument] - method. - - Attributes: - document (google.cloud.discoveryengine_v1alpha.types.Document): - Required. The document to update/create. - - If the caller does not have permission to update the - [Document][google.cloud.discoveryengine.v1alpha.Document], - regardless of whether or not it exists, a - ``PERMISSION_DENIED`` error is returned. - - If the - [Document][google.cloud.discoveryengine.v1alpha.Document] to - update does not exist and - [allow_missing][google.cloud.discoveryengine.v1alpha.UpdateDocumentRequest.allow_missing] - is not set, a ``NOT_FOUND`` error is returned. - allow_missing (bool): - If set to true, and the - [Document][google.cloud.discoveryengine.v1alpha.Document] is - not found, a new - [Document][google.cloud.discoveryengine.v1alpha.Document] - will be created. - """ - - document: gcd_document.Document = proto.Field( - proto.MESSAGE, - number=1, - message=gcd_document.Document, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=2, - ) - - -class DeleteDocumentRequest(proto.Message): - r"""Request message for - [DocumentService.DeleteDocument][google.cloud.discoveryengine.v1alpha.DocumentService.DeleteDocument] - method. - - Attributes: - name (str): - Required. Full resource name of - [Document][google.cloud.discoveryengine.v1alpha.Document], - such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. - - If the caller does not have permission to delete the - [Document][google.cloud.discoveryengine.v1alpha.Document], - regardless of whether or not it exists, a - ``PERMISSION_DENIED`` error is returned. - - If the - [Document][google.cloud.discoveryengine.v1alpha.Document] to - delete does not exist, a ``NOT_FOUND`` error is returned. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/import_config.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/import_config.py deleted file mode 100644 index 34ef54f35016..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/import_config.py +++ /dev/null @@ -1,607 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.discoveryengine_v1alpha.types import document -from google.cloud.discoveryengine_v1alpha.types import user_event -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from google.type import date_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1alpha', - manifest={ - 'GcsSource', - 'BigQuerySource', - 'ImportErrorConfig', - 'ImportUserEventsRequest', - 'ImportUserEventsResponse', - 'ImportUserEventsMetadata', - 'ImportDocumentsMetadata', - 'ImportDocumentsRequest', - 'ImportDocumentsResponse', - }, -) - - -class GcsSource(proto.Message): - r"""Cloud Storage location for input content. - - Attributes: - input_uris (MutableSequence[str]): - Required. Cloud Storage URIs to input files. URI can be up - to 2000 characters long. URIs can match the full object path - (for example, ``gs://bucket/directory/object.json``) or a - pattern matching one or more files, such as - ``gs://bucket/directory/*.json``. - - A request can contain at most 100 files (or 100,000 files if - ``data_schema`` is ``content``). Each file can be up to 2 GB - (or 100 MB if ``data_schema`` is ``content``). - data_schema (str): - The schema to use when parsing the data from the source. - - Supported values for document imports: - - - ``document`` (default): One JSON - [Document][google.cloud.discoveryengine.v1alpha.Document] - per line. Each document must have a valid - [Document.id][google.cloud.discoveryengine.v1alpha.Document.id]. - - ``content``: Unstructured data (e.g. PDF, HTML). Each - file matched by ``input_uris`` becomes a document, with - the ID set to the first 128 bits of SHA256(URI) encoded - as a hex string. - - ``custom``: One custom data JSON per row in arbitrary - format that conforms to the defined - [Schema][google.cloud.discoveryengine.v1alpha.Schema] of - the data store. This can only be used by Gen App Builder. - - ``csv``: A CSV file with header conforming to the defined - [Schema][google.cloud.discoveryengine.v1alpha.Schema] of - the data store. Each entry after the header is imported - as a Document. This can only be used by Gen App Builder. - - Supported values for user even imports: - - - ``user_event`` (default): One JSON - [UserEvent][google.cloud.discoveryengine.v1alpha.UserEvent] - per line. - """ - - input_uris: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - data_schema: str = proto.Field( - proto.STRING, - number=2, - ) - - -class BigQuerySource(proto.Message): - r"""BigQuery source import data from. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - partition_date (google.type.date_pb2.Date): - BigQuery time partitioned table's \_PARTITIONDATE in - YYYY-MM-DD format. - - This field is a member of `oneof`_ ``partition``. - project_id (str): - The project ID (can be project # or ID) that - the BigQuery source is in with a length limit of - 128 characters. If not specified, inherits the - project ID from the parent request. - dataset_id (str): - Required. The BigQuery data set to copy the - data from with a length limit of 1,024 - characters. - table_id (str): - Required. The BigQuery table to copy the data - from with a length limit of 1,024 characters. - gcs_staging_dir (str): - Intermediate Cloud Storage directory used for - the import with a length limit of 2,000 - characters. Can be specified if one wants to - have the BigQuery export to a specific Cloud - Storage directory. - data_schema (str): - The schema to use when parsing the data from the source. - - Supported values for user event imports: - - - ``user_event`` (default): One - [UserEvent][google.cloud.discoveryengine.v1alpha.UserEvent] - per row. - - Supported values for document imports: - - - ``document`` (default): One - [Document][google.cloud.discoveryengine.v1alpha.Document] - format per row. Each document must have a valid - [Document.id][google.cloud.discoveryengine.v1alpha.Document.id] - and one of - [Document.json_data][google.cloud.discoveryengine.v1alpha.Document.json_data] - or - [Document.struct_data][google.cloud.discoveryengine.v1alpha.Document.struct_data]. - - ``custom``: One custom data per row in arbitrary format - that conforms to the defined - [Schema][google.cloud.discoveryengine.v1alpha.Schema] of - the data store. This can only be used by Gen App Builder. - """ - - partition_date: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=5, - oneof='partition', - message=date_pb2.Date, - ) - project_id: str = proto.Field( - proto.STRING, - number=1, - ) - dataset_id: str = proto.Field( - proto.STRING, - number=2, - ) - table_id: str = proto.Field( - proto.STRING, - number=3, - ) - gcs_staging_dir: str = proto.Field( - proto.STRING, - number=4, - ) - data_schema: str = proto.Field( - proto.STRING, - number=6, - ) - - -class ImportErrorConfig(proto.Message): - r"""Configuration of destination for Import related errors. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_prefix (str): - Cloud Storage prefix for import errors. This must be an - empty, existing Cloud Storage directory. Import errors are - written to sharded files in this directory, one per line, as - a JSON-encoded ``google.rpc.Status`` message. - - This field is a member of `oneof`_ ``destination``. - """ - - gcs_prefix: str = proto.Field( - proto.STRING, - number=1, - oneof='destination', - ) - - -class ImportUserEventsRequest(proto.Message): - r"""Request message for the ImportUserEvents request. - - 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: - inline_source (google.cloud.discoveryengine_v1alpha.types.ImportUserEventsRequest.InlineSource): - The Inline source for the input content for - UserEvents. - - This field is a member of `oneof`_ ``source``. - gcs_source (google.cloud.discoveryengine_v1alpha.types.GcsSource): - Cloud Storage location for the input content. - - This field is a member of `oneof`_ ``source``. - bigquery_source (google.cloud.discoveryengine_v1alpha.types.BigQuerySource): - BigQuery input source. - - This field is a member of `oneof`_ ``source``. - parent (str): - Required. Parent DataStore resource name, of the form - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}`` - error_config (google.cloud.discoveryengine_v1alpha.types.ImportErrorConfig): - The desired location of errors incurred - during the Import. Cannot be set for inline user - event imports. - """ - - class InlineSource(proto.Message): - r"""The inline source for the input config for ImportUserEvents - method. - - Attributes: - user_events (MutableSequence[google.cloud.discoveryengine_v1alpha.types.UserEvent]): - Required. A list of user events to import. - Recommended max of 10k items. - """ - - user_events: MutableSequence[user_event.UserEvent] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=user_event.UserEvent, - ) - - inline_source: InlineSource = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message=InlineSource, - ) - gcs_source: 'GcsSource' = proto.Field( - proto.MESSAGE, - number=3, - oneof='source', - message='GcsSource', - ) - bigquery_source: 'BigQuerySource' = proto.Field( - proto.MESSAGE, - number=4, - oneof='source', - message='BigQuerySource', - ) - parent: str = proto.Field( - proto.STRING, - number=1, - ) - error_config: 'ImportErrorConfig' = proto.Field( - proto.MESSAGE, - number=5, - message='ImportErrorConfig', - ) - - -class ImportUserEventsResponse(proto.Message): - r"""Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is returned by the - google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (MutableSequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - error_config (google.cloud.discoveryengine_v1alpha.types.ImportErrorConfig): - Echoes the destination for the complete - errors if this field was set in the request. - joined_events_count (int): - Count of user events imported with complete - existing Documents. - unjoined_events_count (int): - Count of user events imported, but with - Document information not found in the existing - Branch. - """ - - error_samples: MutableSequence[status_pb2.Status] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - error_config: 'ImportErrorConfig' = proto.Field( - proto.MESSAGE, - number=2, - message='ImportErrorConfig', - ) - joined_events_count: int = proto.Field( - proto.INT64, - number=3, - ) - unjoined_events_count: int = proto.Field( - proto.INT64, - number=4, - ) - - -class ImportUserEventsMetadata(proto.Message): - r"""Metadata related to the progress of the Import operation. - This is returned by the google.longrunning.Operation.metadata - field. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - success_count (int): - Count of entries that were processed - successfully. - failure_count (int): - Count of entries that encountered errors - while processing. - """ - - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - success_count: int = proto.Field( - proto.INT64, - number=3, - ) - failure_count: int = proto.Field( - proto.INT64, - number=4, - ) - - -class ImportDocumentsMetadata(proto.Message): - r"""Metadata related to the progress of the ImportDocuments - operation. This is returned by the - google.longrunning.Operation.metadata field. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - success_count (int): - Count of entries that were processed - successfully. - failure_count (int): - Count of entries that encountered errors - while processing. - """ - - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - success_count: int = proto.Field( - proto.INT64, - number=3, - ) - failure_count: int = proto.Field( - proto.INT64, - number=4, - ) - - -class ImportDocumentsRequest(proto.Message): - r"""Request message for Import methods. - - 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: - inline_source (google.cloud.discoveryengine_v1alpha.types.ImportDocumentsRequest.InlineSource): - The Inline source for the input content for - documents. - - This field is a member of `oneof`_ ``source``. - gcs_source (google.cloud.discoveryengine_v1alpha.types.GcsSource): - Cloud Storage location for the input content. - - This field is a member of `oneof`_ ``source``. - bigquery_source (google.cloud.discoveryengine_v1alpha.types.BigQuerySource): - BigQuery input source. - - This field is a member of `oneof`_ ``source``. - parent (str): - Required. The parent branch resource name, such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. - Requires create/update permission. - error_config (google.cloud.discoveryengine_v1alpha.types.ImportErrorConfig): - The desired location of errors incurred - during the Import. - reconciliation_mode (google.cloud.discoveryengine_v1alpha.types.ImportDocumentsRequest.ReconciliationMode): - The mode of reconciliation between existing documents and - the documents to be imported. Defaults to - [ReconciliationMode.INCREMENTAL][google.cloud.discoveryengine.v1alpha.ImportDocumentsRequest.ReconciliationMode.INCREMENTAL]. - auto_generate_ids (bool): - Whether to automatically generate IDs for the documents if - absent. - - If set to ``true``, - [Document.id][google.cloud.discoveryengine.v1alpha.Document.id]s - are automatically generated based on the hash of the - payload, where IDs may not be consistent during multiple - imports. In which case - [ReconciliationMode.FULL][google.cloud.discoveryengine.v1alpha.ImportDocumentsRequest.ReconciliationMode.FULL] - is highly recommended to avoid duplicate contents. If unset - or set to ``false``, - [Document.id][google.cloud.discoveryengine.v1alpha.Document.id]s - have to be specified using - [id_field][google.cloud.discoveryengine.v1alpha.ImportDocumentsRequest.id_field], - otherwise, documents without IDs fail to be imported. - - Only set this field when using - [GcsSource][google.cloud.discoveryengine.v1alpha.GcsSource] - or - [BigQuerySource][google.cloud.discoveryengine.v1alpha.BigQuerySource], - and when - [GcsSource.data_schema][google.cloud.discoveryengine.v1alpha.GcsSource.data_schema] - or - [BigQuerySource.data_schema][google.cloud.discoveryengine.v1alpha.BigQuerySource.data_schema] - is ``custom`` or ``csv``. Otherwise, an INVALID_ARGUMENT - error is thrown. - id_field (str): - The field in the Cloud Storage and BigQuery sources that - indicates the unique IDs of the documents. - - For - [GcsSource][google.cloud.discoveryengine.v1alpha.GcsSource] - it is the key of the JSON field. For instance, ``my_id`` for - JSON ``{"my_id": "some_uuid"}``. For - [BigQuerySource][google.cloud.discoveryengine.v1alpha.BigQuerySource] - it is the column name of the BigQuery table where the unique - ids are stored. - - The values of the JSON field or the BigQuery column are used - as the - [Document.id][google.cloud.discoveryengine.v1alpha.Document.id]s. - The JSON field or the BigQuery column must be of string - type, and the values must be set as valid strings conform to - `RFC-1034 `__ with 1-63 - characters. Otherwise, documents without valid IDs fail to - be imported. - - Only set this field when using - [GcsSource][google.cloud.discoveryengine.v1alpha.GcsSource] - or - [BigQuerySource][google.cloud.discoveryengine.v1alpha.BigQuerySource], - and when - [GcsSource.data_schema][google.cloud.discoveryengine.v1alpha.GcsSource.data_schema] - or - [BigQuerySource.data_schema][google.cloud.discoveryengine.v1alpha.BigQuerySource.data_schema] - is ``custom``. And only set this field when - [auto_generate_ids][google.cloud.discoveryengine.v1alpha.ImportDocumentsRequest.auto_generate_ids] - is unset or set as ``false``. Otherwise, an INVALID_ARGUMENT - error is thrown. - - If it is unset, a default value ``_id`` is used when - importing from the allowed data sources. - """ - class ReconciliationMode(proto.Enum): - r"""Indicates how imported documents are reconciled with the - existing documents created or imported before. - - Values: - RECONCILIATION_MODE_UNSPECIFIED (0): - Defaults to ``INCREMENTAL``. - INCREMENTAL (1): - Inserts new documents or updates existing - documents. - FULL (2): - Calculates diff and replaces the entire - document dataset. Existing documents may be - deleted if they are not present in the source - location. - """ - RECONCILIATION_MODE_UNSPECIFIED = 0 - INCREMENTAL = 1 - FULL = 2 - - class InlineSource(proto.Message): - r"""The inline source for the input config for ImportDocuments - method. - - Attributes: - documents (MutableSequence[google.cloud.discoveryengine_v1alpha.types.Document]): - Required. A list of documents to update/create. Each - document must have a valid - [Document.id][google.cloud.discoveryengine.v1alpha.Document.id]. - Recommended max of 100 items. - """ - - documents: MutableSequence[document.Document] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=document.Document, - ) - - inline_source: InlineSource = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message=InlineSource, - ) - gcs_source: 'GcsSource' = proto.Field( - proto.MESSAGE, - number=3, - oneof='source', - message='GcsSource', - ) - bigquery_source: 'BigQuerySource' = proto.Field( - proto.MESSAGE, - number=4, - oneof='source', - message='BigQuerySource', - ) - parent: str = proto.Field( - proto.STRING, - number=1, - ) - error_config: 'ImportErrorConfig' = proto.Field( - proto.MESSAGE, - number=5, - message='ImportErrorConfig', - ) - reconciliation_mode: ReconciliationMode = proto.Field( - proto.ENUM, - number=6, - enum=ReconciliationMode, - ) - auto_generate_ids: bool = proto.Field( - proto.BOOL, - number=8, - ) - id_field: str = proto.Field( - proto.STRING, - number=9, - ) - - -class ImportDocumentsResponse(proto.Message): - r"""Response of the - [ImportDocumentsRequest][google.cloud.discoveryengine.v1alpha.ImportDocumentsRequest]. - If the long running operation is done, then this message is returned - by the google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (MutableSequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - error_config (google.cloud.discoveryengine_v1alpha.types.ImportErrorConfig): - Echoes the destination for the complete - errors in the request if set. - """ - - error_samples: MutableSequence[status_pb2.Status] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - error_config: 'ImportErrorConfig' = proto.Field( - proto.MESSAGE, - number=2, - message='ImportErrorConfig', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/purge_config.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/purge_config.py deleted file mode 100644 index 8356f4a59877..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/purge_config.py +++ /dev/null @@ -1,247 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1alpha', - manifest={ - 'PurgeUserEventsRequest', - 'PurgeUserEventsResponse', - 'PurgeUserEventsMetadata', - 'PurgeDocumentsRequest', - 'PurgeDocumentsResponse', - 'PurgeDocumentsMetadata', - }, -) - - -class PurgeUserEventsRequest(proto.Message): - r"""Request message for PurgeUserEvents method. - - Attributes: - parent (str): - Required. The resource name of the catalog under which the - events are created. The format is - ``projects/${projectId}/locations/global/collections/{$collectionId}/dataStores/${dataStoreId}`` - filter (str): - Required. The filter string to specify the events to be - deleted with a length limit of 5,000 characters. The - eligible fields for filtering are: - - - ``eventType``: Double quoted - [UserEvent.event_type][google.cloud.discoveryengine.v1alpha.UserEvent.event_type] - string. - - ``eventTime``: in ISO 8601 "zulu" format. - - ``userPseudoId``: Double quoted string. Specifying this - will delete all events associated with a visitor. - - ``userId``: Double quoted string. Specifying this will - delete all events associated with a user. - - Examples: - - - Deleting all events in a time range: - ``eventTime > "2012-04-23T18:25:43.511Z" eventTime < "2012-04-23T18:30:43.511Z"`` - - Deleting specific eventType: ``eventType = "search"`` - - Deleting all events for a specific visitor: - ``userPseudoId = "visitor1024"`` - - Deleting all events inside a DataStore: ``*`` - - The filtering fields are assumed to have an implicit AND. - force (bool): - The ``force`` field is currently not supported. Purge user - event requests will permanently delete all purgeable events. - Once the development is complete: If ``force`` is set to - false, the method will return the expected purge count - without deleting any user events. This field will default to - false if not included in the request. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - force: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class PurgeUserEventsResponse(proto.Message): - r"""Response of the PurgeUserEventsRequest. If the long running - operation is successfully done, then this message is returned by - the google.longrunning.Operations.response field. - - Attributes: - purge_count (int): - The total count of events purged as a result - of the operation. - """ - - purge_count: int = proto.Field( - proto.INT64, - number=1, - ) - - -class PurgeUserEventsMetadata(proto.Message): - r"""Metadata related to the progress of the PurgeUserEvents - operation. This will be returned by the - google.longrunning.Operation.metadata field. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - success_count (int): - Count of entries that were deleted - successfully. - failure_count (int): - Count of entries that encountered errors - while processing. - """ - - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - success_count: int = proto.Field( - proto.INT64, - number=3, - ) - failure_count: int = proto.Field( - proto.INT64, - number=4, - ) - - -class PurgeDocumentsRequest(proto.Message): - r"""Request message for - [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.PurgeDocuments] - method. - - Attributes: - parent (str): - Required. The parent resource name, such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. - filter (str): - Required. Filter matching documents to purge. Only currently - supported value is ``*`` (all items). - force (bool): - Actually performs the purge. If ``force`` is set to false, - return the expected purge count without deleting any - documents. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - force: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class PurgeDocumentsResponse(proto.Message): - r"""Response message for - [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1alpha.DocumentService.PurgeDocuments] - method. If the long running operation is successfully done, then - this message is returned by the - google.longrunning.Operations.response field. - - Attributes: - purge_count (int): - The total count of documents purged as a - result of the operation. - purge_sample (MutableSequence[str]): - A sample of document names that will be deleted. Only - populated if ``force`` is set to false. A max of 100 names - will be returned and the names are chosen at random. - """ - - purge_count: int = proto.Field( - proto.INT64, - number=1, - ) - purge_sample: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class PurgeDocumentsMetadata(proto.Message): - r"""Metadata related to the progress of the PurgeDocuments - operation. This will be returned by the - google.longrunning.Operation.metadata field. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - success_count (int): - Count of entries that were deleted - successfully. - failure_count (int): - Count of entries that encountered errors - while processing. - """ - - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - success_count: int = proto.Field( - proto.INT64, - number=3, - ) - failure_count: int = proto.Field( - proto.INT64, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/recommendation_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/recommendation_service.py deleted file mode 100644 index 7aec69ccc590..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/recommendation_service.py +++ /dev/null @@ -1,287 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.discoveryengine_v1alpha.types import document as gcd_document -from google.cloud.discoveryengine_v1alpha.types import user_event as gcd_user_event -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1alpha', - manifest={ - 'RecommendRequest', - 'RecommendResponse', - }, -) - - -class RecommendRequest(proto.Message): - r"""Request message for Recommend method. - - Attributes: - serving_config (str): - Required. Full resource name of a - [ServingConfig][google.cloud.discoveryengine.v1alpha.ServingConfig]: - ``projects/*/locations/global/collections/*/engines/*/servingConfigs/*``, - or - ``projects/*/locations/global/collections/*/dataStores/*/servingConfigs/*`` - - One default serving config is created along with your - recommendation engine creation. The engine ID will be used - as the ID of the default serving config. For example, for - Engine - ``projects/*/locations/global/collections/*/engines/my-engine``, - you can use - ``projects/*/locations/global/collections/*/engines/my-engine/servingConfigs/my-engine`` - for your [Recommend][] requests. - user_event (google.cloud.discoveryengine_v1alpha.types.UserEvent): - Required. Context about the user, what they are looking at - and what action they took to trigger the Recommend request. - Note that this user event detail won't be ingested to - userEvent logs. Thus, a separate userEvent write request is - required for event logging. - - Don't set - [UserEvent.user_pseudo_id][google.cloud.discoveryengine.v1alpha.UserEvent.user_pseudo_id] - or - [UserEvent.user_info.user_id][google.cloud.discoveryengine.v1alpha.UserInfo.user_id] - to the same fixed ID for different users. If you are trying - to receive non-personalized recommendations (not - recommended; this can negatively impact model performance), - instead set - [UserEvent.user_pseudo_id][google.cloud.discoveryengine.v1alpha.UserEvent.user_pseudo_id] - to a random unique ID and leave - [UserEvent.user_info.user_id][google.cloud.discoveryengine.v1alpha.UserInfo.user_id] - unset. - page_size (int): - Maximum number of results to return. Set this - property to the number of recommendation results - needed. If zero, the service will choose a - reasonable default. The maximum allowed value is - 100. Values above 100 will be coerced to 100. - filter (str): - Filter for restricting recommendation results with a length - limit of 5,000 characters. Currently, only filter - expressions on the ``filter_tags`` attribute is supported. - - Examples: - - - ``(filter_tags: ANY("Red", "Blue") OR filter_tags: ANY("Hot", "Cold"))`` - - ``(filter_tags: ANY("Red", "Blue")) AND NOT (filter_tags: ANY("Green"))`` - - If ``attributeFilteringSyntax`` is set to true under the - ``params`` field, then attribute-based expressions are - expected instead of the above described tag-based syntax. - Examples: - - - (launguage: ANY("en", "es")) AND NOT (categories: - ANY("Movie")) - - (available: true) AND (launguage: ANY("en", "es")) OR - (categories: ANY("Movie")) - - If your filter blocks all results, the API will return - generic (unfiltered) popular Documents. If you only want - results strictly matching the filters, set - ``strictFiltering`` to True in - [RecommendRequest.params][google.cloud.discoveryengine.v1alpha.RecommendRequest.params] - to receive empty results instead. - - Note that the API will never return - [Document][google.cloud.discoveryengine.v1alpha.Document]s - with ``storageStatus`` of ``EXPIRED`` or ``DELETED`` - regardless of filter choices. - validate_only (bool): - Use validate only mode for this - recommendation query. If set to true, a fake - model will be used that returns arbitrary - Document IDs. Note that the validate only mode - should only be used for testing the API, or if - the model is not ready. - params (MutableMapping[str, google.protobuf.struct_pb2.Value]): - Additional domain specific parameters for the - recommendations. - - Allowed values: - - - ``returnDocument``: Boolean. If set to true, the - associated Document object will be returned in - [RecommendResponse.RecommendationResult.document][google.cloud.discoveryengine.v1alpha.RecommendResponse.RecommendationResult.document]. - - ``returnScore``: Boolean. If set to true, the - recommendation 'score' corresponding to each returned - Document will be set in - [RecommendResponse.RecommendationResult.metadata][google.cloud.discoveryengine.v1alpha.RecommendResponse.RecommendationResult.metadata]. - The given 'score' indicates the probability of a Document - conversion given the user's context and history. - - ``strictFiltering``: Boolean. True by default. If set to - false, the service will return generic (unfiltered) - popular Documents instead of empty if your filter blocks - all recommendation results. - - ``diversityLevel``: String. Default empty. If set to be - non-empty, then it needs to be one of: - - - ``no-diversity`` - - ``low-diversity`` - - ``medium-diversity`` - - ``high-diversity`` - - ``auto-diversity`` This gives request-level control - and adjusts recommendation results based on Document - category. - - - ``attributeFilteringSyntax``: Boolean. False by default. - If set to true, the ``filter`` field is interpreted - according to the new, attribute-based syntax. - user_labels (MutableMapping[str, str]): - The user labels applied to a resource must meet the - following requirements: - - - Each resource can have multiple labels, up to a maximum - of 64. - - Each label must be a key-value pair. - - Keys have a minimum length of 1 character and a maximum - length of 63 characters and cannot be empty. Values can - be empty and have a maximum length of 63 characters. - - Keys and values can contain only lowercase letters, - numeric characters, underscores, and dashes. All - characters must use UTF-8 encoding, and international - characters are allowed. - - The key portion of a label must be unique. However, you - can use the same key with multiple resources. - - Keys must start with a lowercase letter or international - character. - - See `Requirements for - labels `__ - for more details. - """ - - serving_config: str = proto.Field( - proto.STRING, - number=1, - ) - user_event: gcd_user_event.UserEvent = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_user_event.UserEvent, - ) - page_size: int = proto.Field( - proto.INT32, - number=3, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=5, - ) - params: MutableMapping[str, struct_pb2.Value] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=6, - message=struct_pb2.Value, - ) - user_labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=8, - ) - - -class RecommendResponse(proto.Message): - r"""Response message for Recommend method. - - Attributes: - results (MutableSequence[google.cloud.discoveryengine_v1alpha.types.RecommendResponse.RecommendationResult]): - A list of recommended Documents. The order - represents the ranking (from the most relevant - Document to the least). - attribution_token (str): - A unique attribution token. This should be included in the - [UserEvent][google.cloud.discoveryengine.v1alpha.UserEvent] - logs resulting from this recommendation, which enables - accurate attribution of recommendation model performance. - missing_ids (MutableSequence[str]): - IDs of documents in the request that were - missing from the default Branch associated with - the requested ServingConfig. - validate_only (bool): - True if - [RecommendRequest.validate_only][google.cloud.discoveryengine.v1alpha.RecommendRequest.validate_only] - was set. - """ - - class RecommendationResult(proto.Message): - r"""RecommendationResult represents a generic recommendation - result with associated metadata. - - Attributes: - id (str): - Resource ID of the recommended Document. - document (google.cloud.discoveryengine_v1alpha.types.Document): - Set if ``returnDocument`` is set to true in - [RecommendRequest.params][google.cloud.discoveryengine.v1alpha.RecommendRequest.params]. - metadata (MutableMapping[str, google.protobuf.struct_pb2.Value]): - Additional Document metadata / annotations. - - Possible values: - - - ``score``: Recommendation score in double value. Is set - if ``returnScore`` is set to true in - [RecommendRequest.params][google.cloud.discoveryengine.v1alpha.RecommendRequest.params]. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - document: gcd_document.Document = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_document.Document, - ) - metadata: MutableMapping[str, struct_pb2.Value] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=3, - message=struct_pb2.Value, - ) - - results: MutableSequence[RecommendationResult] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=RecommendationResult, - ) - attribution_token: str = proto.Field( - proto.STRING, - number=2, - ) - missing_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/schema.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/schema.py deleted file mode 100644 index 6907d55e59d8..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/schema.py +++ /dev/null @@ -1,413 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1alpha', - manifest={ - 'Schema', - 'FieldConfig', - }, -) - - -class Schema(proto.Message): - r"""Defines the structure and layout of a type of document data. - - 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: - struct_schema (google.protobuf.struct_pb2.Struct): - The structured representation of the schema. - - This field is a member of `oneof`_ ``schema``. - json_schema (str): - The JSON representation of the schema. - - This field is a member of `oneof`_ ``schema``. - name (str): - Immutable. The full resource name of the schema, in the - format of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. - - This field must be a UTF-8 encoded string with a length - limit of 1024 characters. - field_configs (MutableSequence[google.cloud.discoveryengine_v1alpha.types.FieldConfig]): - Output only. Configurations for fields of the - schema. - """ - - struct_schema: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=2, - oneof='schema', - message=struct_pb2.Struct, - ) - json_schema: str = proto.Field( - proto.STRING, - number=3, - oneof='schema', - ) - name: str = proto.Field( - proto.STRING, - number=1, - ) - field_configs: MutableSequence['FieldConfig'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='FieldConfig', - ) - - -class FieldConfig(proto.Message): - r"""Configurations for fields of a schema. For example, - configuring a field is indexable, or searchable. - - Attributes: - field_path (str): - Required. Field path of the schema field. For example: - ``title``, ``description``, ``release_info.release_year``. - field_type (google.cloud.discoveryengine_v1alpha.types.FieldConfig.FieldType): - Output only. Raw type of the field. - indexable_option (google.cloud.discoveryengine_v1alpha.types.FieldConfig.IndexableOption): - If - [indexable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.indexable_option] - is - [INDEXABLE_ENABLED][google.cloud.discoveryengine.v1alpha.FieldConfig.IndexableOption.INDEXABLE_ENABLED], - field values are indexed so that it can be filtered or - faceted in - [SearchService.Search][google.cloud.discoveryengine.v1alpha.SearchService.Search]. - - If - [indexable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.indexable_option] - is unset, the server behavior defaults to - [INDEXABLE_DISABLED][google.cloud.discoveryengine.v1alpha.FieldConfig.IndexableOption.INDEXABLE_DISABLED] - for fields that support setting indexable options. For those - fields that do not support setting indexable options, such - as ``object`` and ``boolean`` and key properties, the server - will skip - [indexable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.indexable_option] - setting, and setting - [indexable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.indexable_option] - for those fields will throw ``INVALID_ARGUMENT`` error. - dynamic_facetable_option (google.cloud.discoveryengine_v1alpha.types.FieldConfig.DynamicFacetableOption): - If - [dynamic_facetable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.dynamic_facetable_option] - is - [DYNAMIC_FACETABLE_ENABLED][google.cloud.discoveryengine.v1alpha.FieldConfig.DynamicFacetableOption.DYNAMIC_FACETABLE_ENABLED], - field values are available for dynamic facet. Could only be - [DYNAMIC_FACETABLE_DISABLED][google.cloud.discoveryengine.v1alpha.FieldConfig.DynamicFacetableOption.DYNAMIC_FACETABLE_DISABLED] - if - [FieldConfig.indexable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.indexable_option] - is - [INDEXABLE_DISABLED][google.cloud.discoveryengine.v1alpha.FieldConfig.IndexableOption.INDEXABLE_DISABLED]. - Otherwise, an ``INVALID_ARGUMENT`` error will be returned. - - If - [dynamic_facetable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.dynamic_facetable_option] - is unset, the server behavior defaults to - [DYNAMIC_FACETABLE_DISABLED][google.cloud.discoveryengine.v1alpha.FieldConfig.DynamicFacetableOption.DYNAMIC_FACETABLE_DISABLED] - for fields that support setting dynamic facetable options. - For those fields that do not support setting dynamic - facetable options, such as ``object`` and ``boolean``, the - server will skip dynamic facetable option setting, and - setting - [dynamic_facetable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.dynamic_facetable_option] - for those fields will throw ``INVALID_ARGUMENT`` error. - searchable_option (google.cloud.discoveryengine_v1alpha.types.FieldConfig.SearchableOption): - If - [searchable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.searchable_option] - is - [SEARCHABLE_ENABLED][google.cloud.discoveryengine.v1alpha.FieldConfig.SearchableOption.SEARCHABLE_ENABLED], - field values are searchable by text queries in - [SearchService.Search][google.cloud.discoveryengine.v1alpha.SearchService.Search]. - - If - [SEARCHABLE_ENABLED][google.cloud.discoveryengine.v1alpha.FieldConfig.SearchableOption.SEARCHABLE_ENABLED] - but field type is numerical, field values will not be - searchable by text queries in - [SearchService.Search][google.cloud.discoveryengine.v1alpha.SearchService.Search], - as there are no text values associated to numerical fields. - - If - [searchable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.searchable_option] - is unset, the server behavior defaults to - [SEARCHABLE_DISABLED][google.cloud.discoveryengine.v1alpha.FieldConfig.SearchableOption.SEARCHABLE_DISABLED] - for fields that support setting searchable options. Only - ``string`` fields that have no key property mapping support - setting - [searchable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.searchable_option]. - - For those fields that do not support setting searchable - options, the server will skip searchable option setting, and - setting - [searchable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.searchable_option] - for those fields will throw ``INVALID_ARGUMENT`` error. - retrievable_option (google.cloud.discoveryengine_v1alpha.types.FieldConfig.RetrievableOption): - If - [retrievable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.retrievable_option] - is - [RETRIEVABLE_ENABLED][google.cloud.discoveryengine.v1alpha.FieldConfig.RetrievableOption.RETRIEVABLE_ENABLED], - field values are included in the search results. - - If - [retrievable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.retrievable_option] - is unset, the server behavior defaults to - [RETRIEVABLE_DISABLED][google.cloud.discoveryengine.v1alpha.FieldConfig.RetrievableOption.RETRIEVABLE_DISABLED] - for fields that support setting retrievable options. For - those fields that do not support setting retrievable - options, such as ``object`` and ``boolean``, the server will - skip retrievable option setting, and setting - [retrievable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.retrievable_option] - for those fields will throw ``INVALID_ARGUMENT`` error. - completable_option (google.cloud.discoveryengine_v1alpha.types.FieldConfig.CompletableOption): - If - [completable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.completable_option] - is - [COMPLETABLE_ENABLED][google.cloud.discoveryengine.v1alpha.FieldConfig.CompletableOption.COMPLETABLE_ENABLED], - field values are directly used and returned as suggestions - for Autocomplete in - [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1alpha.CompletionService.CompleteQuery]. - - If - [completable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.completable_option] - is unset, the server behavior defaults to - [COMPLETABLE_DISABLED][google.cloud.discoveryengine.v1alpha.FieldConfig.CompletableOption.COMPLETABLE_DISABLED] - for fields that support setting completable options, which - are just ``string`` fields. For those fields that do not - support setting completable options, the server will skip - completable option setting, and setting - [completable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.completable_option] - for those fields will throw ``INVALID_ARGUMENT`` error. - recs_filterable_option (google.cloud.discoveryengine_v1alpha.types.FieldConfig.FilterableOption): - If - [recs_filterable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.recs_filterable_option] - is - [FILTERABLE_ENABLED][google.cloud.discoveryengine.v1alpha.FieldConfig.FilterableOption.FILTERABLE_ENABLED], - field values are filterable by filter expression in - [RecommendationService.Recommend][google.cloud.discoveryengine.v1alpha.RecommendationService.Recommend]. - - If - [FILTERABLE_ENABLED][google.cloud.discoveryengine.v1alpha.FieldConfig.FilterableOption.FILTERABLE_ENABLED] - but the field type is numerical, field values are not - filterable by text queries in - [RecommendationService.Recommend][google.cloud.discoveryengine.v1alpha.RecommendationService.Recommend]. - Only textual fields are supported. - - If - [recs_filterable_option][google.cloud.discoveryengine.v1alpha.FieldConfig.recs_filterable_option] - is unset, the default setting is - [FILTERABLE_DISABLED][google.cloud.discoveryengine.v1alpha.FieldConfig.FilterableOption.FILTERABLE_DISABLED] - for fields that support setting filterable options. - - When a field set to [FILTERABLE_DISABLED] is filtered, a - warning is generated and an empty result is returned. - key_property_type (str): - Output only. Type of the key property that this field is - mapped to. Empty string if this is not annotated as mapped - to a key property. - - Example types are ``title``, ``description``. Full list is - defined by ``keyPropertyMapping`` in the schema field - annotation. - - If the schema field has a ``KeyPropertyMapping`` annotation, - ``indexable_option`` and ``searchable_option`` of this field - cannot be modified. - """ - class FieldType(proto.Enum): - r"""Field value type in the Schema. - - Values: - FIELD_TYPE_UNSPECIFIED (0): - Field type is unspecified. - OBJECT (1): - Field value type is Object. - STRING (2): - Field value type is String. - NUMBER (3): - Field value type is Number. - INTEGER (4): - Field value type is Integer. - BOOLEAN (5): - Field value type is Boolean. - GEOLOCATION (6): - Field value type is Geolocation. - """ - FIELD_TYPE_UNSPECIFIED = 0 - OBJECT = 1 - STRING = 2 - NUMBER = 3 - INTEGER = 4 - BOOLEAN = 5 - GEOLOCATION = 6 - - class IndexableOption(proto.Enum): - r"""The setting of Indexable options in schema. - - Values: - INDEXABLE_OPTION_UNSPECIFIED (0): - Value used when unset. - INDEXABLE_ENABLED (1): - Indexable option enabled for a schema field. - INDEXABLE_DISABLED (2): - Indexable option disabled for a schema field. - """ - INDEXABLE_OPTION_UNSPECIFIED = 0 - INDEXABLE_ENABLED = 1 - INDEXABLE_DISABLED = 2 - - class DynamicFacetableOption(proto.Enum): - r"""The status of the dynamic facetable option of a schema field. - - Values: - DYNAMIC_FACETABLE_OPTION_UNSPECIFIED (0): - Value used when unset. - DYNAMIC_FACETABLE_ENABLED (1): - Dynamic facetable option enabled for a schema - field. - DYNAMIC_FACETABLE_DISABLED (2): - Dynamic facetable option disabled for a - schema field. - """ - DYNAMIC_FACETABLE_OPTION_UNSPECIFIED = 0 - DYNAMIC_FACETABLE_ENABLED = 1 - DYNAMIC_FACETABLE_DISABLED = 2 - - class SearchableOption(proto.Enum): - r"""The setting of Searchable options in schema. - - Values: - SEARCHABLE_OPTION_UNSPECIFIED (0): - Value used when unset. - SEARCHABLE_ENABLED (1): - Searchable option enabled for a schema field. - SEARCHABLE_DISABLED (2): - Searchable option disabled for a schema - field. - """ - SEARCHABLE_OPTION_UNSPECIFIED = 0 - SEARCHABLE_ENABLED = 1 - SEARCHABLE_DISABLED = 2 - - class RetrievableOption(proto.Enum): - r"""The setting of Retrievable options in schema. - - Values: - RETRIEVABLE_OPTION_UNSPECIFIED (0): - Value used when unset. - RETRIEVABLE_ENABLED (1): - Retrievable option enabled for a schema - field. - RETRIEVABLE_DISABLED (2): - Retrievable option disabled for a schema - field. - """ - RETRIEVABLE_OPTION_UNSPECIFIED = 0 - RETRIEVABLE_ENABLED = 1 - RETRIEVABLE_DISABLED = 2 - - class CompletableOption(proto.Enum): - r"""The setting of Completable options in schema. - - Values: - COMPLETABLE_OPTION_UNSPECIFIED (0): - Value used when unset. - COMPLETABLE_ENABLED (1): - Completable option enabled for a schema - field. - COMPLETABLE_DISABLED (2): - Completable option disabled for a schema - field. - """ - COMPLETABLE_OPTION_UNSPECIFIED = 0 - COMPLETABLE_ENABLED = 1 - COMPLETABLE_DISABLED = 2 - - class FilterableOption(proto.Enum): - r"""Sets the filterable option for schema fields. - - Values: - FILTERABLE_OPTION_UNSPECIFIED (0): - Value used when unset. - FILTERABLE_ENABLED (1): - Filterable option enabled for a schema field. - FILTERABLE_DISABLED (2): - Filterable option disabled for a schema - field. - """ - FILTERABLE_OPTION_UNSPECIFIED = 0 - FILTERABLE_ENABLED = 1 - FILTERABLE_DISABLED = 2 - - field_path: str = proto.Field( - proto.STRING, - number=1, - ) - field_type: FieldType = proto.Field( - proto.ENUM, - number=2, - enum=FieldType, - ) - indexable_option: IndexableOption = proto.Field( - proto.ENUM, - number=3, - enum=IndexableOption, - ) - dynamic_facetable_option: DynamicFacetableOption = proto.Field( - proto.ENUM, - number=4, - enum=DynamicFacetableOption, - ) - searchable_option: SearchableOption = proto.Field( - proto.ENUM, - number=5, - enum=SearchableOption, - ) - retrievable_option: RetrievableOption = proto.Field( - proto.ENUM, - number=6, - enum=RetrievableOption, - ) - completable_option: CompletableOption = proto.Field( - proto.ENUM, - number=8, - enum=CompletableOption, - ) - recs_filterable_option: FilterableOption = proto.Field( - proto.ENUM, - number=9, - enum=FilterableOption, - ) - key_property_type: str = proto.Field( - proto.STRING, - number=7, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/schema_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/schema_service.py deleted file mode 100644 index 0e7a35f7482a..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/schema_service.py +++ /dev/null @@ -1,291 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.discoveryengine_v1alpha.types import schema as gcd_schema -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1alpha', - manifest={ - 'GetSchemaRequest', - 'ListSchemasRequest', - 'ListSchemasResponse', - 'CreateSchemaRequest', - 'UpdateSchemaRequest', - 'DeleteSchemaRequest', - 'CreateSchemaMetadata', - 'UpdateSchemaMetadata', - 'DeleteSchemaMetadata', - }, -) - - -class GetSchemaRequest(proto.Message): - r"""Request message for - [SchemaService.GetSchema][google.cloud.discoveryengine.v1alpha.SchemaService.GetSchema] - method. - - Attributes: - name (str): - Required. The full resource name of the schema, in the - format of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListSchemasRequest(proto.Message): - r"""Request message for - [SchemaService.ListSchemas][google.cloud.discoveryengine.v1alpha.SchemaService.ListSchemas] - method. - - Attributes: - parent (str): - Required. The parent data store resource name, in the format - of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. - page_size (int): - The maximum number of - [Schema][google.cloud.discoveryengine.v1alpha.Schema]s to - return. The service may return fewer than this value. - - If unspecified, at most 100 - [Schema][google.cloud.discoveryengine.v1alpha.Schema]s will - be returned. - - The maximum value is 1000; values above 1000 will be coerced - to 1000. - page_token (str): - A page token, received from a previous - [SchemaService.ListSchemas][google.cloud.discoveryengine.v1alpha.SchemaService.ListSchemas] - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - [SchemaService.ListSchemas][google.cloud.discoveryengine.v1alpha.SchemaService.ListSchemas] - 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 ListSchemasResponse(proto.Message): - r"""Response message for - [SchemaService.ListSchemas][google.cloud.discoveryengine.v1alpha.SchemaService.ListSchemas] - method. - - Attributes: - schemas (MutableSequence[google.cloud.discoveryengine_v1alpha.types.Schema]): - The [Schema][google.cloud.discoveryengine.v1alpha.Schema]s. - next_page_token (str): - A token that can be sent as - [ListSchemasRequest.page_token][google.cloud.discoveryengine.v1alpha.ListSchemasRequest.page_token] - to retrieve the next page. If this field is omitted, there - are no subsequent pages. - """ - - @property - def raw_page(self): - return self - - schemas: MutableSequence[gcd_schema.Schema] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcd_schema.Schema, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class CreateSchemaRequest(proto.Message): - r"""Request message for - [SchemaService.CreateSchema][google.cloud.discoveryengine.v1alpha.SchemaService.CreateSchema] - method. - - Attributes: - parent (str): - Required. The parent data store resource name, in the format - of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. - schema (google.cloud.discoveryengine_v1alpha.types.Schema): - Required. The - [Schema][google.cloud.discoveryengine.v1alpha.Schema] to - create. - schema_id (str): - Required. The ID to use for the - [Schema][google.cloud.discoveryengine.v1alpha.Schema], which - will become the final component of the - [Schema.name][google.cloud.discoveryengine.v1alpha.Schema.name]. - - This field should conform to - `RFC-1034 `__ standard - with a length limit of 63 characters. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - schema: gcd_schema.Schema = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_schema.Schema, - ) - schema_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class UpdateSchemaRequest(proto.Message): - r"""Request message for - [SchemaService.UpdateSchema][google.cloud.discoveryengine.v1alpha.SchemaService.UpdateSchema] - method. - - Attributes: - schema (google.cloud.discoveryengine_v1alpha.types.Schema): - Required. The - [Schema][google.cloud.discoveryengine.v1alpha.Schema] to - update. - allow_missing (bool): - If set to true, and the - [Schema][google.cloud.discoveryengine.v1alpha.Schema] is not - found, a new - [Schema][google.cloud.discoveryengine.v1alpha.Schema] will - be created. In this situation, ``update_mask`` is ignored. - """ - - schema: gcd_schema.Schema = proto.Field( - proto.MESSAGE, - number=1, - message=gcd_schema.Schema, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class DeleteSchemaRequest(proto.Message): - r"""Request message for - [SchemaService.DeleteSchema][google.cloud.discoveryengine.v1alpha.SchemaService.DeleteSchema] - method. - - Attributes: - name (str): - Required. The full resource name of the schema, in the - format of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateSchemaMetadata(proto.Message): - r"""Metadata for Create Schema LRO. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - """ - - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - -class UpdateSchemaMetadata(proto.Message): - r"""Metadata for UpdateSchema LRO. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - """ - - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - -class DeleteSchemaMetadata(proto.Message): - r"""Metadata for DeleteSchema LRO. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - """ - - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/search_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/search_service.py deleted file mode 100644 index c8a300511f68..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/search_service.py +++ /dev/null @@ -1,1365 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.discoveryengine_v1alpha.types import common -from google.cloud.discoveryengine_v1alpha.types import document as gcd_document -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1alpha', - manifest={ - 'SearchRequest', - 'SearchResponse', - }, -) - - -class SearchRequest(proto.Message): - r"""Request message for - [SearchService.Search][google.cloud.discoveryengine.v1alpha.SearchService.Search] - method. - - Attributes: - serving_config (str): - Required. The resource name of the Search serving config, - such as - ``projects/*/locations/global/collections/default_collection/engines/*/servingConfigs/default_serving_config``, - or - ``projects/*/locations/global/collections/default_collection/dataStores/default_data_store/servingConfigs/default_serving_config``. - This field is used to identify the serving configuration - name, set of models used to make the search. - branch (str): - The branch resource name, such as - ``projects/*/locations/global/collections/default_collection/dataStores/default_data_store/branches/0``. - - Use ``default_branch`` as the branch ID or leave this field - empty, to search documents under the default branch. - query (str): - Raw search query. - image_query (google.cloud.discoveryengine_v1alpha.types.SearchRequest.ImageQuery): - Raw image query. - page_size (int): - Maximum number of - [Document][google.cloud.discoveryengine.v1alpha.Document]s - to return. If unspecified, defaults to a reasonable value. - The maximum allowed value is 100. Values above 100 are - coerced to 100. - - If this field is negative, an ``INVALID_ARGUMENT`` is - returned. - page_token (str): - A page token received from a previous - [SearchService.Search][google.cloud.discoveryengine.v1alpha.SearchService.Search] - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - [SearchService.Search][google.cloud.discoveryengine.v1alpha.SearchService.Search] - must match the call that provided the page token. Otherwise, - an ``INVALID_ARGUMENT`` error is returned. - offset (int): - A 0-indexed integer that specifies the current offset (that - is, starting result location, amongst the - [Document][google.cloud.discoveryengine.v1alpha.Document]s - deemed by the API as relevant) in search results. This field - is only considered if - [page_token][google.cloud.discoveryengine.v1alpha.SearchRequest.page_token] - is unset. - - If this field is negative, an ``INVALID_ARGUMENT`` is - returned. - filter (str): - The filter syntax consists of an expression language for - constructing a predicate from one or more fields of the - documents being filtered. Filter expression is - case-sensitive. - - If this field is unrecognizable, an ``INVALID_ARGUMENT`` is - returned. - - Filtering in Vertex AI Search is done by mapping the LHS - filter key to a key property defined in the Vertex AI Search - backend -- this mapping is defined by the customer in their - schema. For example a media customer might have a field - 'name' in their schema. In this case the filter would look - like this: filter --> name:'ANY("king kong")' - - For more information about filtering including syntax and - filter operators, see - `Filter `__ - order_by (str): - The order in which documents are returned. Documents can be - ordered by a field in an - [Document][google.cloud.discoveryengine.v1alpha.Document] - object. Leave it unset if ordered by relevance. ``order_by`` - expression is case-sensitive. For more information on - ordering, see - `Ordering `__ - - If this field is unrecognizable, an ``INVALID_ARGUMENT`` is - returned. - user_info (google.cloud.discoveryengine_v1alpha.types.UserInfo): - Information about the end user. Highly recommended for - analytics. - [UserInfo.user_agent][google.cloud.discoveryengine.v1alpha.UserInfo.user_agent] - is used to deduce ``device_type`` for analytics. - facet_specs (MutableSequence[google.cloud.discoveryengine_v1alpha.types.SearchRequest.FacetSpec]): - Facet specifications for faceted search. If empty, no facets - are returned. - - A maximum of 100 values are allowed. Otherwise, an - ``INVALID_ARGUMENT`` error is returned. - boost_spec (google.cloud.discoveryengine_v1alpha.types.SearchRequest.BoostSpec): - Boost specification to boost certain documents. For more - information on boosting, see - `Boosting `__ - params (MutableMapping[str, google.protobuf.struct_pb2.Value]): - Additional search parameters. - - For public website search only, supported values are: - - - ``user_country_code``: string. Default empty. If set to - non-empty, results are restricted or boosted based on the - location provided. Example: user_country_code: "au" - - For available codes see `Country - Codes `__ - - - ``search_type``: double. Default empty. Enables - non-webpage searching depending on the value. The only - valid non-default value is 1, which enables image - searching. Example: search_type: 1 - query_expansion_spec (google.cloud.discoveryengine_v1alpha.types.SearchRequest.QueryExpansionSpec): - The query expansion specification that - specifies the conditions under which query - expansion occurs. - spell_correction_spec (google.cloud.discoveryengine_v1alpha.types.SearchRequest.SpellCorrectionSpec): - The spell correction specification that - specifies the mode under which spell correction - takes effect. - user_pseudo_id (str): - A unique identifier for tracking visitors. For example, this - could be implemented with an HTTP cookie, which should be - able to uniquely identify a visitor on a single device. This - unique identifier should not change if the visitor logs in - or out of the website. - - This field should NOT have a fixed value such as - ``unknown_visitor``. - - This should be the same identifier as - [UserEvent.user_pseudo_id][google.cloud.discoveryengine.v1alpha.UserEvent.user_pseudo_id] - and - [CompleteQueryRequest.user_pseudo_id][google.cloud.discoveryengine.v1alpha.CompleteQueryRequest.user_pseudo_id] - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an ``INVALID_ARGUMENT`` error - is returned. - content_search_spec (google.cloud.discoveryengine_v1alpha.types.SearchRequest.ContentSearchSpec): - A specification for configuring the behavior - of content search. - embedding_spec (google.cloud.discoveryengine_v1alpha.types.SearchRequest.EmbeddingSpec): - Uses the provided embedding to do additional semantic - document retrieval. The retrieval is based on the dot - product of - [SearchRequest.embedding_spec.embedding_vectors.vector][] - and the document embedding that is provided in - [SearchRequest.embedding_spec.embedding_vectors.field_path][]. - - If - [SearchRequest.embedding_spec.embedding_vectors.field_path][] - is not provided, it will use - [ServingConfig.embedding_config.field_paths][]. - ranking_expression (str): - The ranking expression controls the customized ranking on - retrieval documents. This overrides - [ServingConfig.ranking_expression][google.cloud.discoveryengine.v1alpha.ServingConfig.ranking_expression]. - The ranking expression is a single function or multiple - functions that are joint by "+". - - - ranking_expression = function, { " + ", function }; - Supported functions: - - double \* relevance_score - - double \* dotProduct(embedding_field_path) Function - variables: ``relevance_score``: pre-defined keywords, - used for measure relevance between query and document. - ``embedding_field_path``: the document embedding field - used with query embedding vector. ``dotProduct``: - embedding function between embedding_field_path and query - embedding vector. - - Example ranking expression: If document has an embedding - field doc_embedding, the ranking expression could be - ``0.5 * relevance_score + 0.3 * dotProduct(doc_embedding)``. - safe_search (bool): - Whether to turn on safe search. This is only - supported for website search. - user_labels (MutableMapping[str, str]): - The user labels applied to a resource must meet the - following requirements: - - - Each resource can have multiple labels, up to a maximum - of 64. - - Each label must be a key-value pair. - - Keys have a minimum length of 1 character and a maximum - length of 63 characters and cannot be empty. Values can - be empty and have a maximum length of 63 characters. - - Keys and values can contain only lowercase letters, - numeric characters, underscores, and dashes. All - characters must use UTF-8 encoding, and international - characters are allowed. - - The key portion of a label must be unique. However, you - can use the same key with multiple resources. - - Keys must start with a lowercase letter or international - character. - - See `Google Cloud - Document `__ - for more details. - """ - - class ImageQuery(proto.Message): - r"""Specifies the image query input. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - image_bytes (str): - Base64 encoded image bytes. Supported image - formats: JPEG, PNG, and BMP. - - This field is a member of `oneof`_ ``image``. - """ - - image_bytes: str = proto.Field( - proto.STRING, - number=1, - oneof='image', - ) - - class FacetSpec(proto.Message): - r"""A facet specification to perform faceted search. - - Attributes: - facet_key (google.cloud.discoveryengine_v1alpha.types.SearchRequest.FacetSpec.FacetKey): - Required. The facet key specification. - limit (int): - Maximum of facet values that should be returned for this - facet. If unspecified, defaults to 20. The maximum allowed - value is 300. Values above 300 are coerced to 300. - - If this field is negative, an ``INVALID_ARGUMENT`` is - returned. - excluded_filter_keys (MutableSequence[str]): - List of keys to exclude when faceting. - - By default, - [FacetKey.key][google.cloud.discoveryengine.v1alpha.SearchRequest.FacetSpec.FacetKey.key] - is not excluded from the filter unless it is listed in this - field. - - Listing a facet key in this field allows its values to - appear as facet results, even when they are filtered out of - search results. Using this field does not affect what search - results are returned. - - For example, suppose there are 100 documents with the color - facet "Red" and 200 documents with the color facet "Blue". A - query containing the filter "color:ANY("Red")" and having - "color" as - [FacetKey.key][google.cloud.discoveryengine.v1alpha.SearchRequest.FacetSpec.FacetKey.key] - would by default return only "Red" documents in the search - results, and also return "Red" with count 100 as the only - color facet. Although there are also blue documents - available, "Blue" would not be shown as an available facet - value. - - If "color" is listed in "excludedFilterKeys", then the query - returns the facet values "Red" with count 100 and "Blue" - with count 200, because the "color" key is now excluded from - the filter. Because this field doesn't affect search - results, the search results are still correctly filtered to - return only "Red" documents. - - A maximum of 100 values are allowed. Otherwise, an - ``INVALID_ARGUMENT`` error is returned. - enable_dynamic_position (bool): - Enables dynamic position for this facet. If set to true, the - position of this facet among all facets in the response is - determined automatically. If dynamic facets are enabled, it - is ordered together. If set to false, the position of this - facet in the response is the same as in the request, and it - is ranked before the facets with dynamic position enable and - all dynamic facets. - - For example, you may always want to have rating facet - returned in the response, but it's not necessarily to always - display the rating facet at the top. In that case, you can - set enable_dynamic_position to true so that the position of - rating facet in response is determined automatically. - - Another example, assuming you have the following facets in - the request: - - - "rating", enable_dynamic_position = true - - - "price", enable_dynamic_position = false - - - "brands", enable_dynamic_position = false - - And also you have a dynamic facets enabled, which generates - a facet ``gender``. Then the final order of the facets in - the response can be ("price", "brands", "rating", "gender") - or ("price", "brands", "gender", "rating") depends on how - API orders "gender" and "rating" facets. However, notice - that "price" and "brands" are always ranked at first and - second position because their enable_dynamic_position is - false. - """ - - class FacetKey(proto.Message): - r"""Specifies how a facet is computed. - - Attributes: - key (str): - Required. Supported textual and numerical facet keys in - [Document][google.cloud.discoveryengine.v1alpha.Document] - object, over which the facet values are computed. Facet key - is case-sensitive. - intervals (MutableSequence[google.cloud.discoveryengine_v1alpha.types.Interval]): - Set only if values should be bucketed into - intervals. Must be set for facets with numerical - values. Must not be set for facet with text - values. Maximum number of intervals is 30. - restricted_values (MutableSequence[str]): - Only get facet for the given restricted values. Only - supported on textual fields. For example, suppose "category" - has three values "Action > 2022", "Action > 2021" and - "Sci-Fi > 2022". If set "restricted_values" to "Action > - 2022", the "category" facet only contains "Action > 2022". - Only supported on textual fields. Maximum is 10. - prefixes (MutableSequence[str]): - Only get facet values that start with the - given string prefix. For example, suppose - "category" has three values "Action > 2022", - "Action > 2021" and "Sci-Fi > 2022". If set - "prefixes" to "Action", the "category" facet - only contains "Action > 2022" and "Action > - 2021". Only supported on textual fields. Maximum - is 10. - contains (MutableSequence[str]): - Only get facet values that contains the given - strings. For example, suppose "category" has - three values "Action > 2022", "Action > 2021" - and "Sci-Fi > 2022". If set "contains" to - "2022", the "category" facet only contains - "Action > 2022" and "Sci-Fi > 2022". Only - supported on textual fields. Maximum is 10. - case_insensitive (bool): - True to make facet keys case insensitive when - getting faceting values with prefixes or - contains; false otherwise. - order_by (str): - The order in which documents are returned. - - Allowed values are: - - - "count desc", which means order by - [SearchResponse.Facet.values.count][google.cloud.discoveryengine.v1alpha.SearchResponse.Facet.FacetValue.count] - descending. - - - "value desc", which means order by - [SearchResponse.Facet.values.value][google.cloud.discoveryengine.v1alpha.SearchResponse.Facet.FacetValue.value] - descending. Only applies to textual facets. - - If not set, textual values are sorted in `natural - order `__; - numerical intervals are sorted in the order given by - [FacetSpec.FacetKey.intervals][google.cloud.discoveryengine.v1alpha.SearchRequest.FacetSpec.FacetKey.intervals]. - """ - - key: str = proto.Field( - proto.STRING, - number=1, - ) - intervals: MutableSequence[common.Interval] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=common.Interval, - ) - restricted_values: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - prefixes: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - contains: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - case_insensitive: bool = proto.Field( - proto.BOOL, - number=6, - ) - order_by: str = proto.Field( - proto.STRING, - number=7, - ) - - facet_key: 'SearchRequest.FacetSpec.FacetKey' = proto.Field( - proto.MESSAGE, - number=1, - message='SearchRequest.FacetSpec.FacetKey', - ) - limit: int = proto.Field( - proto.INT32, - number=2, - ) - excluded_filter_keys: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - enable_dynamic_position: bool = proto.Field( - proto.BOOL, - number=4, - ) - - class BoostSpec(proto.Message): - r"""Boost specification to boost certain documents. - - Attributes: - condition_boost_specs (MutableSequence[google.cloud.discoveryengine_v1alpha.types.SearchRequest.BoostSpec.ConditionBoostSpec]): - Condition boost specifications. If a document - matches multiple conditions in the - specifictions, boost scores from these - specifications are all applied and combined in a - non-linear way. Maximum number of specifications - is 20. - """ - - class ConditionBoostSpec(proto.Message): - r"""Boost applies to documents which match a condition. - - Attributes: - condition (str): - An expression which specifies a boost condition. The syntax - and supported fields are the same as a filter expression. - See - [SearchRequest.filter][google.cloud.discoveryengine.v1alpha.SearchRequest.filter] - for detail syntax and limitations. - - Examples: - - - To boost documents with document ID "doc_1" or "doc_2", - and color "Red" or "Blue": - - - (id: ANY("doc_1", "doc_2")) AND (color: - ANY("Red","Blue")) - boost (float): - Strength of the condition boost, which should be in [-1, 1]. - Negative boost means demotion. Default is 0.0. - - Setting to 1.0 gives the document a big promotion. However, - it does not necessarily mean that the boosted document will - be the top result at all times, nor that other documents - will be excluded. Results could still be shown even when - none of them matches the condition. And results that are - significantly more relevant to the search query can still - trump your heavily favored but irrelevant documents. - - Setting to -1.0 gives the document a big demotion. However, - results that are deeply relevant might still be shown. The - document will have an upstream battle to get a fairly high - ranking, but it is not blocked out completely. - - Setting to 0.0 means no boost applied. The boosting - condition is ignored. - """ - - condition: str = proto.Field( - proto.STRING, - number=1, - ) - boost: float = proto.Field( - proto.FLOAT, - number=2, - ) - - condition_boost_specs: MutableSequence['SearchRequest.BoostSpec.ConditionBoostSpec'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SearchRequest.BoostSpec.ConditionBoostSpec', - ) - - class QueryExpansionSpec(proto.Message): - r"""Specification to determine under which conditions query - expansion should occur. - - Attributes: - condition (google.cloud.discoveryengine_v1alpha.types.SearchRequest.QueryExpansionSpec.Condition): - The condition under which query expansion should occur. - Default to - [Condition.DISABLED][google.cloud.discoveryengine.v1alpha.SearchRequest.QueryExpansionSpec.Condition.DISABLED]. - pin_unexpanded_results (bool): - Whether to pin unexpanded results. If this - field is set to true, unexpanded products are - always at the top of the search results, - followed by the expanded results. - """ - class Condition(proto.Enum): - r"""Enum describing under which condition query expansion should - occur. - - Values: - CONDITION_UNSPECIFIED (0): - Unspecified query expansion condition. In this case, server - behavior defaults to - [Condition.DISABLED][google.cloud.discoveryengine.v1alpha.SearchRequest.QueryExpansionSpec.Condition.DISABLED]. - DISABLED (1): - Disabled query expansion. Only the exact search query is - used, even if - [SearchResponse.total_size][google.cloud.discoveryengine.v1alpha.SearchResponse.total_size] - is zero. - AUTO (2): - Automatic query expansion built by the Search - API. - """ - CONDITION_UNSPECIFIED = 0 - DISABLED = 1 - AUTO = 2 - - condition: 'SearchRequest.QueryExpansionSpec.Condition' = proto.Field( - proto.ENUM, - number=1, - enum='SearchRequest.QueryExpansionSpec.Condition', - ) - pin_unexpanded_results: bool = proto.Field( - proto.BOOL, - number=2, - ) - - class SpellCorrectionSpec(proto.Message): - r"""The specification for query spell correction. - - Attributes: - mode (google.cloud.discoveryengine_v1alpha.types.SearchRequest.SpellCorrectionSpec.Mode): - The mode under which spell correction should take effect to - replace the original search query. Default to - [Mode.AUTO][google.cloud.discoveryengine.v1alpha.SearchRequest.SpellCorrectionSpec.Mode.AUTO]. - """ - class Mode(proto.Enum): - r"""Enum describing under which mode spell correction should - occur. - - Values: - MODE_UNSPECIFIED (0): - Unspecified spell correction mode. In this case, server - behavior defaults to - [Mode.AUTO][google.cloud.discoveryengine.v1alpha.SearchRequest.SpellCorrectionSpec.Mode.AUTO]. - SUGGESTION_ONLY (1): - Search API will try to find a spell suggestion if there is - any and put in the - [SearchResponse.corrected_query][google.cloud.discoveryengine.v1alpha.SearchResponse.corrected_query]. - The spell suggestion will not be used as the search query. - AUTO (2): - Automatic spell correction built by the - Search API. Search will be based on the - corrected query if found. - """ - MODE_UNSPECIFIED = 0 - SUGGESTION_ONLY = 1 - AUTO = 2 - - mode: 'SearchRequest.SpellCorrectionSpec.Mode' = proto.Field( - proto.ENUM, - number=1, - enum='SearchRequest.SpellCorrectionSpec.Mode', - ) - - class ContentSearchSpec(proto.Message): - r"""A specification for configuring the behavior of content - search. - - Attributes: - snippet_spec (google.cloud.discoveryengine_v1alpha.types.SearchRequest.ContentSearchSpec.SnippetSpec): - If ``snippetSpec`` is not specified, snippets are not - included in the search response. - summary_spec (google.cloud.discoveryengine_v1alpha.types.SearchRequest.ContentSearchSpec.SummarySpec): - If ``summarySpec`` is not specified, summaries are not - included in the search response. - extractive_content_spec (google.cloud.discoveryengine_v1alpha.types.SearchRequest.ContentSearchSpec.ExtractiveContentSpec): - If there is no extractive_content_spec provided, there will - be no extractive answer in the search response. - """ - - class SnippetSpec(proto.Message): - r"""A specification for configuring snippets in a search - response. - - Attributes: - max_snippet_count (int): - [DEPRECATED] This field is deprecated. To control snippet - return, use ``return_snippet`` field. For backwards - compatibility, we will return snippet if max_snippet_count > - 0. - reference_only (bool): - [DEPRECATED] This field is deprecated and will have no - affect on the snippet. - return_snippet (bool): - If ``true``, then return snippet. If no snippet can be - generated, we return "No snippet is available for this - page." A ``snippet_status`` with ``SUCCESS`` or - ``NO_SNIPPET_AVAILABLE`` will also be returned. - """ - - max_snippet_count: int = proto.Field( - proto.INT32, - number=1, - ) - reference_only: bool = proto.Field( - proto.BOOL, - number=2, - ) - return_snippet: bool = proto.Field( - proto.BOOL, - number=3, - ) - - class SummarySpec(proto.Message): - r"""A specification for configuring a summary returned in a - search response. - - Attributes: - summary_result_count (int): - The number of top results to generate the summary from. If - the number of results returned is less than - ``summaryResultCount``, the summary is generated from all of - the results. - - At most five results can be used to generate a summary. - include_citations (bool): - Specifies whether to include citations in the summary. The - default value is ``false``. - - When this field is set to ``true``, summaries include - in-line citation numbers. - - Example summary including citations: - - BigQuery is Google Cloud's fully managed and completely - serverless enterprise data warehouse [1]. BigQuery supports - all data types, works across clouds, and has built-in - machine learning and business intelligence, all within a - unified platform [2, 3]. - - The citation numbers refer to the returned search results - and are 1-indexed. For example, [1] means that the sentence - is attributed to the first search result. [2, 3] means that - the sentence is attributed to both the second and third - search results. - ignore_adversarial_query (bool): - Specifies whether to filter out adversarial queries. The - default value is ``false``. - - Google employs search-query classification to detect - adversarial queries. No summary is returned if the search - query is classified as an adversarial query. For example, a - user might ask a question regarding negative comments about - the company or submit a query designed to generate unsafe, - policy-violating output. If this field is set to ``true``, - we skip generating summaries for adversarial queries and - return fallback messages instead. - ignore_non_summary_seeking_query (bool): - Specifies whether to filter out queries that are not - summary-seeking. The default value is ``false``. - - Google employs search-query classification to detect - summary-seeking queries. No summary is returned if the - search query is classified as a non-summary seeking query. - For example, ``why is the sky blue`` and - ``Who is the best soccer player in the world?`` are - summary-seeking queries, but ``SFO airport`` and - ``world cup 2026`` are not. They are most likely - navigational queries. If this field is set to ``true``, we - skip generating summaries for non-summary seeking queries - and return fallback messages instead. - language_code (str): - Language code for Summary. Use language tags defined by - `BCP47 `__. - Note: This is an experimental feature. - """ - - summary_result_count: int = proto.Field( - proto.INT32, - number=1, - ) - include_citations: bool = proto.Field( - proto.BOOL, - number=2, - ) - ignore_adversarial_query: bool = proto.Field( - proto.BOOL, - number=3, - ) - ignore_non_summary_seeking_query: bool = proto.Field( - proto.BOOL, - number=4, - ) - language_code: str = proto.Field( - proto.STRING, - number=6, - ) - - class ExtractiveContentSpec(proto.Message): - r"""A specification for configuring the extractive content in a - search response. - - Attributes: - max_extractive_answer_count (int): - The maximum number of extractive answers returned in each - search result. - - An extractive answer is a verbatim answer extracted from the - original document, which provides a precise and contextually - relevant answer to the search query. - - If the number of matching answers is less than the - ``max_extractive_answer_count``, return all of the answers. - Otherwise, return the ``max_extractive_answer_count``. - - At most one answer is returned for each - [SearchResult][google.cloud.discoveryengine.v1alpha.SearchResponse.SearchResult]. - max_extractive_segment_count (int): - The max number of extractive segments returned in each - search result. Only applied if the - [DataStore][google.cloud.discoveryengine.v1alpha.DataStore] - is set to - [DataStore.ContentConfig.CONTENT_REQUIRED][google.cloud.discoveryengine.v1alpha.DataStore.ContentConfig.CONTENT_REQUIRED] - or - [DataStore.solution_types][google.cloud.discoveryengine.v1alpha.DataStore.solution_types] - is - [SOLUTION_TYPE_CHAT][google.cloud.discoveryengine.v1alpha.SolutionType.SOLUTION_TYPE_CHAT]. - - An extractive segment is a text segment extracted from the - original document that is relevant to the search query, and, - in general, more verbose than an extractive answer. The - segment could then be used as input for LLMs to generate - summaries and answers. - - If the number of matching segments is less than - ``max_extractive_segment_count``, return all of the - segments. Otherwise, return the - ``max_extractive_segment_count``. - return_extractive_segment_score (bool): - Specifies whether to return the confidence score from the - extractive segments in each search result. The default value - is ``false``. - - Note: this is a priavte preview feature and only works for - allowlisted users, please reach out to Cloud Support team if - you want to use it. - num_previous_segments (int): - Specifies whether to also include the adjacent from each - selected segments. Return at most ``num_previous_segments`` - segments before each selected segments. - num_next_segments (int): - Return at most ``num_next_segments`` segments after each - selected segments. - """ - - max_extractive_answer_count: int = proto.Field( - proto.INT32, - number=1, - ) - max_extractive_segment_count: int = proto.Field( - proto.INT32, - number=2, - ) - return_extractive_segment_score: bool = proto.Field( - proto.BOOL, - number=3, - ) - num_previous_segments: int = proto.Field( - proto.INT32, - number=4, - ) - num_next_segments: int = proto.Field( - proto.INT32, - number=5, - ) - - snippet_spec: 'SearchRequest.ContentSearchSpec.SnippetSpec' = proto.Field( - proto.MESSAGE, - number=1, - message='SearchRequest.ContentSearchSpec.SnippetSpec', - ) - summary_spec: 'SearchRequest.ContentSearchSpec.SummarySpec' = proto.Field( - proto.MESSAGE, - number=2, - message='SearchRequest.ContentSearchSpec.SummarySpec', - ) - extractive_content_spec: 'SearchRequest.ContentSearchSpec.ExtractiveContentSpec' = proto.Field( - proto.MESSAGE, - number=3, - message='SearchRequest.ContentSearchSpec.ExtractiveContentSpec', - ) - - class EmbeddingSpec(proto.Message): - r"""The specification that uses customized query embedding vector - to do semantic document retrieval. - - Attributes: - embedding_vectors (MutableSequence[google.cloud.discoveryengine_v1alpha.types.SearchRequest.EmbeddingSpec.EmbeddingVector]): - The embedding vector used for retrieval. - Limit to 1. - """ - - class EmbeddingVector(proto.Message): - r"""Embedding vector. - - Attributes: - field_path (str): - Embedding field path in schema. - vector (MutableSequence[float]): - Query embedding vector. - """ - - field_path: str = proto.Field( - proto.STRING, - number=1, - ) - vector: MutableSequence[float] = proto.RepeatedField( - proto.FLOAT, - number=2, - ) - - embedding_vectors: MutableSequence['SearchRequest.EmbeddingSpec.EmbeddingVector'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SearchRequest.EmbeddingSpec.EmbeddingVector', - ) - - serving_config: str = proto.Field( - proto.STRING, - number=1, - ) - branch: str = proto.Field( - proto.STRING, - number=2, - ) - query: str = proto.Field( - proto.STRING, - number=3, - ) - image_query: ImageQuery = proto.Field( - proto.MESSAGE, - number=19, - message=ImageQuery, - ) - page_size: int = proto.Field( - proto.INT32, - number=4, - ) - page_token: str = proto.Field( - proto.STRING, - number=5, - ) - offset: int = proto.Field( - proto.INT32, - number=6, - ) - filter: str = proto.Field( - proto.STRING, - number=7, - ) - order_by: str = proto.Field( - proto.STRING, - number=8, - ) - user_info: common.UserInfo = proto.Field( - proto.MESSAGE, - number=21, - message=common.UserInfo, - ) - facet_specs: MutableSequence[FacetSpec] = proto.RepeatedField( - proto.MESSAGE, - number=9, - message=FacetSpec, - ) - boost_spec: BoostSpec = proto.Field( - proto.MESSAGE, - number=10, - message=BoostSpec, - ) - params: MutableMapping[str, struct_pb2.Value] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=11, - message=struct_pb2.Value, - ) - query_expansion_spec: QueryExpansionSpec = proto.Field( - proto.MESSAGE, - number=13, - message=QueryExpansionSpec, - ) - spell_correction_spec: SpellCorrectionSpec = proto.Field( - proto.MESSAGE, - number=14, - message=SpellCorrectionSpec, - ) - user_pseudo_id: str = proto.Field( - proto.STRING, - number=15, - ) - content_search_spec: ContentSearchSpec = proto.Field( - proto.MESSAGE, - number=24, - message=ContentSearchSpec, - ) - embedding_spec: EmbeddingSpec = proto.Field( - proto.MESSAGE, - number=23, - message=EmbeddingSpec, - ) - ranking_expression: str = proto.Field( - proto.STRING, - number=26, - ) - safe_search: bool = proto.Field( - proto.BOOL, - number=20, - ) - user_labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=22, - ) - - -class SearchResponse(proto.Message): - r"""Response message for - [SearchService.Search][google.cloud.discoveryengine.v1alpha.SearchService.Search] - method. - - Attributes: - results (MutableSequence[google.cloud.discoveryengine_v1alpha.types.SearchResponse.SearchResult]): - A list of matched documents. The order - represents the ranking. - facets (MutableSequence[google.cloud.discoveryengine_v1alpha.types.SearchResponse.Facet]): - Results of facets requested by user. - guided_search_result (google.cloud.discoveryengine_v1alpha.types.SearchResponse.GuidedSearchResult): - Guided search result. - total_size (int): - The estimated total count of matched items irrespective of - pagination. The count of - [results][google.cloud.discoveryengine.v1alpha.SearchResponse.results] - returned by pagination may be less than the - [total_size][google.cloud.discoveryengine.v1alpha.SearchResponse.total_size] - that matches. - attribution_token (str): - A unique search token. This should be included in the - [UserEvent][google.cloud.discoveryengine.v1alpha.UserEvent] - logs resulting from this search, which enables accurate - attribution of search model performance. - redirect_uri (str): - The URI of a customer-defined redirect page. If redirect - action is triggered, no search is performed, and only - [redirect_uri][google.cloud.discoveryengine.v1alpha.SearchResponse.redirect_uri] - and - [attribution_token][google.cloud.discoveryengine.v1alpha.SearchResponse.attribution_token] - are set in the response. - next_page_token (str): - A token that can be sent as - [SearchRequest.page_token][google.cloud.discoveryengine.v1alpha.SearchRequest.page_token] - to retrieve the next page. If this field is omitted, there - are no subsequent pages. - corrected_query (str): - Contains the spell corrected query, if found. If the spell - correction type is AUTOMATIC, then the search results are - based on corrected_query. Otherwise the original query is - used for search. - summary (google.cloud.discoveryengine_v1alpha.types.SearchResponse.Summary): - A summary as part of the search results. This field is only - returned if - [SearchRequest.ContentSearchSpec.summary_spec][google.cloud.discoveryengine.v1alpha.SearchRequest.ContentSearchSpec.summary_spec] - is set. - applied_controls (MutableSequence[str]): - Controls applied as part of the Control - service. - geo_search_debug_info (MutableSequence[google.cloud.discoveryengine_v1alpha.types.SearchResponse.GeoSearchDebugInfo]): - - query_expansion_info (google.cloud.discoveryengine_v1alpha.types.SearchResponse.QueryExpansionInfo): - Query expansion information for the returned - results. - """ - - class SearchResult(proto.Message): - r"""Represents the search results. - - Attributes: - id (str): - [Document.id][google.cloud.discoveryengine.v1alpha.Document.id] - of the searched - [Document][google.cloud.discoveryengine.v1alpha.Document]. - document (google.cloud.discoveryengine_v1alpha.types.Document): - The document data snippet in the search - response. Only fields that are marked as - retrievable are populated. - model_scores (MutableMapping[str, google.cloud.discoveryengine_v1alpha.types.DoubleList]): - Google provided available scores. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - document: gcd_document.Document = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_document.Document, - ) - model_scores: MutableMapping[str, common.DoubleList] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=4, - message=common.DoubleList, - ) - - class Facet(proto.Message): - r"""A facet result. - - Attributes: - key (str): - The key for this facet. E.g., "colors" or "price". It - matches - [SearchRequest.FacetSpec.FacetKey.key][google.cloud.discoveryengine.v1alpha.SearchRequest.FacetSpec.FacetKey.key]. - values (MutableSequence[google.cloud.discoveryengine_v1alpha.types.SearchResponse.Facet.FacetValue]): - The facet values for this field. - dynamic_facet (bool): - Whether the facet is dynamically generated. - """ - - class FacetValue(proto.Message): - r"""A facet value which contains value names and their count. - - 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: - value (str): - Text value of a facet, such as "Black" for - facet "colors". - - This field is a member of `oneof`_ ``facet_value``. - interval (google.cloud.discoveryengine_v1alpha.types.Interval): - Interval value for a facet, such as [10, 20) for facet - "price". It matches - [SearchRequest.FacetSpec.FacetKey.intervals][google.cloud.discoveryengine.v1alpha.SearchRequest.FacetSpec.FacetKey.intervals]. - - This field is a member of `oneof`_ ``facet_value``. - count (int): - Number of items that have this facet value. - """ - - value: str = proto.Field( - proto.STRING, - number=1, - oneof='facet_value', - ) - interval: common.Interval = proto.Field( - proto.MESSAGE, - number=2, - oneof='facet_value', - message=common.Interval, - ) - count: int = proto.Field( - proto.INT64, - number=3, - ) - - key: str = proto.Field( - proto.STRING, - number=1, - ) - values: MutableSequence['SearchResponse.Facet.FacetValue'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='SearchResponse.Facet.FacetValue', - ) - dynamic_facet: bool = proto.Field( - proto.BOOL, - number=3, - ) - - class GuidedSearchResult(proto.Message): - r"""Guided search result. The guided search helps user to refine - the search results and narrow down to the real needs from a - broaded search results. - - Attributes: - refinement_attributes (MutableSequence[google.cloud.discoveryengine_v1alpha.types.SearchResponse.GuidedSearchResult.RefinementAttribute]): - A list of ranked refinement attributes. - follow_up_questions (MutableSequence[str]): - Suggested follow-up questions. - """ - - class RefinementAttribute(proto.Message): - r"""Useful attribute for search result refinements. - - Attributes: - attribute_key (str): - Attribute key used to refine the results e.g. 'movie_type'. - attribute_value (str): - Attribute value used to refine the results - e.g. 'drama'. - """ - - attribute_key: str = proto.Field( - proto.STRING, - number=1, - ) - attribute_value: str = proto.Field( - proto.STRING, - number=2, - ) - - refinement_attributes: MutableSequence['SearchResponse.GuidedSearchResult.RefinementAttribute'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SearchResponse.GuidedSearchResult.RefinementAttribute', - ) - follow_up_questions: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - class Summary(proto.Message): - r"""Summary of the top N search result specified by the summary - spec. - - Attributes: - summary_text (str): - The summary content. - summary_skipped_reasons (MutableSequence[google.cloud.discoveryengine_v1alpha.types.SearchResponse.Summary.SummarySkippedReason]): - Additional summary-skipped reasons. This - provides the reason for ignored cases. If - nothing is skipped, this field is not set. - safety_attributes (google.cloud.discoveryengine_v1alpha.types.SearchResponse.Summary.SafetyAttributes): - A collection of Safety Attribute categories - and their associated confidence scores. - """ - class SummarySkippedReason(proto.Enum): - r"""An Enum for summary-skipped reasons. - - Values: - SUMMARY_SKIPPED_REASON_UNSPECIFIED (0): - Default value. The summary skipped reason is - not specified. - ADVERSARIAL_QUERY_IGNORED (1): - The adversarial query ignored case. - - Only populated when - [SummarySpec.ignore_adversarial_query][google.cloud.discoveryengine.v1alpha.SearchRequest.ContentSearchSpec.SummarySpec.ignore_adversarial_query] - is set to ``true``. - NON_SUMMARY_SEEKING_QUERY_IGNORED (2): - The non-summary seeking query ignored case. - - Only populated when - [SummarySpec.ignore_non_summary_seeking_query][google.cloud.discoveryengine.v1alpha.SearchRequest.ContentSearchSpec.SummarySpec.ignore_non_summary_seeking_query] - is set to ``true``. - OUT_OF_DOMAIN_QUERY_IGNORED (3): - The out-of-domain query ignored case. - - Google skips the summary if there are no - high-relevance search results. For example, the - data store contains facts about company A but - the user query is asking questions about company - B. - POTENTIAL_POLICY_VIOLATION (4): - The potential policy violation case. - - Google skips the summary if there is a potential - policy violation detected. This includes content - that may be violent or toxic. - LLM_ADDON_NOT_ENABLED (5): - The LLM addon not enabled case. - - Google skips the summary if the LLM addon is not - enabled. - """ - SUMMARY_SKIPPED_REASON_UNSPECIFIED = 0 - ADVERSARIAL_QUERY_IGNORED = 1 - NON_SUMMARY_SEEKING_QUERY_IGNORED = 2 - OUT_OF_DOMAIN_QUERY_IGNORED = 3 - POTENTIAL_POLICY_VIOLATION = 4 - LLM_ADDON_NOT_ENABLED = 5 - - class SafetyAttributes(proto.Message): - r"""Safety Attribute categories and their associated confidence - scores. - - Attributes: - categories (MutableSequence[str]): - The display names of Safety Attribute - categories associated with the generated - content. Order matches the Scores. - scores (MutableSequence[float]): - The confidence scores of the each category, - higher value means higher confidence. Order - matches the Categories. - """ - - categories: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - scores: MutableSequence[float] = proto.RepeatedField( - proto.FLOAT, - number=2, - ) - - summary_text: str = proto.Field( - proto.STRING, - number=1, - ) - summary_skipped_reasons: MutableSequence['SearchResponse.Summary.SummarySkippedReason'] = proto.RepeatedField( - proto.ENUM, - number=2, - enum='SearchResponse.Summary.SummarySkippedReason', - ) - safety_attributes: 'SearchResponse.Summary.SafetyAttributes' = proto.Field( - proto.MESSAGE, - number=3, - message='SearchResponse.Summary.SafetyAttributes', - ) - - class GeoSearchDebugInfo(proto.Message): - r"""Debug information specifically related to forward geocoding - issues arising from Geolocation Search. - - Attributes: - original_address_query (str): - The address from which forward geocoding - ingestion produced issues. - error_message (str): - The error produced. - """ - - original_address_query: str = proto.Field( - proto.STRING, - number=1, - ) - error_message: str = proto.Field( - proto.STRING, - number=2, - ) - - class QueryExpansionInfo(proto.Message): - r"""Information describing query expansion including whether - expansion has occurred. - - Attributes: - expanded_query (bool): - Bool describing whether query expansion has - occurred. - pinned_result_count (int): - Number of pinned results. This field will only be set when - expansion happens and - [SearchRequest.QueryExpansionSpec.pin_unexpanded_results][google.cloud.discoveryengine.v1alpha.SearchRequest.QueryExpansionSpec.pin_unexpanded_results] - is set to true. - """ - - expanded_query: bool = proto.Field( - proto.BOOL, - number=1, - ) - pinned_result_count: int = proto.Field( - proto.INT64, - number=2, - ) - - @property - def raw_page(self): - return self - - results: MutableSequence[SearchResult] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=SearchResult, - ) - facets: MutableSequence[Facet] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=Facet, - ) - guided_search_result: GuidedSearchResult = proto.Field( - proto.MESSAGE, - number=8, - message=GuidedSearchResult, - ) - total_size: int = proto.Field( - proto.INT32, - number=3, - ) - attribution_token: str = proto.Field( - proto.STRING, - number=4, - ) - redirect_uri: str = proto.Field( - proto.STRING, - number=12, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=5, - ) - corrected_query: str = proto.Field( - proto.STRING, - number=7, - ) - summary: Summary = proto.Field( - proto.MESSAGE, - number=9, - message=Summary, - ) - applied_controls: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=10, - ) - geo_search_debug_info: MutableSequence[GeoSearchDebugInfo] = proto.RepeatedField( - proto.MESSAGE, - number=16, - message=GeoSearchDebugInfo, - ) - query_expansion_info: QueryExpansionInfo = proto.Field( - proto.MESSAGE, - number=14, - message=QueryExpansionInfo, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/site_search_engine_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/site_search_engine_service.py deleted file mode 100644 index 55d34ab5fbbd..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/site_search_engine_service.py +++ /dev/null @@ -1,211 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1alpha', - manifest={ - 'RecrawlUrisRequest', - 'RecrawlUrisResponse', - 'RecrawlUrisMetadata', - }, -) - - -class RecrawlUrisRequest(proto.Message): - r"""Request message for - [SiteSearchEngineService.RecrawlUris][google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.RecrawlUris] - method. - - Attributes: - site_search_engine (str): - Required. Full resource name of the - [SiteSearchEngine][google.cloud.discoveryengine.v1alpha.SiteSearchEngine], - such as - ``projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine``. - uris (MutableSequence[str]): - Required. List of URIs to crawl. At most 10K URIs are - supported, otherwise an INVALID_ARGUMENT error is thrown. - Each URI should match at least one - [TargetSite][google.cloud.discoveryengine.v1alpha.TargetSite] - in ``site_search_engine``. - """ - - site_search_engine: str = proto.Field( - proto.STRING, - number=1, - ) - uris: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class RecrawlUrisResponse(proto.Message): - r"""Response message for - [SiteSearchEngineService.RecrawlUris][google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.RecrawlUris] - method. - - Attributes: - failure_samples (MutableSequence[google.cloud.discoveryengine_v1alpha.types.RecrawlUrisResponse.FailureInfo]): - Details for a sample of up to 10 ``failed_uris``. - failed_uris (MutableSequence[str]): - URIs that were not crawled before the LRO - terminated. - """ - - class FailureInfo(proto.Message): - r"""Details about why a particular URI failed to be crawled. Each - FailureInfo contains one FailureReason per CorpusType. - - Attributes: - uri (str): - URI that failed to be crawled. - failure_reasons (MutableSequence[google.cloud.discoveryengine_v1alpha.types.RecrawlUrisResponse.FailureInfo.FailureReason]): - List of failure reasons by corpus type (e.g. - desktop, mobile). - """ - - class FailureReason(proto.Message): - r"""Details about why crawling failed for a particular - CorpusType, e.g. DESKTOP and MOBILE crawling may fail for - different reasons. - - Attributes: - corpus_type (google.cloud.discoveryengine_v1alpha.types.RecrawlUrisResponse.FailureInfo.FailureReason.CorpusType): - DESKTOP, MOBILE, or CORPUS_TYPE_UNSPECIFIED. - error_message (str): - Reason why the URI was not crawled. - """ - class CorpusType(proto.Enum): - r"""CorpusType for the failed crawling operation. - - Values: - CORPUS_TYPE_UNSPECIFIED (0): - Default value. - DESKTOP (1): - Denotes a crawling attempt for the desktop - version of a page. - MOBILE (2): - Denotes a crawling attempt for the mobile - version of a page. - """ - CORPUS_TYPE_UNSPECIFIED = 0 - DESKTOP = 1 - MOBILE = 2 - - corpus_type: 'RecrawlUrisResponse.FailureInfo.FailureReason.CorpusType' = proto.Field( - proto.ENUM, - number=1, - enum='RecrawlUrisResponse.FailureInfo.FailureReason.CorpusType', - ) - error_message: str = proto.Field( - proto.STRING, - number=2, - ) - - uri: str = proto.Field( - proto.STRING, - number=1, - ) - failure_reasons: MutableSequence['RecrawlUrisResponse.FailureInfo.FailureReason'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='RecrawlUrisResponse.FailureInfo.FailureReason', - ) - - failure_samples: MutableSequence[FailureInfo] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=FailureInfo, - ) - failed_uris: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class RecrawlUrisMetadata(proto.Message): - r"""Metadata related to the progress of the - [SiteSearchEngineService.RecrawlUris][google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.RecrawlUris] - operation. This will be returned by the - google.longrunning.Operation.metadata field. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - invalid_uris (MutableSequence[str]): - Unique URIs in the request that don't match - any TargetSite in the DataStore, only match - TargetSites that haven't been fully indexed, or - match a TargetSite with type EXCLUDE. - valid_uris_count (int): - Total number of unique URIs in the request that are not in - invalid_uris. - success_count (int): - Total number of URIs that have been crawled - so far. - pending_count (int): - Total number of URIs that have yet to be - crawled. - quota_exceeded_count (int): - Total number of URIs that were rejected due - to insufficient indexing resources. - """ - - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - invalid_uris: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - valid_uris_count: int = proto.Field( - proto.INT32, - number=4, - ) - success_count: int = proto.Field( - proto.INT32, - number=5, - ) - pending_count: int = proto.Field( - proto.INT32, - number=6, - ) - quota_exceeded_count: int = proto.Field( - proto.INT32, - number=7, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/user_event.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/user_event.py deleted file mode 100644 index a0276c22fc7e..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/user_event.py +++ /dev/null @@ -1,761 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.discoveryengine_v1alpha.types import common -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1alpha', - manifest={ - 'UserEvent', - 'PageInfo', - 'SearchInfo', - 'CompletionInfo', - 'TransactionInfo', - 'DocumentInfo', - 'PanelInfo', - 'MediaInfo', - }, -) - - -class UserEvent(proto.Message): - r"""UserEvent captures all metadata information Discovery Engine - API needs to know about how end users interact with customers' - website. - - Attributes: - event_type (str): - Required. User event type. Allowed values are: - - Generic values: - - - ``search``: Search for Documents. - - ``view-item``: Detailed page view of a Document. - - ``view-item-list``: View of a panel or ordered list of - Documents. - - ``view-home-page``: View of the home page. - - ``view-category-page``: View of a category page, e.g. - Home > Men > Jeans - - Retail-related values: - - - ``add-to-cart``: Add an item(s) to cart, e.g. in Retail - online shopping - - ``purchase``: Purchase an item(s) - - Media-related values: - - - ``media-play``: Start/resume watching a video, playing a - song, etc. - - ``media-complete``: Finished or stopped midway through a - video, song, etc. - user_pseudo_id (str): - Required. A unique identifier for tracking visitors. - - For example, this could be implemented with an HTTP cookie, - which should be able to uniquely identify a visitor on a - single device. This unique identifier should not change if - the visitor log in/out of the website. - - Do not set the field to the same fixed ID for different - users. This mixes the event history of those users together, - which results in degraded model quality. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an ``INVALID_ARGUMENT`` error - is returned. - - The field should not contain PII or user-data. We recommend - to use Google Analytics `Client - ID `__ - for this field. - event_time (google.protobuf.timestamp_pb2.Timestamp): - Only required for - [UserEventService.ImportUserEvents][google.cloud.discoveryengine.v1alpha.UserEventService.ImportUserEvents] - method. Timestamp of when the user event happened. - user_info (google.cloud.discoveryengine_v1alpha.types.UserInfo): - Information about the end user. - direct_user_request (bool): - Should set to true if the request is made directly from the - end user, in which case the - [UserEvent.user_info.user_agent][google.cloud.discoveryengine.v1alpha.UserInfo.user_agent] - can be populated from the HTTP request. - - This flag should be set only if the API request is made - directly from the end user such as a mobile app (and not if - a gateway or a server is processing and pushing the user - events). - - This should not be set when using the JavaScript tag in - [UserEventService.CollectUserEvent][google.cloud.discoveryengine.v1alpha.UserEventService.CollectUserEvent]. - session_id (str): - A unique identifier for tracking a visitor session with a - length limit of 128 bytes. A session is an aggregation of an - end user behavior in a time span. - - A general guideline to populate the session_id: - - 1. If user has no activity for 30 min, a new session_id - should be assigned. - 2. The session_id should be unique across users, suggest use - uuid or add - [UserEvent.user_pseudo_id][google.cloud.discoveryengine.v1alpha.UserEvent.user_pseudo_id] - as prefix. - page_info (google.cloud.discoveryengine_v1alpha.types.PageInfo): - Page metadata such as categories and other critical - information for certain event types such as - ``view-category-page``. - attribution_token (str): - Token to attribute an API response to user action(s) to - trigger the event. - - Highly recommended for user events that are the result of - [RecommendationService.Recommend][google.cloud.discoveryengine.v1alpha.RecommendationService.Recommend]. - This field enables accurate attribution of recommendation - model performance. - - The value must be one of: - - - [RecommendResponse.attribution_token][google.cloud.discoveryengine.v1alpha.RecommendResponse.attribution_token] - for events that are the result of - [RecommendationService.Recommend][google.cloud.discoveryengine.v1alpha.RecommendationService.Recommend]. - - [SearchResponse.attribution_token][google.cloud.discoveryengine.v1alpha.SearchResponse.attribution_token] - for events that are the result of - [SearchService.Search][google.cloud.discoveryengine.v1alpha.SearchService.Search]. - - This token enables us to accurately attribute page view or - conversion completion back to the event and the particular - predict response containing this clicked/purchased product. - If user clicks on product K in the recommendation results, - pass - [RecommendResponse.attribution_token][google.cloud.discoveryengine.v1alpha.RecommendResponse.attribution_token] - as a URL parameter to product K's page. When recording - events on product K's page, log the - [RecommendResponse.attribution_token][google.cloud.discoveryengine.v1alpha.RecommendResponse.attribution_token] - to this field. - filter (str): - The filter syntax consists of an expression language for - constructing a predicate from one or more fields of the - documents being filtered. - - One example is for ``search`` events, the associated - [SearchRequest][google.cloud.discoveryengine.v1alpha.SearchRequest] - may contain a filter expression in - [SearchRequest.filter][google.cloud.discoveryengine.v1alpha.SearchRequest.filter] - conforming to https://google.aip.dev/160#filtering. - - Similarly, for ``view-item-list`` events that are generated - from a [RecommendationService.RecommendRequest][], this - field may be populated directly from - [RecommendationService.RecommendRequest.filter][] conforming - to https://google.aip.dev/160#filtering. - - The value must be a UTF-8 encoded string with a length limit - of 1,000 characters. Otherwise, an ``INVALID_ARGUMENT`` - error is returned. - documents (MutableSequence[google.cloud.discoveryengine_v1alpha.types.DocumentInfo]): - List of - [Document][google.cloud.discoveryengine.v1alpha.Document]s - associated with this user event. - - This field is optional except for the following event types: - - - ``view-item`` - - ``add-to-cart`` - - ``purchase`` - - ``media-play`` - - ``media-complete`` - - In a ``search`` event, this field represents the documents - returned to the end user on the current page (the end user - may have not finished browsing the whole page yet). When a - new page is returned to the end user, after - pagination/filtering/ordering even for the same query, a new - ``search`` event with different - [UserEvent.documents][google.cloud.discoveryengine.v1alpha.UserEvent.documents] - is desired. - panel (google.cloud.discoveryengine_v1alpha.types.PanelInfo): - Panel metadata associated with this user - event. - search_info (google.cloud.discoveryengine_v1alpha.types.SearchInfo): - [SearchService.Search][google.cloud.discoveryengine.v1alpha.SearchService.Search] - details related to the event. - - This field should be set for ``search`` event. - completion_info (google.cloud.discoveryengine_v1alpha.types.CompletionInfo): - [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1alpha.CompletionService.CompleteQuery] - details related to the event. - - This field should be set for ``search`` event when - autocomplete function is enabled and the user clicks a - suggestion for search. - transaction_info (google.cloud.discoveryengine_v1alpha.types.TransactionInfo): - The transaction metadata (if any) associated - with this user event. - tag_ids (MutableSequence[str]): - A list of identifiers for the independent - experiment groups this user event belongs to. - This is used to distinguish between user events - associated with different experiment setups on - the customer end. - promotion_ids (MutableSequence[str]): - The promotion IDs if this is an event - associated with promotions. Currently, this - field is restricted to at most one ID. - attributes (MutableMapping[str, google.cloud.discoveryengine_v1alpha.types.CustomAttribute]): - Extra user event features to include in the recommendation - model. These attributes must NOT contain data that needs to - be parsed or processed further, e.g. JSON or other - encodings. - - If you provide custom attributes for ingested user events, - also include them in the user events that you associate with - prediction requests. Custom attribute formatting must be - consistent between imported events and events provided with - prediction requests. This lets the Discovery Engine API use - those custom attributes when training models and serving - predictions, which helps improve recommendation quality. - - This field needs to pass all below criteria, otherwise an - ``INVALID_ARGUMENT`` error is returned: - - - The key must be a UTF-8 encoded string with a length - limit of 5,000 characters. - - For text attributes, at most 400 values are allowed. - Empty values are not allowed. Each value must be a UTF-8 - encoded string with a length limit of 256 characters. - - For number attributes, at most 400 values are allowed. - - For product recommendations, an example of extra user - information is ``traffic_channel``, which is how a user - arrives at the site. Users can arrive at the site by coming - to the site directly, coming through Google search, or in - other ways. - media_info (google.cloud.discoveryengine_v1alpha.types.MediaInfo): - Media-specific info. - """ - - event_type: str = proto.Field( - proto.STRING, - number=1, - ) - user_pseudo_id: str = proto.Field( - proto.STRING, - number=2, - ) - event_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - user_info: common.UserInfo = proto.Field( - proto.MESSAGE, - number=4, - message=common.UserInfo, - ) - direct_user_request: bool = proto.Field( - proto.BOOL, - number=5, - ) - session_id: str = proto.Field( - proto.STRING, - number=6, - ) - page_info: 'PageInfo' = proto.Field( - proto.MESSAGE, - number=7, - message='PageInfo', - ) - attribution_token: str = proto.Field( - proto.STRING, - number=8, - ) - filter: str = proto.Field( - proto.STRING, - number=9, - ) - documents: MutableSequence['DocumentInfo'] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message='DocumentInfo', - ) - panel: 'PanelInfo' = proto.Field( - proto.MESSAGE, - number=11, - message='PanelInfo', - ) - search_info: 'SearchInfo' = proto.Field( - proto.MESSAGE, - number=12, - message='SearchInfo', - ) - completion_info: 'CompletionInfo' = proto.Field( - proto.MESSAGE, - number=13, - message='CompletionInfo', - ) - transaction_info: 'TransactionInfo' = proto.Field( - proto.MESSAGE, - number=14, - message='TransactionInfo', - ) - tag_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=15, - ) - promotion_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=16, - ) - attributes: MutableMapping[str, common.CustomAttribute] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=17, - message=common.CustomAttribute, - ) - media_info: 'MediaInfo' = proto.Field( - proto.MESSAGE, - number=18, - message='MediaInfo', - ) - - -class PageInfo(proto.Message): - r"""Detailed page information. - - Attributes: - pageview_id (str): - A unique ID of a web page view. - - This should be kept the same for all user events triggered - from the same pageview. For example, an item detail page - view could trigger multiple events as the user is browsing - the page. The ``pageview_id`` property should be kept the - same for all these events so that they can be grouped - together properly. - - When using the client side event reporting with JavaScript - pixel and Google Tag Manager, this value is filled in - automatically. - page_category (str): - The most specific category associated with a category page. - - To represent full path of category, use '>' sign to separate - different hierarchies. If '>' is part of the category name, - please replace it with other character(s). - - Category pages include special pages such as sales or - promotions. For instance, a special sale page may have the - category hierarchy: - ``"pageCategory" : "Sales > 2017 Black Friday Deals"``. - - Required for ``view-category-page`` events. Other event - types should not set this field. Otherwise, an - ``INVALID_ARGUMENT`` error is returned. - uri (str): - Complete URL (window.location.href) of the - user's current page. - When using the client side event reporting with - JavaScript pixel and Google Tag Manager, this - value is filled in automatically. Maximum length - 5,000 characters. - referrer_uri (str): - The referrer URL of the current page. - - When using the client side event reporting with - JavaScript pixel and Google Tag Manager, this - value is filled in automatically. However, some - browser privacy restrictions may cause this - field to be empty. - """ - - pageview_id: str = proto.Field( - proto.STRING, - number=1, - ) - page_category: str = proto.Field( - proto.STRING, - number=2, - ) - uri: str = proto.Field( - proto.STRING, - number=3, - ) - referrer_uri: str = proto.Field( - proto.STRING, - number=4, - ) - - -class SearchInfo(proto.Message): - r"""Detailed search information. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - search_query (str): - The user's search query. - - See - [SearchRequest.query][google.cloud.discoveryengine.v1alpha.SearchRequest.query] - for definition. - - The value must be a UTF-8 encoded string with a length limit - of 5,000 characters. Otherwise, an ``INVALID_ARGUMENT`` - error is returned. - - At least one of - [search_query][google.cloud.discoveryengine.v1alpha.SearchInfo.search_query] - or - [PageInfo.page_category][google.cloud.discoveryengine.v1alpha.PageInfo.page_category] - is required for ``search`` events. Other event types should - not set this field. Otherwise, an ``INVALID_ARGUMENT`` error - is returned. - order_by (str): - The order in which products are returned, if applicable. - - See - [SearchRequest.order_by][google.cloud.discoveryengine.v1alpha.SearchRequest.order_by] - for definition and syntax. - - The value must be a UTF-8 encoded string with a length limit - of 1,000 characters. Otherwise, an ``INVALID_ARGUMENT`` - error is returned. - - This can only be set for ``search`` events. Other event - types should not set this field. Otherwise, an - ``INVALID_ARGUMENT`` error is returned. - offset (int): - An integer that specifies the current offset for pagination - (the 0-indexed starting location, amongst the products - deemed by the API as relevant). - - See - [SearchRequest.offset][google.cloud.discoveryengine.v1alpha.SearchRequest.offset] - for definition. - - If this field is negative, an ``INVALID_ARGUMENT`` is - returned. - - This can only be set for ``search`` events. Other event - types should not set this field. Otherwise, an - ``INVALID_ARGUMENT`` error is returned. - - This field is a member of `oneof`_ ``_offset``. - """ - - search_query: str = proto.Field( - proto.STRING, - number=1, - ) - order_by: str = proto.Field( - proto.STRING, - number=2, - ) - offset: int = proto.Field( - proto.INT32, - number=3, - optional=True, - ) - - -class CompletionInfo(proto.Message): - r"""Detailed completion information including completion - attribution token and clicked completion info. - - Attributes: - selected_suggestion (str): - End user selected - [CompleteQueryResponse.QuerySuggestion.suggestion][google.cloud.discoveryengine.v1alpha.CompleteQueryResponse.QuerySuggestion.suggestion]. - selected_position (int): - End user selected - [CompleteQueryResponse.QuerySuggestion.suggestion][google.cloud.discoveryengine.v1alpha.CompleteQueryResponse.QuerySuggestion.suggestion] - position, starting from 0. - """ - - selected_suggestion: str = proto.Field( - proto.STRING, - number=1, - ) - selected_position: int = proto.Field( - proto.INT32, - number=2, - ) - - -class TransactionInfo(proto.Message): - r"""A transaction represents the entire purchase transaction. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - value (float): - Required. Total non-zero value associated - with the transaction. This value may include - shipping, tax, or other adjustments to the total - value that you want to include. - - This field is a member of `oneof`_ ``_value``. - currency (str): - Required. Currency code. Use three-character - ISO-4217 code. - transaction_id (str): - The transaction ID with a length limit of 128 - characters. - tax (float): - All the taxes associated with the - transaction. - - This field is a member of `oneof`_ ``_tax``. - cost (float): - All the costs associated with the products. These can be - manufacturing costs, shipping expenses not borne by the end - user, or any other costs, such that: - - - Profit = - [value][google.cloud.discoveryengine.v1alpha.TransactionInfo.value] - - - [tax][google.cloud.discoveryengine.v1alpha.TransactionInfo.tax] - - - [cost][google.cloud.discoveryengine.v1alpha.TransactionInfo.cost] - - This field is a member of `oneof`_ ``_cost``. - discount_value (float): - The total discount(s) value applied to this transaction. - This figure should be excluded from - [TransactionInfo.value][google.cloud.discoveryengine.v1alpha.TransactionInfo.value] - - For example, if a user paid - [TransactionInfo.value][google.cloud.discoveryengine.v1alpha.TransactionInfo.value] - amount, then nominal (pre-discount) value of the transaction - is the sum of - [TransactionInfo.value][google.cloud.discoveryengine.v1alpha.TransactionInfo.value] - and - [TransactionInfo.discount_value][google.cloud.discoveryengine.v1alpha.TransactionInfo.discount_value] - - This means that profit is calculated the same way, - regardless of the discount value, and that - [TransactionInfo.discount_value][google.cloud.discoveryengine.v1alpha.TransactionInfo.discount_value] - can be larger than - [TransactionInfo.value][google.cloud.discoveryengine.v1alpha.TransactionInfo.value]: - - - Profit = - [value][google.cloud.discoveryengine.v1alpha.TransactionInfo.value] - - - [tax][google.cloud.discoveryengine.v1alpha.TransactionInfo.tax] - - - [cost][google.cloud.discoveryengine.v1alpha.TransactionInfo.cost] - - This field is a member of `oneof`_ ``_discount_value``. - """ - - value: float = proto.Field( - proto.FLOAT, - number=1, - optional=True, - ) - currency: str = proto.Field( - proto.STRING, - number=2, - ) - transaction_id: str = proto.Field( - proto.STRING, - number=3, - ) - tax: float = proto.Field( - proto.FLOAT, - number=4, - optional=True, - ) - cost: float = proto.Field( - proto.FLOAT, - number=5, - optional=True, - ) - discount_value: float = proto.Field( - proto.FLOAT, - number=6, - optional=True, - ) - - -class DocumentInfo(proto.Message): - r"""Detailed document information associated with a user event. - - 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: - id (str): - The - [Document][google.cloud.discoveryengine.v1alpha.Document] - resource ID. - - This field is a member of `oneof`_ ``document_descriptor``. - name (str): - The - [Document][google.cloud.discoveryengine.v1alpha.Document] - resource full name, of the form: - ``projects/{project_id}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}/branches/{branch_id}/documents/{document_id}`` - - This field is a member of `oneof`_ ``document_descriptor``. - uri (str): - The - [Document][google.cloud.discoveryengine.v1alpha.Document] - URI - only allowed for website data stores. - - This field is a member of `oneof`_ ``document_descriptor``. - quantity (int): - Quantity of the Document associated with the user event. - Defaults to 1. - - For example, this field will be 2 if two quantities of the - same Document are involved in a ``add-to-cart`` event. - - Required for events of the following event types: - - - ``add-to-cart`` - - ``purchase`` - - This field is a member of `oneof`_ ``_quantity``. - promotion_ids (MutableSequence[str]): - The promotion IDs associated with this - Document. Currently, this field is restricted to - at most one ID. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - oneof='document_descriptor', - ) - name: str = proto.Field( - proto.STRING, - number=2, - oneof='document_descriptor', - ) - uri: str = proto.Field( - proto.STRING, - number=6, - oneof='document_descriptor', - ) - quantity: int = proto.Field( - proto.INT32, - number=3, - optional=True, - ) - promotion_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - - -class PanelInfo(proto.Message): - r"""Detailed panel information associated with a user event. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - panel_id (str): - Required. The panel ID. - display_name (str): - The display name of the panel. - panel_position (int): - The ordered position of the panel, if shown to the user with - other panels. If set, then - [total_panels][google.cloud.discoveryengine.v1alpha.PanelInfo.total_panels] - must also be set. - - This field is a member of `oneof`_ ``_panel_position``. - total_panels (int): - The total number of panels, including this one, shown to the - user. Must be set if - [panel_position][google.cloud.discoveryengine.v1alpha.PanelInfo.panel_position] - is set. - - This field is a member of `oneof`_ ``_total_panels``. - """ - - panel_id: str = proto.Field( - proto.STRING, - number=2, - ) - display_name: str = proto.Field( - proto.STRING, - number=3, - ) - panel_position: int = proto.Field( - proto.INT32, - number=4, - optional=True, - ) - total_panels: int = proto.Field( - proto.INT32, - number=5, - optional=True, - ) - - -class MediaInfo(proto.Message): - r"""Media-specific user event information. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - media_progress_duration (google.protobuf.duration_pb2.Duration): - The media progress time in seconds, if applicable. For - example, if the end user has finished 90 seconds of a - playback video, then - [MediaInfo.media_progress_duration.seconds][google.protobuf.Duration.seconds] - should be set to 90. - media_progress_percentage (float): - Media progress should be computed using only the - [media_progress_duration][google.cloud.discoveryengine.v1alpha.MediaInfo.media_progress_duration] - relative to the media total length. - - This value must be between ``[0, 1.0]`` inclusive. - - If this is not a playback or the progress cannot be computed - (e.g. ongoing livestream), this field should be unset. - - This field is a member of `oneof`_ ``_media_progress_percentage``. - """ - - media_progress_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - media_progress_percentage: float = proto.Field( - proto.FLOAT, - number=2, - optional=True, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/user_event_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/user_event_service.py deleted file mode 100644 index c5ec95071940..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/user_event_service.py +++ /dev/null @@ -1,110 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.discoveryengine_v1alpha.types import user_event as gcd_user_event - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1alpha', - manifest={ - 'WriteUserEventRequest', - 'CollectUserEventRequest', - }, -) - - -class WriteUserEventRequest(proto.Message): - r"""Request message for WriteUserEvent method. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - parent (str): - Required. The parent DataStore resource name, such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. - user_event (google.cloud.discoveryengine_v1alpha.types.UserEvent): - Required. User event to write. - - This field is a member of `oneof`_ ``_user_event``. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - user_event: gcd_user_event.UserEvent = proto.Field( - proto.MESSAGE, - number=2, - optional=True, - message=gcd_user_event.UserEvent, - ) - - -class CollectUserEventRequest(proto.Message): - r"""Request message for CollectUserEvent method. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - parent (str): - Required. The parent DataStore resource name, such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. - user_event (str): - Required. URL encoded UserEvent proto with a - length limit of 2,000,000 characters. - uri (str): - The URL including cgi-parameters but - excluding the hash fragment with a length limit - of 5,000 characters. This is often more useful - than the referer URL, because many browsers only - send the domain for third-party requests. - - This field is a member of `oneof`_ ``_uri``. - ets (int): - The event timestamp in milliseconds. This - prevents browser caching of otherwise identical - get requests. The name is abbreviated to reduce - the payload bytes. - - This field is a member of `oneof`_ ``_ets``. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - user_event: str = proto.Field( - proto.STRING, - number=2, - ) - uri: str = proto.Field( - proto.STRING, - number=3, - optional=True, - ) - ets: int = proto.Field( - proto.INT64, - number=4, - optional=True, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/mypy.ini b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/noxfile.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/noxfile.py deleted file mode 100644 index dfc37936ccfa..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/noxfile.py +++ /dev/null @@ -1,184 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.11" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "lint_setup_py", -] - -@nox.session(python=ALL_PYTHON) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/discoveryengine_v1alpha/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - 'mypy', - 'types-requests', - 'types-protobuf' - ) - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==7.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_completion_service_complete_query_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_completion_service_complete_query_async.py deleted file mode 100644 index 5c669849a195..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_completion_service_complete_query_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CompleteQuery -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_CompletionService_CompleteQuery_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -async def sample_complete_query(): - # Create a client - client = discoveryengine_v1alpha.CompletionServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.CompleteQueryRequest( - data_store="data_store_value", - query="query_value", - ) - - # Make the request - response = await client.complete_query(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_CompletionService_CompleteQuery_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_completion_service_complete_query_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_completion_service_complete_query_sync.py deleted file mode 100644 index 6e01114696ff..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_completion_service_complete_query_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CompleteQuery -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_CompletionService_CompleteQuery_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -def sample_complete_query(): - # Create a client - client = discoveryengine_v1alpha.CompletionServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.CompleteQueryRequest( - data_store="data_store_value", - query="query_value", - ) - - # Make the request - response = client.complete_query(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_CompletionService_CompleteQuery_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_converse_conversation_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_converse_conversation_async.py deleted file mode 100644 index b92f6208cb53..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_converse_conversation_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ConverseConversation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_ConversationalSearchService_ConverseConversation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -async def sample_converse_conversation(): - # Create a client - client = discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.ConverseConversationRequest( - name="name_value", - ) - - # Make the request - response = await client.converse_conversation(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_ConversationalSearchService_ConverseConversation_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_converse_conversation_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_converse_conversation_sync.py deleted file mode 100644 index c729b8e5128a..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_converse_conversation_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ConverseConversation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_ConversationalSearchService_ConverseConversation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -def sample_converse_conversation(): - # Create a client - client = discoveryengine_v1alpha.ConversationalSearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.ConverseConversationRequest( - name="name_value", - ) - - # Make the request - response = client.converse_conversation(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_ConversationalSearchService_ConverseConversation_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_create_conversation_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_create_conversation_async.py deleted file mode 100644 index 6b3581f3ec78..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_create_conversation_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateConversation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_ConversationalSearchService_CreateConversation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -async def sample_create_conversation(): - # Create a client - client = discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.CreateConversationRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_conversation(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_ConversationalSearchService_CreateConversation_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_create_conversation_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_create_conversation_sync.py deleted file mode 100644 index 083ae91a8a5a..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_create_conversation_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateConversation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_ConversationalSearchService_CreateConversation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -def sample_create_conversation(): - # Create a client - client = discoveryengine_v1alpha.ConversationalSearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.CreateConversationRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_conversation(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_ConversationalSearchService_CreateConversation_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_delete_conversation_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_delete_conversation_async.py deleted file mode 100644 index 6be302999234..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_delete_conversation_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteConversation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_ConversationalSearchService_DeleteConversation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -async def sample_delete_conversation(): - # Create a client - client = discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.DeleteConversationRequest( - name="name_value", - ) - - # Make the request - await client.delete_conversation(request=request) - - -# [END discoveryengine_v1alpha_generated_ConversationalSearchService_DeleteConversation_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_delete_conversation_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_delete_conversation_sync.py deleted file mode 100644 index ef3206f9d867..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_delete_conversation_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteConversation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_ConversationalSearchService_DeleteConversation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -def sample_delete_conversation(): - # Create a client - client = discoveryengine_v1alpha.ConversationalSearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.DeleteConversationRequest( - name="name_value", - ) - - # Make the request - client.delete_conversation(request=request) - - -# [END discoveryengine_v1alpha_generated_ConversationalSearchService_DeleteConversation_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_get_conversation_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_get_conversation_async.py deleted file mode 100644 index 8f8a2ed38b12..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_get_conversation_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetConversation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_ConversationalSearchService_GetConversation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -async def sample_get_conversation(): - # Create a client - client = discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.GetConversationRequest( - name="name_value", - ) - - # Make the request - response = await client.get_conversation(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_ConversationalSearchService_GetConversation_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_get_conversation_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_get_conversation_sync.py deleted file mode 100644 index a890c360cac6..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_get_conversation_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetConversation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_ConversationalSearchService_GetConversation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -def sample_get_conversation(): - # Create a client - client = discoveryengine_v1alpha.ConversationalSearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.GetConversationRequest( - name="name_value", - ) - - # Make the request - response = client.get_conversation(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_ConversationalSearchService_GetConversation_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_list_conversations_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_list_conversations_async.py deleted file mode 100644 index 43cd740fdb04..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_list_conversations_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListConversations -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_ConversationalSearchService_ListConversations_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -async def sample_list_conversations(): - # Create a client - client = discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.ListConversationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversations(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END discoveryengine_v1alpha_generated_ConversationalSearchService_ListConversations_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_list_conversations_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_list_conversations_sync.py deleted file mode 100644 index 4ea900cd1c37..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_list_conversations_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListConversations -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_ConversationalSearchService_ListConversations_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -def sample_list_conversations(): - # Create a client - client = discoveryengine_v1alpha.ConversationalSearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.ListConversationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversations(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END discoveryengine_v1alpha_generated_ConversationalSearchService_ListConversations_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_update_conversation_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_update_conversation_async.py deleted file mode 100644 index 53d6e3b5f804..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_update_conversation_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for 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-discoveryengine - - -# [START discoveryengine_v1alpha_generated_ConversationalSearchService_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 discoveryengine_v1alpha - - -async def sample_update_conversation(): - # Create a client - client = discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.UpdateConversationRequest( - ) - - # Make the request - response = await client.update_conversation(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_ConversationalSearchService_UpdateConversation_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_update_conversation_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_update_conversation_sync.py deleted file mode 100644 index f1bc6a28a0ab..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_conversational_search_service_update_conversation_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for 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-discoveryengine - - -# [START discoveryengine_v1alpha_generated_ConversationalSearchService_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 discoveryengine_v1alpha - - -def sample_update_conversation(): - # Create a client - client = discoveryengine_v1alpha.ConversationalSearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.UpdateConversationRequest( - ) - - # Make the request - response = client.update_conversation(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_ConversationalSearchService_UpdateConversation_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_create_document_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_create_document_async.py deleted file mode 100644 index 197fa2d86cb5..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_create_document_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_DocumentService_CreateDocument_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -async def sample_create_document(): - # Create a client - client = discoveryengine_v1alpha.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.CreateDocumentRequest( - parent="parent_value", - document_id="document_id_value", - ) - - # Make the request - response = await client.create_document(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_DocumentService_CreateDocument_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_create_document_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_create_document_sync.py deleted file mode 100644 index 9d2f43561e6d..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_create_document_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_DocumentService_CreateDocument_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -def sample_create_document(): - # Create a client - client = discoveryengine_v1alpha.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.CreateDocumentRequest( - parent="parent_value", - document_id="document_id_value", - ) - - # Make the request - response = client.create_document(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_DocumentService_CreateDocument_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_delete_document_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_delete_document_async.py deleted file mode 100644 index 94222cb3fa7f..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_delete_document_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_DocumentService_DeleteDocument_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -async def sample_delete_document(): - # Create a client - client = discoveryengine_v1alpha.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.DeleteDocumentRequest( - name="name_value", - ) - - # Make the request - await client.delete_document(request=request) - - -# [END discoveryengine_v1alpha_generated_DocumentService_DeleteDocument_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_delete_document_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_delete_document_sync.py deleted file mode 100644 index b7f221c3a7b3..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_delete_document_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_DocumentService_DeleteDocument_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -def sample_delete_document(): - # Create a client - client = discoveryengine_v1alpha.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.DeleteDocumentRequest( - name="name_value", - ) - - # Make the request - client.delete_document(request=request) - - -# [END discoveryengine_v1alpha_generated_DocumentService_DeleteDocument_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_get_document_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_get_document_async.py deleted file mode 100644 index 0d4b0bf5e7ac..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_get_document_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_DocumentService_GetDocument_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -async def sample_get_document(): - # Create a client - client = discoveryengine_v1alpha.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.GetDocumentRequest( - name="name_value", - ) - - # Make the request - response = await client.get_document(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_DocumentService_GetDocument_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_get_document_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_get_document_sync.py deleted file mode 100644 index 5f81c278063e..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_get_document_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_DocumentService_GetDocument_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -def sample_get_document(): - # Create a client - client = discoveryengine_v1alpha.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.GetDocumentRequest( - name="name_value", - ) - - # Make the request - response = client.get_document(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_DocumentService_GetDocument_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_import_documents_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_import_documents_async.py deleted file mode 100644 index 6c6300958c5e..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_import_documents_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportDocuments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_DocumentService_ImportDocuments_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -async def sample_import_documents(): - # Create a client - client = discoveryengine_v1alpha.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.ImportDocumentsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.import_documents(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_DocumentService_ImportDocuments_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_import_documents_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_import_documents_sync.py deleted file mode 100644 index 26dd44fd2e50..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_import_documents_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportDocuments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_DocumentService_ImportDocuments_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -def sample_import_documents(): - # Create a client - client = discoveryengine_v1alpha.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.ImportDocumentsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.import_documents(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_DocumentService_ImportDocuments_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_list_documents_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_list_documents_async.py deleted file mode 100644 index e3dbd6905564..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_list_documents_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListDocuments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_DocumentService_ListDocuments_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -async def sample_list_documents(): - # Create a client - client = discoveryengine_v1alpha.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.ListDocumentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_documents(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END discoveryengine_v1alpha_generated_DocumentService_ListDocuments_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_list_documents_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_list_documents_sync.py deleted file mode 100644 index 7fa03e62969b..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_list_documents_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListDocuments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_DocumentService_ListDocuments_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -def sample_list_documents(): - # Create a client - client = discoveryengine_v1alpha.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.ListDocumentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_documents(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END discoveryengine_v1alpha_generated_DocumentService_ListDocuments_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_purge_documents_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_purge_documents_async.py deleted file mode 100644 index 45b09d4f452b..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_purge_documents_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PurgeDocuments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_DocumentService_PurgeDocuments_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -async def sample_purge_documents(): - # Create a client - client = discoveryengine_v1alpha.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.PurgeDocumentsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_documents(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_DocumentService_PurgeDocuments_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_purge_documents_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_purge_documents_sync.py deleted file mode 100644 index 8fc675f1cda3..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_purge_documents_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PurgeDocuments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_DocumentService_PurgeDocuments_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -def sample_purge_documents(): - # Create a client - client = discoveryengine_v1alpha.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.PurgeDocumentsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_documents(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_DocumentService_PurgeDocuments_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_update_document_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_update_document_async.py deleted file mode 100644 index 73c47803842d..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_update_document_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_DocumentService_UpdateDocument_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -async def sample_update_document(): - # Create a client - client = discoveryengine_v1alpha.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.UpdateDocumentRequest( - ) - - # Make the request - response = await client.update_document(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_DocumentService_UpdateDocument_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_update_document_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_update_document_sync.py deleted file mode 100644 index 68d14fe02d15..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_document_service_update_document_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_DocumentService_UpdateDocument_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -def sample_update_document(): - # Create a client - client = discoveryengine_v1alpha.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.UpdateDocumentRequest( - ) - - # Make the request - response = client.update_document(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_DocumentService_UpdateDocument_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_recommendation_service_recommend_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_recommendation_service_recommend_async.py deleted file mode 100644 index 25ad50f34a8c..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_recommendation_service_recommend_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Recommend -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_RecommendationService_Recommend_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -async def sample_recommend(): - # Create a client - client = discoveryengine_v1alpha.RecommendationServiceAsyncClient() - - # Initialize request argument(s) - user_event = discoveryengine_v1alpha.UserEvent() - user_event.event_type = "event_type_value" - user_event.user_pseudo_id = "user_pseudo_id_value" - - request = discoveryengine_v1alpha.RecommendRequest( - serving_config="serving_config_value", - user_event=user_event, - ) - - # Make the request - response = await client.recommend(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_RecommendationService_Recommend_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_recommendation_service_recommend_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_recommendation_service_recommend_sync.py deleted file mode 100644 index 7da58be33a1f..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_recommendation_service_recommend_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Recommend -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_RecommendationService_Recommend_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -def sample_recommend(): - # Create a client - client = discoveryengine_v1alpha.RecommendationServiceClient() - - # Initialize request argument(s) - user_event = discoveryengine_v1alpha.UserEvent() - user_event.event_type = "event_type_value" - user_event.user_pseudo_id = "user_pseudo_id_value" - - request = discoveryengine_v1alpha.RecommendRequest( - serving_config="serving_config_value", - user_event=user_event, - ) - - # Make the request - response = client.recommend(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_RecommendationService_Recommend_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_create_schema_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_create_schema_async.py deleted file mode 100644 index 34f0bc7db5eb..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_create_schema_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateSchema -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_SchemaService_CreateSchema_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -async def sample_create_schema(): - # Create a client - client = discoveryengine_v1alpha.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.CreateSchemaRequest( - parent="parent_value", - schema_id="schema_id_value", - ) - - # Make the request - operation = client.create_schema(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_SchemaService_CreateSchema_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_create_schema_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_create_schema_sync.py deleted file mode 100644 index b0cd2f174166..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_create_schema_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateSchema -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_SchemaService_CreateSchema_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -def sample_create_schema(): - # Create a client - client = discoveryengine_v1alpha.SchemaServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.CreateSchemaRequest( - parent="parent_value", - schema_id="schema_id_value", - ) - - # Make the request - operation = client.create_schema(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_SchemaService_CreateSchema_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_delete_schema_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_delete_schema_async.py deleted file mode 100644 index 7c195b6508c5..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_delete_schema_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteSchema -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_SchemaService_DeleteSchema_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -async def sample_delete_schema(): - # Create a client - client = discoveryengine_v1alpha.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.DeleteSchemaRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_schema(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_SchemaService_DeleteSchema_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_delete_schema_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_delete_schema_sync.py deleted file mode 100644 index dff9cfb661b1..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_delete_schema_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteSchema -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_SchemaService_DeleteSchema_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -def sample_delete_schema(): - # Create a client - client = discoveryengine_v1alpha.SchemaServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.DeleteSchemaRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_schema(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_SchemaService_DeleteSchema_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_get_schema_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_get_schema_async.py deleted file mode 100644 index c9da228ac811..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_get_schema_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetSchema -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_SchemaService_GetSchema_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -async def sample_get_schema(): - # Create a client - client = discoveryengine_v1alpha.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.GetSchemaRequest( - name="name_value", - ) - - # Make the request - response = await client.get_schema(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_SchemaService_GetSchema_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_get_schema_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_get_schema_sync.py deleted file mode 100644 index ea9e973843dd..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_get_schema_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetSchema -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_SchemaService_GetSchema_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -def sample_get_schema(): - # Create a client - client = discoveryengine_v1alpha.SchemaServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.GetSchemaRequest( - name="name_value", - ) - - # Make the request - response = client.get_schema(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_SchemaService_GetSchema_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_list_schemas_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_list_schemas_async.py deleted file mode 100644 index 594f682f8dea..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_list_schemas_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListSchemas -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_SchemaService_ListSchemas_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -async def sample_list_schemas(): - # Create a client - client = discoveryengine_v1alpha.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.ListSchemasRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_schemas(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END discoveryengine_v1alpha_generated_SchemaService_ListSchemas_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_list_schemas_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_list_schemas_sync.py deleted file mode 100644 index 476fe6943a0a..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_list_schemas_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListSchemas -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_SchemaService_ListSchemas_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -def sample_list_schemas(): - # Create a client - client = discoveryengine_v1alpha.SchemaServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.ListSchemasRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_schemas(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END discoveryengine_v1alpha_generated_SchemaService_ListSchemas_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_update_schema_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_update_schema_async.py deleted file mode 100644 index 15ecd5c92277..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_update_schema_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateSchema -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_SchemaService_UpdateSchema_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -async def sample_update_schema(): - # Create a client - client = discoveryengine_v1alpha.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.UpdateSchemaRequest( - ) - - # Make the request - operation = client.update_schema(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_SchemaService_UpdateSchema_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_update_schema_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_update_schema_sync.py deleted file mode 100644 index 751bbefc31fb..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_schema_service_update_schema_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateSchema -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_SchemaService_UpdateSchema_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -def sample_update_schema(): - # Create a client - client = discoveryengine_v1alpha.SchemaServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.UpdateSchemaRequest( - ) - - # Make the request - operation = client.update_schema(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_SchemaService_UpdateSchema_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_search_service_search_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_search_service_search_async.py deleted file mode 100644 index ed04cd567ada..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_search_service_search_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Search -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_SearchService_Search_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -async def sample_search(): - # Create a client - client = discoveryengine_v1alpha.SearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.SearchRequest( - serving_config="serving_config_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END discoveryengine_v1alpha_generated_SearchService_Search_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_search_service_search_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_search_service_search_sync.py deleted file mode 100644 index ca39f556b3b2..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_search_service_search_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Search -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_SearchService_Search_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -def sample_search(): - # Create a client - client = discoveryengine_v1alpha.SearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.SearchRequest( - serving_config="serving_config_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END discoveryengine_v1alpha_generated_SearchService_Search_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_site_search_engine_service_recrawl_uris_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_site_search_engine_service_recrawl_uris_async.py deleted file mode 100644 index 7a083fc2362b..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_site_search_engine_service_recrawl_uris_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RecrawlUris -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_SiteSearchEngineService_RecrawlUris_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -async def sample_recrawl_uris(): - # Create a client - client = discoveryengine_v1alpha.SiteSearchEngineServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.RecrawlUrisRequest( - site_search_engine="site_search_engine_value", - uris=['uris_value1', 'uris_value2'], - ) - - # Make the request - operation = client.recrawl_uris(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_SiteSearchEngineService_RecrawlUris_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_site_search_engine_service_recrawl_uris_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_site_search_engine_service_recrawl_uris_sync.py deleted file mode 100644 index f0e38570263e..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_site_search_engine_service_recrawl_uris_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RecrawlUris -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_SiteSearchEngineService_RecrawlUris_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -def sample_recrawl_uris(): - # Create a client - client = discoveryengine_v1alpha.SiteSearchEngineServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.RecrawlUrisRequest( - site_search_engine="site_search_engine_value", - uris=['uris_value1', 'uris_value2'], - ) - - # Make the request - operation = client.recrawl_uris(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_SiteSearchEngineService_RecrawlUris_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_collect_user_event_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_collect_user_event_async.py deleted file mode 100644 index 66c89511c060..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_collect_user_event_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CollectUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_UserEventService_CollectUserEvent_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -async def sample_collect_user_event(): - # Create a client - client = discoveryengine_v1alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = await client.collect_user_event(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_UserEventService_CollectUserEvent_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_collect_user_event_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_collect_user_event_sync.py deleted file mode 100644 index bf5d7495686b..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_collect_user_event_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CollectUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_UserEventService_CollectUserEvent_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -def sample_collect_user_event(): - # Create a client - client = discoveryengine_v1alpha.UserEventServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = client.collect_user_event(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_UserEventService_CollectUserEvent_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_import_user_events_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_import_user_events_async.py deleted file mode 100644 index e94e32400499..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_import_user_events_async.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_UserEventService_ImportUserEvents_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -async def sample_import_user_events(): - # Create a client - client = discoveryengine_v1alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - inline_source = discoveryengine_v1alpha.InlineSource() - inline_source.user_events.event_type = "event_type_value" - inline_source.user_events.user_pseudo_id = "user_pseudo_id_value" - - request = discoveryengine_v1alpha.ImportUserEventsRequest( - inline_source=inline_source, - parent="parent_value", - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_UserEventService_ImportUserEvents_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_import_user_events_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_import_user_events_sync.py deleted file mode 100644 index 6fe5c9dfe3a0..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_import_user_events_sync.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_UserEventService_ImportUserEvents_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -def sample_import_user_events(): - # Create a client - client = discoveryengine_v1alpha.UserEventServiceClient() - - # Initialize request argument(s) - inline_source = discoveryengine_v1alpha.InlineSource() - inline_source.user_events.event_type = "event_type_value" - inline_source.user_events.user_pseudo_id = "user_pseudo_id_value" - - request = discoveryengine_v1alpha.ImportUserEventsRequest( - inline_source=inline_source, - parent="parent_value", - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_UserEventService_ImportUserEvents_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_purge_user_events_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_purge_user_events_async.py deleted file mode 100644 index fe3f264a8936..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_purge_user_events_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PurgeUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_UserEventService_PurgeUserEvents_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -async def sample_purge_user_events(): - # Create a client - client = discoveryengine_v1alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_UserEventService_PurgeUserEvents_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_purge_user_events_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_purge_user_events_sync.py deleted file mode 100644 index 0801661354e9..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_purge_user_events_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PurgeUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_UserEventService_PurgeUserEvents_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -def sample_purge_user_events(): - # Create a client - client = discoveryengine_v1alpha.UserEventServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.PurgeUserEventsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_UserEventService_PurgeUserEvents_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_write_user_event_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_write_user_event_async.py deleted file mode 100644 index 674fe125a506..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_write_user_event_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for WriteUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_UserEventService_WriteUserEvent_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -async def sample_write_user_event(): - # Create a client - client = discoveryengine_v1alpha.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.WriteUserEventRequest( - parent="parent_value", - ) - - # Make the request - response = await client.write_user_event(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_UserEventService_WriteUserEvent_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_write_user_event_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_write_user_event_sync.py deleted file mode 100644 index 19d53382b452..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_user_event_service_write_user_event_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for WriteUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1alpha_generated_UserEventService_WriteUserEvent_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1alpha - - -def sample_write_user_event(): - # Create a client - client = discoveryengine_v1alpha.UserEventServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1alpha.WriteUserEventRequest( - parent="parent_value", - ) - - # Make the request - response = client.write_user_event(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1alpha_generated_UserEventService_WriteUserEvent_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1alpha.json b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1alpha.json deleted file mode 100644 index ce41071d0b4c..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1alpha.json +++ /dev/null @@ -1,6290 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.discoveryengine.v1alpha", - "version": "v1alpha" - } - ], - "language": "PYTHON", - "name": "google-cloud-discoveryengine", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.CompletionServiceAsyncClient", - "shortName": "CompletionServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.CompletionServiceAsyncClient.complete_query", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.CompletionService.CompleteQuery", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "CompleteQuery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.CompleteQueryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.CompleteQueryResponse", - "shortName": "complete_query" - }, - "description": "Sample for CompleteQuery", - "file": "discoveryengine_v1alpha_generated_completion_service_complete_query_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_CompletionService_CompleteQuery_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": "discoveryengine_v1alpha_generated_completion_service_complete_query_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.CompletionServiceClient", - "shortName": "CompletionServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.CompletionServiceClient.complete_query", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.CompletionService.CompleteQuery", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "CompleteQuery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.CompleteQueryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.CompleteQueryResponse", - "shortName": "complete_query" - }, - "description": "Sample for CompleteQuery", - "file": "discoveryengine_v1alpha_generated_completion_service_complete_query_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_CompletionService_CompleteQuery_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": "discoveryengine_v1alpha_generated_completion_service_complete_query_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient", - "shortName": "ConversationalSearchServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient.converse_conversation", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService.ConverseConversation", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService", - "shortName": "ConversationalSearchService" - }, - "shortName": "ConverseConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.ConverseConversationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "query", - "type": "google.cloud.discoveryengine_v1alpha.types.TextInput" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.ConverseConversationResponse", - "shortName": "converse_conversation" - }, - "description": "Sample for ConverseConversation", - "file": "discoveryengine_v1alpha_generated_conversational_search_service_converse_conversation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_ConversationalSearchService_ConverseConversation_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": "discoveryengine_v1alpha_generated_conversational_search_service_converse_conversation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceClient", - "shortName": "ConversationalSearchServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceClient.converse_conversation", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService.ConverseConversation", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService", - "shortName": "ConversationalSearchService" - }, - "shortName": "ConverseConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.ConverseConversationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "query", - "type": "google.cloud.discoveryengine_v1alpha.types.TextInput" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.ConverseConversationResponse", - "shortName": "converse_conversation" - }, - "description": "Sample for ConverseConversation", - "file": "discoveryengine_v1alpha_generated_conversational_search_service_converse_conversation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_ConversationalSearchService_ConverseConversation_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": "discoveryengine_v1alpha_generated_conversational_search_service_converse_conversation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient", - "shortName": "ConversationalSearchServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient.create_conversation", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService.CreateConversation", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService", - "shortName": "ConversationalSearchService" - }, - "shortName": "CreateConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.CreateConversationRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "conversation", - "type": "google.cloud.discoveryengine_v1alpha.types.Conversation" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.Conversation", - "shortName": "create_conversation" - }, - "description": "Sample for CreateConversation", - "file": "discoveryengine_v1alpha_generated_conversational_search_service_create_conversation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_ConversationalSearchService_CreateConversation_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": "discoveryengine_v1alpha_generated_conversational_search_service_create_conversation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceClient", - "shortName": "ConversationalSearchServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceClient.create_conversation", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService.CreateConversation", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService", - "shortName": "ConversationalSearchService" - }, - "shortName": "CreateConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.CreateConversationRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "conversation", - "type": "google.cloud.discoveryengine_v1alpha.types.Conversation" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.Conversation", - "shortName": "create_conversation" - }, - "description": "Sample for CreateConversation", - "file": "discoveryengine_v1alpha_generated_conversational_search_service_create_conversation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_ConversationalSearchService_CreateConversation_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": "discoveryengine_v1alpha_generated_conversational_search_service_create_conversation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient", - "shortName": "ConversationalSearchServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient.delete_conversation", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService.DeleteConversation", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService", - "shortName": "ConversationalSearchService" - }, - "shortName": "DeleteConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.DeleteConversationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_conversation" - }, - "description": "Sample for DeleteConversation", - "file": "discoveryengine_v1alpha_generated_conversational_search_service_delete_conversation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_ConversationalSearchService_DeleteConversation_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": "discoveryengine_v1alpha_generated_conversational_search_service_delete_conversation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceClient", - "shortName": "ConversationalSearchServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceClient.delete_conversation", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService.DeleteConversation", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService", - "shortName": "ConversationalSearchService" - }, - "shortName": "DeleteConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.DeleteConversationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_conversation" - }, - "description": "Sample for DeleteConversation", - "file": "discoveryengine_v1alpha_generated_conversational_search_service_delete_conversation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_ConversationalSearchService_DeleteConversation_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": "discoveryengine_v1alpha_generated_conversational_search_service_delete_conversation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient", - "shortName": "ConversationalSearchServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient.get_conversation", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService.GetConversation", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService", - "shortName": "ConversationalSearchService" - }, - "shortName": "GetConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.GetConversationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.Conversation", - "shortName": "get_conversation" - }, - "description": "Sample for GetConversation", - "file": "discoveryengine_v1alpha_generated_conversational_search_service_get_conversation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_ConversationalSearchService_GetConversation_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": "discoveryengine_v1alpha_generated_conversational_search_service_get_conversation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceClient", - "shortName": "ConversationalSearchServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceClient.get_conversation", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService.GetConversation", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService", - "shortName": "ConversationalSearchService" - }, - "shortName": "GetConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.GetConversationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.Conversation", - "shortName": "get_conversation" - }, - "description": "Sample for GetConversation", - "file": "discoveryengine_v1alpha_generated_conversational_search_service_get_conversation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_ConversationalSearchService_GetConversation_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": "discoveryengine_v1alpha_generated_conversational_search_service_get_conversation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient", - "shortName": "ConversationalSearchServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient.list_conversations", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService.ListConversations", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService", - "shortName": "ConversationalSearchService" - }, - "shortName": "ListConversations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.ListConversationsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.services.conversational_search_service.pagers.ListConversationsAsyncPager", - "shortName": "list_conversations" - }, - "description": "Sample for ListConversations", - "file": "discoveryengine_v1alpha_generated_conversational_search_service_list_conversations_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_ConversationalSearchService_ListConversations_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": "discoveryengine_v1alpha_generated_conversational_search_service_list_conversations_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceClient", - "shortName": "ConversationalSearchServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceClient.list_conversations", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService.ListConversations", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService", - "shortName": "ConversationalSearchService" - }, - "shortName": "ListConversations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.ListConversationsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.services.conversational_search_service.pagers.ListConversationsPager", - "shortName": "list_conversations" - }, - "description": "Sample for ListConversations", - "file": "discoveryengine_v1alpha_generated_conversational_search_service_list_conversations_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_ConversationalSearchService_ListConversations_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": "discoveryengine_v1alpha_generated_conversational_search_service_list_conversations_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient", - "shortName": "ConversationalSearchServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceAsyncClient.update_conversation", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService.UpdateConversation", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService", - "shortName": "ConversationalSearchService" - }, - "shortName": "UpdateConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.UpdateConversationRequest" - }, - { - "name": "conversation", - "type": "google.cloud.discoveryengine_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, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.Conversation", - "shortName": "update_conversation" - }, - "description": "Sample for UpdateConversation", - "file": "discoveryengine_v1alpha_generated_conversational_search_service_update_conversation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_ConversationalSearchService_UpdateConversation_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": "discoveryengine_v1alpha_generated_conversational_search_service_update_conversation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceClient", - "shortName": "ConversationalSearchServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.ConversationalSearchServiceClient.update_conversation", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService.UpdateConversation", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.ConversationalSearchService", - "shortName": "ConversationalSearchService" - }, - "shortName": "UpdateConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.UpdateConversationRequest" - }, - { - "name": "conversation", - "type": "google.cloud.discoveryengine_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, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.Conversation", - "shortName": "update_conversation" - }, - "description": "Sample for UpdateConversation", - "file": "discoveryengine_v1alpha_generated_conversational_search_service_update_conversation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_ConversationalSearchService_UpdateConversation_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": "discoveryengine_v1alpha_generated_conversational_search_service_update_conversation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceAsyncClient", - "shortName": "DataStoreServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceAsyncClient.create_data_store", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService.CreateDataStore", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService", - "shortName": "DataStoreService" - }, - "shortName": "CreateDataStore" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.CreateDataStoreRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "data_store", - "type": "google.cloud.discoveryengine_v1alpha.types.DataStore" - }, - { - "name": "data_store_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_data_store" - }, - "description": "Sample for CreateDataStore", - "file": "discoveryengine_v1alpha_generated_data_store_service_create_data_store_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DataStoreService_CreateDataStore_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": "discoveryengine_v1alpha_generated_data_store_service_create_data_store_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceClient", - "shortName": "DataStoreServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceClient.create_data_store", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService.CreateDataStore", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService", - "shortName": "DataStoreService" - }, - "shortName": "CreateDataStore" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.CreateDataStoreRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "data_store", - "type": "google.cloud.discoveryengine_v1alpha.types.DataStore" - }, - { - "name": "data_store_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_data_store" - }, - "description": "Sample for CreateDataStore", - "file": "discoveryengine_v1alpha_generated_data_store_service_create_data_store_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DataStoreService_CreateDataStore_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": "discoveryengine_v1alpha_generated_data_store_service_create_data_store_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceAsyncClient", - "shortName": "DataStoreServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceAsyncClient.delete_data_store", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService.DeleteDataStore", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService", - "shortName": "DataStoreService" - }, - "shortName": "DeleteDataStore" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.DeleteDataStoreRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_data_store" - }, - "description": "Sample for DeleteDataStore", - "file": "discoveryengine_v1alpha_generated_data_store_service_delete_data_store_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DataStoreService_DeleteDataStore_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": "discoveryengine_v1alpha_generated_data_store_service_delete_data_store_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceClient", - "shortName": "DataStoreServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceClient.delete_data_store", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService.DeleteDataStore", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService", - "shortName": "DataStoreService" - }, - "shortName": "DeleteDataStore" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.DeleteDataStoreRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_data_store" - }, - "description": "Sample for DeleteDataStore", - "file": "discoveryengine_v1alpha_generated_data_store_service_delete_data_store_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DataStoreService_DeleteDataStore_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": "discoveryengine_v1alpha_generated_data_store_service_delete_data_store_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceAsyncClient", - "shortName": "DataStoreServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceAsyncClient.get_data_store", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService.GetDataStore", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService", - "shortName": "DataStoreService" - }, - "shortName": "GetDataStore" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.GetDataStoreRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.DataStore", - "shortName": "get_data_store" - }, - "description": "Sample for GetDataStore", - "file": "discoveryengine_v1alpha_generated_data_store_service_get_data_store_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DataStoreService_GetDataStore_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": "discoveryengine_v1alpha_generated_data_store_service_get_data_store_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceClient", - "shortName": "DataStoreServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceClient.get_data_store", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService.GetDataStore", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService", - "shortName": "DataStoreService" - }, - "shortName": "GetDataStore" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.GetDataStoreRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.DataStore", - "shortName": "get_data_store" - }, - "description": "Sample for GetDataStore", - "file": "discoveryengine_v1alpha_generated_data_store_service_get_data_store_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DataStoreService_GetDataStore_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": "discoveryengine_v1alpha_generated_data_store_service_get_data_store_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceAsyncClient", - "shortName": "DataStoreServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceAsyncClient.list_data_stores", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService.ListDataStores", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService", - "shortName": "DataStoreService" - }, - "shortName": "ListDataStores" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.ListDataStoresRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.services.data_store_service.pagers.ListDataStoresAsyncPager", - "shortName": "list_data_stores" - }, - "description": "Sample for ListDataStores", - "file": "discoveryengine_v1alpha_generated_data_store_service_list_data_stores_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DataStoreService_ListDataStores_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": "discoveryengine_v1alpha_generated_data_store_service_list_data_stores_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceClient", - "shortName": "DataStoreServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceClient.list_data_stores", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService.ListDataStores", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService", - "shortName": "DataStoreService" - }, - "shortName": "ListDataStores" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.ListDataStoresRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.services.data_store_service.pagers.ListDataStoresPager", - "shortName": "list_data_stores" - }, - "description": "Sample for ListDataStores", - "file": "discoveryengine_v1alpha_generated_data_store_service_list_data_stores_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DataStoreService_ListDataStores_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": "discoveryengine_v1alpha_generated_data_store_service_list_data_stores_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceAsyncClient", - "shortName": "DataStoreServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceAsyncClient.update_data_store", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService.UpdateDataStore", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService", - "shortName": "DataStoreService" - }, - "shortName": "UpdateDataStore" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.UpdateDataStoreRequest" - }, - { - "name": "data_store", - "type": "google.cloud.discoveryengine_v1alpha.types.DataStore" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.DataStore", - "shortName": "update_data_store" - }, - "description": "Sample for UpdateDataStore", - "file": "discoveryengine_v1alpha_generated_data_store_service_update_data_store_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DataStoreService_UpdateDataStore_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": "discoveryengine_v1alpha_generated_data_store_service_update_data_store_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceClient", - "shortName": "DataStoreServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceClient.update_data_store", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService.UpdateDataStore", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService", - "shortName": "DataStoreService" - }, - "shortName": "UpdateDataStore" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.UpdateDataStoreRequest" - }, - { - "name": "data_store", - "type": "google.cloud.discoveryengine_v1alpha.types.DataStore" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.DataStore", - "shortName": "update_data_store" - }, - "description": "Sample for UpdateDataStore", - "file": "discoveryengine_v1alpha_generated_data_store_service_update_data_store_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DataStoreService_UpdateDataStore_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": "discoveryengine_v1alpha_generated_data_store_service_update_data_store_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient", - "shortName": "DocumentServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient.create_document", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.CreateDocument", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "CreateDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.CreateDocumentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "document", - "type": "google.cloud.discoveryengine_v1alpha.types.Document" - }, - { - "name": "document_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.Document", - "shortName": "create_document" - }, - "description": "Sample for CreateDocument", - "file": "discoveryengine_v1alpha_generated_document_service_create_document_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DocumentService_CreateDocument_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": "discoveryengine_v1alpha_generated_document_service_create_document_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient", - "shortName": "DocumentServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient.create_document", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.CreateDocument", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "CreateDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.CreateDocumentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "document", - "type": "google.cloud.discoveryengine_v1alpha.types.Document" - }, - { - "name": "document_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.Document", - "shortName": "create_document" - }, - "description": "Sample for CreateDocument", - "file": "discoveryengine_v1alpha_generated_document_service_create_document_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DocumentService_CreateDocument_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": "discoveryengine_v1alpha_generated_document_service_create_document_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient", - "shortName": "DocumentServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient.delete_document", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.DeleteDocument", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "DeleteDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.DeleteDocumentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_document" - }, - "description": "Sample for DeleteDocument", - "file": "discoveryengine_v1alpha_generated_document_service_delete_document_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DocumentService_DeleteDocument_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": "discoveryengine_v1alpha_generated_document_service_delete_document_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient", - "shortName": "DocumentServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient.delete_document", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.DeleteDocument", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "DeleteDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.DeleteDocumentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_document" - }, - "description": "Sample for DeleteDocument", - "file": "discoveryengine_v1alpha_generated_document_service_delete_document_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DocumentService_DeleteDocument_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": "discoveryengine_v1alpha_generated_document_service_delete_document_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient", - "shortName": "DocumentServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient.get_document", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.GetDocument", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "GetDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.GetDocumentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.Document", - "shortName": "get_document" - }, - "description": "Sample for GetDocument", - "file": "discoveryengine_v1alpha_generated_document_service_get_document_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DocumentService_GetDocument_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": "discoveryengine_v1alpha_generated_document_service_get_document_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient", - "shortName": "DocumentServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient.get_document", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.GetDocument", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "GetDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.GetDocumentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.Document", - "shortName": "get_document" - }, - "description": "Sample for GetDocument", - "file": "discoveryengine_v1alpha_generated_document_service_get_document_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DocumentService_GetDocument_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": "discoveryengine_v1alpha_generated_document_service_get_document_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient", - "shortName": "DocumentServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient.import_documents", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.ImportDocuments", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "ImportDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.ImportDocumentsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "import_documents" - }, - "description": "Sample for ImportDocuments", - "file": "discoveryengine_v1alpha_generated_document_service_import_documents_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DocumentService_ImportDocuments_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": "discoveryengine_v1alpha_generated_document_service_import_documents_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient", - "shortName": "DocumentServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient.import_documents", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.ImportDocuments", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "ImportDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.ImportDocumentsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "import_documents" - }, - "description": "Sample for ImportDocuments", - "file": "discoveryengine_v1alpha_generated_document_service_import_documents_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DocumentService_ImportDocuments_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": "discoveryengine_v1alpha_generated_document_service_import_documents_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient", - "shortName": "DocumentServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient.list_documents", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.ListDocuments", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "ListDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.ListDocumentsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.services.document_service.pagers.ListDocumentsAsyncPager", - "shortName": "list_documents" - }, - "description": "Sample for ListDocuments", - "file": "discoveryengine_v1alpha_generated_document_service_list_documents_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DocumentService_ListDocuments_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": "discoveryengine_v1alpha_generated_document_service_list_documents_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient", - "shortName": "DocumentServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient.list_documents", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.ListDocuments", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "ListDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.ListDocumentsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.services.document_service.pagers.ListDocumentsPager", - "shortName": "list_documents" - }, - "description": "Sample for ListDocuments", - "file": "discoveryengine_v1alpha_generated_document_service_list_documents_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DocumentService_ListDocuments_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": "discoveryengine_v1alpha_generated_document_service_list_documents_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient", - "shortName": "DocumentServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient.purge_documents", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.PurgeDocuments", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "PurgeDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.PurgeDocumentsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "purge_documents" - }, - "description": "Sample for PurgeDocuments", - "file": "discoveryengine_v1alpha_generated_document_service_purge_documents_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DocumentService_PurgeDocuments_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": "discoveryengine_v1alpha_generated_document_service_purge_documents_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient", - "shortName": "DocumentServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient.purge_documents", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.PurgeDocuments", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "PurgeDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.PurgeDocumentsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "purge_documents" - }, - "description": "Sample for PurgeDocuments", - "file": "discoveryengine_v1alpha_generated_document_service_purge_documents_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DocumentService_PurgeDocuments_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": "discoveryengine_v1alpha_generated_document_service_purge_documents_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient", - "shortName": "DocumentServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient.update_document", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.UpdateDocument", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "UpdateDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.UpdateDocumentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.Document", - "shortName": "update_document" - }, - "description": "Sample for UpdateDocument", - "file": "discoveryengine_v1alpha_generated_document_service_update_document_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DocumentService_UpdateDocument_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": "discoveryengine_v1alpha_generated_document_service_update_document_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient", - "shortName": "DocumentServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient.update_document", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.UpdateDocument", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "UpdateDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.UpdateDocumentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.Document", - "shortName": "update_document" - }, - "description": "Sample for UpdateDocument", - "file": "discoveryengine_v1alpha_generated_document_service_update_document_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DocumentService_UpdateDocument_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": "discoveryengine_v1alpha_generated_document_service_update_document_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient", - "shortName": "EngineServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient.create_engine", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.CreateEngine", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", - "shortName": "EngineService" - }, - "shortName": "CreateEngine" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.CreateEngineRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "engine", - "type": "google.cloud.discoveryengine_v1alpha.types.Engine" - }, - { - "name": "engine_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_engine" - }, - "description": "Sample for CreateEngine", - "file": "discoveryengine_v1alpha_generated_engine_service_create_engine_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_EngineService_CreateEngine_async", - "segments": [ - { - "end": 61, - "start": 27, - "type": "FULL" - }, - { - "end": 61, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 51, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 58, - "start": 52, - "type": "REQUEST_EXECUTION" - }, - { - "end": 62, - "start": 59, - "type": "RESPONSE_HANDLING" - } - ], - "title": "discoveryengine_v1alpha_generated_engine_service_create_engine_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient", - "shortName": "EngineServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient.create_engine", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.CreateEngine", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", - "shortName": "EngineService" - }, - "shortName": "CreateEngine" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.CreateEngineRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "engine", - "type": "google.cloud.discoveryengine_v1alpha.types.Engine" - }, - { - "name": "engine_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_engine" - }, - "description": "Sample for CreateEngine", - "file": "discoveryengine_v1alpha_generated_engine_service_create_engine_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_EngineService_CreateEngine_sync", - "segments": [ - { - "end": 61, - "start": 27, - "type": "FULL" - }, - { - "end": 61, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 51, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 58, - "start": 52, - "type": "REQUEST_EXECUTION" - }, - { - "end": 62, - "start": 59, - "type": "RESPONSE_HANDLING" - } - ], - "title": "discoveryengine_v1alpha_generated_engine_service_create_engine_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient", - "shortName": "EngineServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient.delete_engine", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.DeleteEngine", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", - "shortName": "EngineService" - }, - "shortName": "DeleteEngine" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.DeleteEngineRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_engine" - }, - "description": "Sample for DeleteEngine", - "file": "discoveryengine_v1alpha_generated_engine_service_delete_engine_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_EngineService_DeleteEngine_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": "discoveryengine_v1alpha_generated_engine_service_delete_engine_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient", - "shortName": "EngineServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient.delete_engine", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.DeleteEngine", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", - "shortName": "EngineService" - }, - "shortName": "DeleteEngine" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.DeleteEngineRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_engine" - }, - "description": "Sample for DeleteEngine", - "file": "discoveryengine_v1alpha_generated_engine_service_delete_engine_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_EngineService_DeleteEngine_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": "discoveryengine_v1alpha_generated_engine_service_delete_engine_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient", - "shortName": "EngineServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient.get_engine", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.GetEngine", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", - "shortName": "EngineService" - }, - "shortName": "GetEngine" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.GetEngineRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.Engine", - "shortName": "get_engine" - }, - "description": "Sample for GetEngine", - "file": "discoveryengine_v1alpha_generated_engine_service_get_engine_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_EngineService_GetEngine_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": "discoveryengine_v1alpha_generated_engine_service_get_engine_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient", - "shortName": "EngineServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient.get_engine", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.GetEngine", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", - "shortName": "EngineService" - }, - "shortName": "GetEngine" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.GetEngineRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.Engine", - "shortName": "get_engine" - }, - "description": "Sample for GetEngine", - "file": "discoveryengine_v1alpha_generated_engine_service_get_engine_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_EngineService_GetEngine_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": "discoveryengine_v1alpha_generated_engine_service_get_engine_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient", - "shortName": "EngineServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient.list_engines", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.ListEngines", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", - "shortName": "EngineService" - }, - "shortName": "ListEngines" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.ListEnginesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.services.engine_service.pagers.ListEnginesAsyncPager", - "shortName": "list_engines" - }, - "description": "Sample for ListEngines", - "file": "discoveryengine_v1alpha_generated_engine_service_list_engines_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_EngineService_ListEngines_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": "discoveryengine_v1alpha_generated_engine_service_list_engines_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient", - "shortName": "EngineServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient.list_engines", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.ListEngines", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", - "shortName": "EngineService" - }, - "shortName": "ListEngines" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.ListEnginesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.services.engine_service.pagers.ListEnginesPager", - "shortName": "list_engines" - }, - "description": "Sample for ListEngines", - "file": "discoveryengine_v1alpha_generated_engine_service_list_engines_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_EngineService_ListEngines_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": "discoveryengine_v1alpha_generated_engine_service_list_engines_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient", - "shortName": "EngineServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient.pause_engine", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.PauseEngine", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", - "shortName": "EngineService" - }, - "shortName": "PauseEngine" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.PauseEngineRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.Engine", - "shortName": "pause_engine" - }, - "description": "Sample for PauseEngine", - "file": "discoveryengine_v1alpha_generated_engine_service_pause_engine_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_EngineService_PauseEngine_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": "discoveryengine_v1alpha_generated_engine_service_pause_engine_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient", - "shortName": "EngineServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient.pause_engine", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.PauseEngine", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", - "shortName": "EngineService" - }, - "shortName": "PauseEngine" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.PauseEngineRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.Engine", - "shortName": "pause_engine" - }, - "description": "Sample for PauseEngine", - "file": "discoveryengine_v1alpha_generated_engine_service_pause_engine_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_EngineService_PauseEngine_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": "discoveryengine_v1alpha_generated_engine_service_pause_engine_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient", - "shortName": "EngineServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient.resume_engine", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.ResumeEngine", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", - "shortName": "EngineService" - }, - "shortName": "ResumeEngine" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.ResumeEngineRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.Engine", - "shortName": "resume_engine" - }, - "description": "Sample for ResumeEngine", - "file": "discoveryengine_v1alpha_generated_engine_service_resume_engine_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_EngineService_ResumeEngine_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": "discoveryengine_v1alpha_generated_engine_service_resume_engine_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient", - "shortName": "EngineServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient.resume_engine", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.ResumeEngine", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", - "shortName": "EngineService" - }, - "shortName": "ResumeEngine" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.ResumeEngineRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.Engine", - "shortName": "resume_engine" - }, - "description": "Sample for ResumeEngine", - "file": "discoveryengine_v1alpha_generated_engine_service_resume_engine_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_EngineService_ResumeEngine_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": "discoveryengine_v1alpha_generated_engine_service_resume_engine_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient", - "shortName": "EngineServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient.tune_engine", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.TuneEngine", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", - "shortName": "EngineService" - }, - "shortName": "TuneEngine" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.TuneEngineRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "tune_engine" - }, - "description": "Sample for TuneEngine", - "file": "discoveryengine_v1alpha_generated_engine_service_tune_engine_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_EngineService_TuneEngine_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": "discoveryengine_v1alpha_generated_engine_service_tune_engine_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient", - "shortName": "EngineServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient.tune_engine", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.TuneEngine", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", - "shortName": "EngineService" - }, - "shortName": "TuneEngine" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.TuneEngineRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "tune_engine" - }, - "description": "Sample for TuneEngine", - "file": "discoveryengine_v1alpha_generated_engine_service_tune_engine_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_EngineService_TuneEngine_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": "discoveryengine_v1alpha_generated_engine_service_tune_engine_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient", - "shortName": "EngineServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient.update_engine", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.UpdateEngine", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", - "shortName": "EngineService" - }, - "shortName": "UpdateEngine" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.UpdateEngineRequest" - }, - { - "name": "engine", - "type": "google.cloud.discoveryengine_v1alpha.types.Engine" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.Engine", - "shortName": "update_engine" - }, - "description": "Sample for UpdateEngine", - "file": "discoveryengine_v1alpha_generated_engine_service_update_engine_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_EngineService_UpdateEngine_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": "discoveryengine_v1alpha_generated_engine_service_update_engine_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient", - "shortName": "EngineServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient.update_engine", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.UpdateEngine", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", - "shortName": "EngineService" - }, - "shortName": "UpdateEngine" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.UpdateEngineRequest" - }, - { - "name": "engine", - "type": "google.cloud.discoveryengine_v1alpha.types.Engine" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.Engine", - "shortName": "update_engine" - }, - "description": "Sample for UpdateEngine", - "file": "discoveryengine_v1alpha_generated_engine_service_update_engine_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_EngineService_UpdateEngine_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": "discoveryengine_v1alpha_generated_engine_service_update_engine_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.RecommendationServiceAsyncClient", - "shortName": "RecommendationServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.RecommendationServiceAsyncClient.recommend", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.RecommendationService.Recommend", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.RecommendationService", - "shortName": "RecommendationService" - }, - "shortName": "Recommend" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.RecommendRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.RecommendResponse", - "shortName": "recommend" - }, - "description": "Sample for Recommend", - "file": "discoveryengine_v1alpha_generated_recommendation_service_recommend_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_RecommendationService_Recommend_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "discoveryengine_v1alpha_generated_recommendation_service_recommend_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.RecommendationServiceClient", - "shortName": "RecommendationServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.RecommendationServiceClient.recommend", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.RecommendationService.Recommend", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.RecommendationService", - "shortName": "RecommendationService" - }, - "shortName": "Recommend" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.RecommendRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.RecommendResponse", - "shortName": "recommend" - }, - "description": "Sample for Recommend", - "file": "discoveryengine_v1alpha_generated_recommendation_service_recommend_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_RecommendationService_Recommend_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "discoveryengine_v1alpha_generated_recommendation_service_recommend_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceAsyncClient", - "shortName": "SchemaServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceAsyncClient.create_schema", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService.CreateSchema", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "CreateSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.CreateSchemaRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "schema", - "type": "google.cloud.discoveryengine_v1alpha.types.Schema" - }, - { - "name": "schema_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_schema" - }, - "description": "Sample for CreateSchema", - "file": "discoveryengine_v1alpha_generated_schema_service_create_schema_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_SchemaService_CreateSchema_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": "discoveryengine_v1alpha_generated_schema_service_create_schema_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceClient", - "shortName": "SchemaServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceClient.create_schema", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService.CreateSchema", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "CreateSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.CreateSchemaRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "schema", - "type": "google.cloud.discoveryengine_v1alpha.types.Schema" - }, - { - "name": "schema_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_schema" - }, - "description": "Sample for CreateSchema", - "file": "discoveryengine_v1alpha_generated_schema_service_create_schema_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_SchemaService_CreateSchema_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": "discoveryengine_v1alpha_generated_schema_service_create_schema_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceAsyncClient", - "shortName": "SchemaServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceAsyncClient.delete_schema", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService.DeleteSchema", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "DeleteSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.DeleteSchemaRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_schema" - }, - "description": "Sample for DeleteSchema", - "file": "discoveryengine_v1alpha_generated_schema_service_delete_schema_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_SchemaService_DeleteSchema_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": "discoveryengine_v1alpha_generated_schema_service_delete_schema_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceClient", - "shortName": "SchemaServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceClient.delete_schema", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService.DeleteSchema", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "DeleteSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.DeleteSchemaRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_schema" - }, - "description": "Sample for DeleteSchema", - "file": "discoveryengine_v1alpha_generated_schema_service_delete_schema_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_SchemaService_DeleteSchema_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": "discoveryengine_v1alpha_generated_schema_service_delete_schema_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceAsyncClient", - "shortName": "SchemaServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceAsyncClient.get_schema", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService.GetSchema", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "GetSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.GetSchemaRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.Schema", - "shortName": "get_schema" - }, - "description": "Sample for GetSchema", - "file": "discoveryengine_v1alpha_generated_schema_service_get_schema_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_SchemaService_GetSchema_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": "discoveryengine_v1alpha_generated_schema_service_get_schema_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceClient", - "shortName": "SchemaServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceClient.get_schema", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService.GetSchema", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "GetSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.GetSchemaRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.Schema", - "shortName": "get_schema" - }, - "description": "Sample for GetSchema", - "file": "discoveryengine_v1alpha_generated_schema_service_get_schema_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_SchemaService_GetSchema_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": "discoveryengine_v1alpha_generated_schema_service_get_schema_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceAsyncClient", - "shortName": "SchemaServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceAsyncClient.list_schemas", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService.ListSchemas", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "ListSchemas" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.ListSchemasRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.services.schema_service.pagers.ListSchemasAsyncPager", - "shortName": "list_schemas" - }, - "description": "Sample for ListSchemas", - "file": "discoveryengine_v1alpha_generated_schema_service_list_schemas_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_SchemaService_ListSchemas_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": "discoveryengine_v1alpha_generated_schema_service_list_schemas_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceClient", - "shortName": "SchemaServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceClient.list_schemas", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService.ListSchemas", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "ListSchemas" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.ListSchemasRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.services.schema_service.pagers.ListSchemasPager", - "shortName": "list_schemas" - }, - "description": "Sample for ListSchemas", - "file": "discoveryengine_v1alpha_generated_schema_service_list_schemas_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_SchemaService_ListSchemas_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": "discoveryengine_v1alpha_generated_schema_service_list_schemas_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceAsyncClient", - "shortName": "SchemaServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceAsyncClient.update_schema", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService.UpdateSchema", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "UpdateSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.UpdateSchemaRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_schema" - }, - "description": "Sample for UpdateSchema", - "file": "discoveryengine_v1alpha_generated_schema_service_update_schema_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_SchemaService_UpdateSchema_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "discoveryengine_v1alpha_generated_schema_service_update_schema_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceClient", - "shortName": "SchemaServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.SchemaServiceClient.update_schema", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService.UpdateSchema", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "UpdateSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.UpdateSchemaRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_schema" - }, - "description": "Sample for UpdateSchema", - "file": "discoveryengine_v1alpha_generated_schema_service_update_schema_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_SchemaService_UpdateSchema_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "discoveryengine_v1alpha_generated_schema_service_update_schema_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.SearchServiceAsyncClient", - "shortName": "SearchServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.SearchServiceAsyncClient.search", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.SearchService.Search", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.SearchService", - "shortName": "SearchService" - }, - "shortName": "Search" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.SearchRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.services.search_service.pagers.SearchAsyncPager", - "shortName": "search" - }, - "description": "Sample for Search", - "file": "discoveryengine_v1alpha_generated_search_service_search_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_SearchService_Search_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": "discoveryengine_v1alpha_generated_search_service_search_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.SearchServiceClient", - "shortName": "SearchServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.SearchServiceClient.search", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.SearchService.Search", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.SearchService", - "shortName": "SearchService" - }, - "shortName": "Search" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.SearchRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.services.search_service.pagers.SearchPager", - "shortName": "search" - }, - "description": "Sample for Search", - "file": "discoveryengine_v1alpha_generated_search_service_search_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_SearchService_Search_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": "discoveryengine_v1alpha_generated_search_service_search_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.SiteSearchEngineServiceAsyncClient", - "shortName": "SiteSearchEngineServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.SiteSearchEngineServiceAsyncClient.recrawl_uris", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.RecrawlUris", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.SiteSearchEngineService", - "shortName": "SiteSearchEngineService" - }, - "shortName": "RecrawlUris" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.RecrawlUrisRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "recrawl_uris" - }, - "description": "Sample for RecrawlUris", - "file": "discoveryengine_v1alpha_generated_site_search_engine_service_recrawl_uris_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_SiteSearchEngineService_RecrawlUris_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": "discoveryengine_v1alpha_generated_site_search_engine_service_recrawl_uris_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.SiteSearchEngineServiceClient", - "shortName": "SiteSearchEngineServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.SiteSearchEngineServiceClient.recrawl_uris", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.SiteSearchEngineService.RecrawlUris", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.SiteSearchEngineService", - "shortName": "SiteSearchEngineService" - }, - "shortName": "RecrawlUris" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.RecrawlUrisRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "recrawl_uris" - }, - "description": "Sample for RecrawlUris", - "file": "discoveryengine_v1alpha_generated_site_search_engine_service_recrawl_uris_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_SiteSearchEngineService_RecrawlUris_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": "discoveryengine_v1alpha_generated_site_search_engine_service_recrawl_uris_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.UserEventServiceAsyncClient.collect_user_event", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.UserEventService.CollectUserEvent", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "CollectUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.CollectUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api.httpbody_pb2.HttpBody", - "shortName": "collect_user_event" - }, - "description": "Sample for CollectUserEvent", - "file": "discoveryengine_v1alpha_generated_user_event_service_collect_user_event_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_UserEventService_CollectUserEvent_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": "discoveryengine_v1alpha_generated_user_event_service_collect_user_event_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.UserEventServiceClient.collect_user_event", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.UserEventService.CollectUserEvent", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "CollectUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.CollectUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api.httpbody_pb2.HttpBody", - "shortName": "collect_user_event" - }, - "description": "Sample for CollectUserEvent", - "file": "discoveryengine_v1alpha_generated_user_event_service_collect_user_event_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_UserEventService_CollectUserEvent_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": "discoveryengine_v1alpha_generated_user_event_service_collect_user_event_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.UserEventServiceAsyncClient.import_user_events", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.UserEventService.ImportUserEvents", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "ImportUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.ImportUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "import_user_events" - }, - "description": "Sample for ImportUserEvents", - "file": "discoveryengine_v1alpha_generated_user_event_service_import_user_events_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_UserEventService_ImportUserEvents_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": "discoveryengine_v1alpha_generated_user_event_service_import_user_events_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.UserEventServiceClient.import_user_events", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.UserEventService.ImportUserEvents", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "ImportUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.ImportUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "import_user_events" - }, - "description": "Sample for ImportUserEvents", - "file": "discoveryengine_v1alpha_generated_user_event_service_import_user_events_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_UserEventService_ImportUserEvents_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": "discoveryengine_v1alpha_generated_user_event_service_import_user_events_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.UserEventServiceAsyncClient.purge_user_events", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.UserEventService.PurgeUserEvents", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "PurgeUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.PurgeUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "purge_user_events" - }, - "description": "Sample for PurgeUserEvents", - "file": "discoveryengine_v1alpha_generated_user_event_service_purge_user_events_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_UserEventService_PurgeUserEvents_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": "discoveryengine_v1alpha_generated_user_event_service_purge_user_events_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.UserEventServiceClient.purge_user_events", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.UserEventService.PurgeUserEvents", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "PurgeUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.PurgeUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "purge_user_events" - }, - "description": "Sample for PurgeUserEvents", - "file": "discoveryengine_v1alpha_generated_user_event_service_purge_user_events_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_UserEventService_PurgeUserEvents_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": "discoveryengine_v1alpha_generated_user_event_service_purge_user_events_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.UserEventServiceAsyncClient.write_user_event", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.UserEventService.WriteUserEvent", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "WriteUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.WriteUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.UserEvent", - "shortName": "write_user_event" - }, - "description": "Sample for WriteUserEvent", - "file": "discoveryengine_v1alpha_generated_user_event_service_write_user_event_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_UserEventService_WriteUserEvent_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": "discoveryengine_v1alpha_generated_user_event_service_write_user_event_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1alpha.UserEventServiceClient.write_user_event", - "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.UserEventService.WriteUserEvent", - "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "WriteUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.WriteUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.UserEvent", - "shortName": "write_user_event" - }, - "description": "Sample for WriteUserEvent", - "file": "discoveryengine_v1alpha_generated_user_event_service_write_user_event_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_UserEventService_WriteUserEvent_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": "discoveryengine_v1alpha_generated_user_event_service_write_user_event_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/scripts/fixup_discoveryengine_v1alpha_keywords.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/scripts/fixup_discoveryengine_v1alpha_keywords.py deleted file mode 100644 index 36332ca4a1e0..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/scripts/fixup_discoveryengine_v1alpha_keywords.py +++ /dev/null @@ -1,214 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class discoveryengineCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'collect_user_event': ('parent', 'user_event', 'uri', 'ets', ), - 'complete_query': ('data_store', 'query', 'query_model', 'user_pseudo_id', 'include_tail_suggestions', ), - 'converse_conversation': ('name', 'query', 'serving_config', 'conversation', 'safe_search', 'user_labels', 'summary_spec', ), - 'create_conversation': ('parent', 'conversation', ), - 'create_data_store': ('parent', 'data_store', 'data_store_id', 'create_advanced_site_search', ), - 'create_document': ('parent', 'document', 'document_id', ), - 'create_engine': ('parent', 'engine', 'engine_id', ), - 'create_schema': ('parent', 'schema', 'schema_id', ), - 'delete_conversation': ('name', ), - 'delete_data_store': ('name', ), - 'delete_document': ('name', ), - 'delete_engine': ('name', ), - 'delete_schema': ('name', ), - 'get_conversation': ('name', ), - 'get_data_store': ('name', ), - 'get_document': ('name', ), - 'get_engine': ('name', ), - 'get_schema': ('name', ), - 'import_documents': ('parent', 'inline_source', 'gcs_source', 'bigquery_source', 'error_config', 'reconciliation_mode', 'auto_generate_ids', 'id_field', ), - 'import_user_events': ('parent', 'inline_source', 'gcs_source', 'bigquery_source', 'error_config', ), - 'list_conversations': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'list_data_stores': ('parent', 'page_size', 'page_token', 'filter', ), - 'list_documents': ('parent', 'page_size', 'page_token', ), - 'list_engines': ('parent', 'page_size', 'page_token', 'filter', ), - 'list_schemas': ('parent', 'page_size', 'page_token', ), - 'pause_engine': ('name', ), - 'purge_documents': ('parent', 'filter', 'force', ), - 'purge_user_events': ('parent', 'filter', 'force', ), - 'recommend': ('serving_config', 'user_event', 'page_size', 'filter', 'validate_only', 'params', 'user_labels', ), - 'recrawl_uris': ('site_search_engine', 'uris', ), - 'resume_engine': ('name', ), - 'search': ('serving_config', 'branch', 'query', 'image_query', 'page_size', 'page_token', 'offset', 'filter', 'order_by', 'user_info', 'facet_specs', 'boost_spec', 'params', 'query_expansion_spec', 'spell_correction_spec', 'user_pseudo_id', 'content_search_spec', 'embedding_spec', 'ranking_expression', 'safe_search', 'user_labels', ), - 'tune_engine': ('name', ), - 'update_conversation': ('conversation', 'update_mask', ), - 'update_data_store': ('data_store', 'update_mask', ), - 'update_document': ('document', 'allow_missing', ), - 'update_engine': ('engine', 'update_mask', ), - 'update_schema': ('schema', 'allow_missing', ), - 'write_user_event': ('parent', 'user_event', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=discoveryengineCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the discoveryengine client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/setup.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/setup.py deleted file mode 100644 index 513896d68575..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/setup.py +++ /dev/null @@ -1,90 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-discoveryengine' - - -description = "Google Cloud Discoveryengine API client library" - -version = {} -with open(os.path.join(package_root, 'google/cloud/discoveryengine/gapic_version.py')) as fp: - exec(fp.read(), version) -version = version["__version__"] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "proto-plus >= 1.22.0, <2.0.0dev", - "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", - "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", -] -url = "https://github.com/googleapis/python-discoveryengine" - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, "README.rst") -with io.open(readme_filename, encoding="utf-8") as readme_file: - readme = readme_file.read() - -packages = [ - package - for package in setuptools.PEP420PackageFinder.find() - if package.startswith("google") -] - -namespaces = ["google", "google.cloud"] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - namespace_packages=namespaces, - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.10.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.10.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.11.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.11.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.12.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.12.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.7.txt deleted file mode 100644 index 6c44adfea7ee..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.7.txt +++ /dev/null @@ -1,9 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.0 -proto-plus==1.22.0 -protobuf==3.19.5 diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.8.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.8.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.9.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/testing/constraints-3.9.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/__init__.py deleted file mode 100644 index 1b4db446eb8d..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/__init__.py deleted file mode 100644 index 1b4db446eb8d..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/__init__.py deleted file mode 100644 index 1b4db446eb8d..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/__init__.py deleted file mode 100644 index 1b4db446eb8d..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_completion_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_completion_service.py deleted file mode 100644 index 1db2af92f704..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_completion_service.py +++ /dev/null @@ -1,1920 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.discoveryengine_v1alpha.services.completion_service import CompletionServiceAsyncClient -from google.cloud.discoveryengine_v1alpha.services.completion_service import CompletionServiceClient -from google.cloud.discoveryengine_v1alpha.services.completion_service import transports -from google.cloud.discoveryengine_v1alpha.types import completion_service -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert CompletionServiceClient._get_default_mtls_endpoint(None) is None - assert CompletionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (CompletionServiceClient, "grpc"), - (CompletionServiceAsyncClient, "grpc_asyncio"), - (CompletionServiceClient, "rest"), -]) -def test_completion_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.CompletionServiceGrpcTransport, "grpc"), - (transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.CompletionServiceRestTransport, "rest"), -]) -def test_completion_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", [ - (CompletionServiceClient, "grpc"), - (CompletionServiceAsyncClient, "grpc_asyncio"), - (CompletionServiceClient, "rest"), -]) -def test_completion_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -def test_completion_service_client_get_transport_class(): - transport = CompletionServiceClient.get_transport_class() - available_transports = [ - transports.CompletionServiceGrpcTransport, - transports.CompletionServiceRestTransport, - ] - assert transport in available_transports - - transport = CompletionServiceClient.get_transport_class("grpc") - assert transport == transports.CompletionServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (CompletionServiceClient, transports.CompletionServiceRestTransport, "rest"), -]) -@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) -@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) -def test_completion_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(CompletionServiceClient, '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(CompletionServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "true"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "false"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (CompletionServiceClient, transports.CompletionServiceRestTransport, "rest", "true"), - (CompletionServiceClient, transports.CompletionServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) -@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_completion_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 - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - CompletionServiceClient, CompletionServiceAsyncClient -]) -@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) -@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) -def test_completion_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (CompletionServiceClient, transports.CompletionServiceRestTransport, "rest"), -]) -def test_completion_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, - 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", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (CompletionServiceClient, transports.CompletionServiceRestTransport, "rest", None), -]) -def test_completion_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, - scopes=None, - client_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_completion_service_client_client_options_from_dict(): - with mock.patch('google.cloud.discoveryengine_v1alpha.services.completion_service.transports.CompletionServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = CompletionServiceClient( - 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", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_completion_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, - scopes=None, - client_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - completion_service.CompleteQueryRequest, - dict, -]) -def test_complete_query(request_type, transport: str = 'grpc'): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = completion_service.CompleteQueryResponse( - tail_match_triggered=True, - ) - response = client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, completion_service.CompleteQueryResponse) - assert response.tail_match_triggered is True - - -def test_complete_query_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - client.complete_query() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - -@pytest.mark.asyncio -async def test_complete_query_async(transport: str = 'grpc_asyncio', request_type=completion_service.CompleteQueryRequest): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse( - tail_match_triggered=True, - )) - response = await client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, completion_service.CompleteQueryResponse) - assert response.tail_match_triggered is True - - -@pytest.mark.asyncio -async def test_complete_query_async_from_dict(): - await test_complete_query_async(request_type=dict) - - -def test_complete_query_field_headers(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = completion_service.CompleteQueryRequest() - - request.data_store = 'data_store_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - call.return_value = completion_service.CompleteQueryResponse() - client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'data_store=data_store_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_complete_query_field_headers_async(): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = completion_service.CompleteQueryRequest() - - request.data_store = 'data_store_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse()) - await client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'data_store=data_store_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - completion_service.CompleteQueryRequest, - dict, -]) -def test_complete_query_rest(request_type): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'data_store': 'projects/sample1/locations/sample2/dataStores/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 = completion_service.CompleteQueryResponse( - tail_match_triggered=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = completion_service.CompleteQueryResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.complete_query(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, completion_service.CompleteQueryResponse) - assert response.tail_match_triggered is True - - -def test_complete_query_rest_required_fields(request_type=completion_service.CompleteQueryRequest): - transport_class = transports.CompletionServiceRestTransport - - request_init = {} - request_init["data_store"] = "" - request_init["query"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "query" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).complete_query._get_unset_required_fields(jsonified_request) - 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["dataStore"] = 'data_store_value' - jsonified_request["query"] = 'query_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).complete_query._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("include_tail_suggestions", "query", "query_model", "user_pseudo_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "dataStore" in jsonified_request - assert jsonified_request["dataStore"] == 'data_store_value' - assert "query" in jsonified_request - assert jsonified_request["query"] == 'query_value' - - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = completion_service.CompleteQueryResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = completion_service.CompleteQueryResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.complete_query(request) - - expected_params = [ - ( - "query", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_complete_query_rest_unset_required_fields(): - transport = transports.CompletionServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.complete_query._get_unset_required_fields({}) - assert set(unset_fields) == (set(("includeTailSuggestions", "query", "queryModel", "userPseudoId", )) & set(("dataStore", "query", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_complete_query_rest_interceptors(null_interceptor): - transport = transports.CompletionServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.CompletionServiceRestInterceptor(), - ) - client = CompletionServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.CompletionServiceRestInterceptor, "post_complete_query") as post, \ - mock.patch.object(transports.CompletionServiceRestInterceptor, "pre_complete_query") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = completion_service.CompleteQueryRequest.pb(completion_service.CompleteQueryRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = completion_service.CompleteQueryResponse.to_json(completion_service.CompleteQueryResponse()) - - request = completion_service.CompleteQueryRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = completion_service.CompleteQueryResponse() - - client.complete_query(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_complete_query_rest_bad_request(transport: str = 'rest', request_type=completion_service.CompleteQueryRequest): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'data_store': 'projects/sample1/locations/sample2/dataStores/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.complete_query(request) - - -def test_complete_query_rest_error(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = CompletionServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.CompletionServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.CompletionServiceGrpcTransport, - transports.CompletionServiceGrpcAsyncIOTransport, - transports.CompletionServiceRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = CompletionServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.CompletionServiceGrpcTransport, - ) - -def test_completion_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.CompletionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_completion_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.discoveryengine_v1alpha.services.completion_service.transports.CompletionServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.CompletionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'complete_query', - 'get_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_completion_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.discoveryengine_v1alpha.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CompletionServiceTransport( - 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_completion_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.discoveryengine_v1alpha.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CompletionServiceTransport() - adc.assert_called_once() - - -def test_completion_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) - CompletionServiceClient() - 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.CompletionServiceGrpcTransport, - transports.CompletionServiceGrpcAsyncIOTransport, - ], -) -def test_completion_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.CompletionServiceGrpcTransport, - transports.CompletionServiceGrpcAsyncIOTransport, - transports.CompletionServiceRestTransport, - ], -) -def test_completion_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.CompletionServiceGrpcTransport, grpc_helpers), - (transports.CompletionServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_completion_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) -def test_completion_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_completion_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.CompletionServiceRestTransport ( - 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_completion_service_host_no_port(transport_name): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_completion_service_host_with_port(transport_name): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_completion_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = CompletionServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = CompletionServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.complete_query._session - session2 = client2.transport.complete_query._session - assert session1 != session2 -def test_completion_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CompletionServiceGrpcTransport( - 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_completion_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CompletionServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) -def test_completion_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.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) -def test_completion_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_data_store_path(): - project = "squid" - location = "clam" - data_store = "whelk" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) - actual = CompletionServiceClient.data_store_path(project, location, data_store) - assert expected == actual - - -def test_parse_data_store_path(): - expected = { - "project": "octopus", - "location": "oyster", - "data_store": "nudibranch", - } - path = CompletionServiceClient.data_store_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_data_store_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = CompletionServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = CompletionServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = CompletionServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = CompletionServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = CompletionServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = CompletionServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = CompletionServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = CompletionServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = CompletionServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = CompletionServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.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.CompletionServiceTransport, '_prep_wrapped_messages') as prep: - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = CompletionServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_get_operation(transport: str = "grpc"): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = CompletionServiceClient( - 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 = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = CompletionServiceClient( - 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 = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = CompletionServiceClient( - 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", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_conversational_search_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_conversational_search_service.py deleted file mode 100644 index 40e254d2a90f..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_conversational_search_service.py +++ /dev/null @@ -1,4908 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.discoveryengine_v1alpha.services.conversational_search_service import ConversationalSearchServiceAsyncClient -from google.cloud.discoveryengine_v1alpha.services.conversational_search_service import ConversationalSearchServiceClient -from google.cloud.discoveryengine_v1alpha.services.conversational_search_service import pagers -from google.cloud.discoveryengine_v1alpha.services.conversational_search_service import transports -from google.cloud.discoveryengine_v1alpha.types import conversation -from google.cloud.discoveryengine_v1alpha.types import conversation as gcd_conversation -from google.cloud.discoveryengine_v1alpha.types import conversational_search_service -from google.cloud.discoveryengine_v1alpha.types import search_service -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert ConversationalSearchServiceClient._get_default_mtls_endpoint(None) is None - assert ConversationalSearchServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ConversationalSearchServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ConversationalSearchServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ConversationalSearchServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ConversationalSearchServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ConversationalSearchServiceClient, "grpc"), - (ConversationalSearchServiceAsyncClient, "grpc_asyncio"), - (ConversationalSearchServiceClient, "rest"), -]) -def test_conversational_search_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ConversationalSearchServiceGrpcTransport, "grpc"), - (transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ConversationalSearchServiceRestTransport, "rest"), -]) -def test_conversational_search_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", [ - (ConversationalSearchServiceClient, "grpc"), - (ConversationalSearchServiceAsyncClient, "grpc_asyncio"), - (ConversationalSearchServiceClient, "rest"), -]) -def test_conversational_search_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -def test_conversational_search_service_client_get_transport_class(): - transport = ConversationalSearchServiceClient.get_transport_class() - available_transports = [ - transports.ConversationalSearchServiceGrpcTransport, - transports.ConversationalSearchServiceRestTransport, - ] - assert transport in available_transports - - transport = ConversationalSearchServiceClient.get_transport_class("grpc") - assert transport == transports.ConversationalSearchServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport, "grpc"), - (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (ConversationalSearchServiceClient, transports.ConversationalSearchServiceRestTransport, "rest"), -]) -@mock.patch.object(ConversationalSearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationalSearchServiceClient)) -@mock.patch.object(ConversationalSearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationalSearchServiceAsyncClient)) -def test_conversational_search_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(ConversationalSearchServiceClient, '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(ConversationalSearchServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport, "grpc", "true"), - (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport, "grpc", "false"), - (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (ConversationalSearchServiceClient, transports.ConversationalSearchServiceRestTransport, "rest", "true"), - (ConversationalSearchServiceClient, transports.ConversationalSearchServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(ConversationalSearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationalSearchServiceClient)) -@mock.patch.object(ConversationalSearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationalSearchServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_conversational_search_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 - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - ConversationalSearchServiceClient, ConversationalSearchServiceAsyncClient -]) -@mock.patch.object(ConversationalSearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationalSearchServiceClient)) -@mock.patch.object(ConversationalSearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationalSearchServiceAsyncClient)) -def test_conversational_search_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport, "grpc"), - (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (ConversationalSearchServiceClient, transports.ConversationalSearchServiceRestTransport, "rest"), -]) -def test_conversational_search_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, - 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", [ - (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport, "grpc", grpc_helpers), - (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (ConversationalSearchServiceClient, transports.ConversationalSearchServiceRestTransport, "rest", None), -]) -def test_conversational_search_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, - scopes=None, - client_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_conversational_search_service_client_client_options_from_dict(): - with mock.patch('google.cloud.discoveryengine_v1alpha.services.conversational_search_service.transports.ConversationalSearchServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ConversationalSearchServiceClient( - 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", [ - (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport, "grpc", grpc_helpers), - (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_conversational_search_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, - scopes=None, - client_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - conversational_search_service.ConverseConversationRequest, - dict, -]) -def test_converse_conversation(request_type, transport: str = 'grpc'): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.converse_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversational_search_service.ConverseConversationResponse( - related_questions=['related_questions_value'], - ) - response = client.converse_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] == conversational_search_service.ConverseConversationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, conversational_search_service.ConverseConversationResponse) - assert response.related_questions == ['related_questions_value'] - - -def test_converse_conversation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.converse_conversation), - '__call__') as call: - client.converse_conversation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversational_search_service.ConverseConversationRequest() - -@pytest.mark.asyncio -async def test_converse_conversation_async(transport: str = 'grpc_asyncio', request_type=conversational_search_service.ConverseConversationRequest): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.converse_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversational_search_service.ConverseConversationResponse( - related_questions=['related_questions_value'], - )) - response = await client.converse_conversation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == conversational_search_service.ConverseConversationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, conversational_search_service.ConverseConversationResponse) - assert response.related_questions == ['related_questions_value'] - - -@pytest.mark.asyncio -async def test_converse_conversation_async_from_dict(): - await test_converse_conversation_async(request_type=dict) - - -def test_converse_conversation_field_headers(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversational_search_service.ConverseConversationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.converse_conversation), - '__call__') as call: - call.return_value = conversational_search_service.ConverseConversationResponse() - client.converse_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', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_converse_conversation_field_headers_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversational_search_service.ConverseConversationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.converse_conversation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversational_search_service.ConverseConversationResponse()) - await client.converse_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', - 'name=name_value', - ) in kw['metadata'] - - -def test_converse_conversation_flattened(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.converse_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversational_search_service.ConverseConversationResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.converse_conversation( - name='name_value', - query=conversation.TextInput(input='input_value'), - ) - - # Establish that the 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].query - mock_val = conversation.TextInput(input='input_value') - assert arg == mock_val - - -def test_converse_conversation_flattened_error(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.converse_conversation( - conversational_search_service.ConverseConversationRequest(), - name='name_value', - query=conversation.TextInput(input='input_value'), - ) - -@pytest.mark.asyncio -async def test_converse_conversation_flattened_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.converse_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversational_search_service.ConverseConversationResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversational_search_service.ConverseConversationResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.converse_conversation( - name='name_value', - query=conversation.TextInput(input='input_value'), - ) - - # Establish that 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].query - mock_val = conversation.TextInput(input='input_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_converse_conversation_flattened_error_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.converse_conversation( - conversational_search_service.ConverseConversationRequest(), - name='name_value', - query=conversation.TextInput(input='input_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - conversational_search_service.CreateConversationRequest, - dict, -]) -def test_create_conversation(request_type, transport: str = 'grpc'): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_conversation.Conversation( - name='name_value', - state=gcd_conversation.Conversation.State.IN_PROGRESS, - user_pseudo_id='user_pseudo_id_value', - ) - response = client.create_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] == conversational_search_service.CreateConversationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_conversation.Conversation) - assert response.name == 'name_value' - assert response.state == gcd_conversation.Conversation.State.IN_PROGRESS - assert response.user_pseudo_id == 'user_pseudo_id_value' - - -def test_create_conversation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_conversation), - '__call__') as call: - client.create_conversation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversational_search_service.CreateConversationRequest() - -@pytest.mark.asyncio -async def test_create_conversation_async(transport: str = 'grpc_asyncio', request_type=conversational_search_service.CreateConversationRequest): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation.Conversation( - name='name_value', - state=gcd_conversation.Conversation.State.IN_PROGRESS, - user_pseudo_id='user_pseudo_id_value', - )) - response = await client.create_conversation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == conversational_search_service.CreateConversationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_conversation.Conversation) - assert response.name == 'name_value' - assert response.state == gcd_conversation.Conversation.State.IN_PROGRESS - assert response.user_pseudo_id == 'user_pseudo_id_value' - - -@pytest.mark.asyncio -async def test_create_conversation_async_from_dict(): - await test_create_conversation_async(request_type=dict) - - -def test_create_conversation_field_headers(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversational_search_service.CreateConversationRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_conversation), - '__call__') as call: - call.return_value = gcd_conversation.Conversation() - client.create_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', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_conversation_field_headers_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversational_search_service.CreateConversationRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_conversation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation.Conversation()) - await client.create_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', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_conversation_flattened(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_conversation.Conversation() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_conversation( - parent='parent_value', - conversation=gcd_conversation.Conversation(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].conversation - mock_val = gcd_conversation.Conversation(name='name_value') - assert arg == mock_val - - -def test_create_conversation_flattened_error(): - client = ConversationalSearchServiceClient( - credentials=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_conversation( - conversational_search_service.CreateConversationRequest(), - parent='parent_value', - conversation=gcd_conversation.Conversation(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_conversation_flattened_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_conversation.Conversation() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation.Conversation()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_conversation( - parent='parent_value', - conversation=gcd_conversation.Conversation(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].conversation - mock_val = gcd_conversation.Conversation(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_conversation_flattened_error_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_conversation( - conversational_search_service.CreateConversationRequest(), - parent='parent_value', - conversation=gcd_conversation.Conversation(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - conversational_search_service.DeleteConversationRequest, - dict, -]) -def test_delete_conversation(request_type, transport: str = 'grpc'): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_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] == conversational_search_service.DeleteConversationRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_conversation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_conversation), - '__call__') as call: - client.delete_conversation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversational_search_service.DeleteConversationRequest() - -@pytest.mark.asyncio -async def test_delete_conversation_async(transport: str = 'grpc_asyncio', request_type=conversational_search_service.DeleteConversationRequest): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_conversation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == conversational_search_service.DeleteConversationRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_conversation_async_from_dict(): - await test_delete_conversation_async(request_type=dict) - - -def test_delete_conversation_field_headers(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversational_search_service.DeleteConversationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_conversation), - '__call__') as call: - call.return_value = None - client.delete_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', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_conversation_field_headers_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversational_search_service.DeleteConversationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_conversation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_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', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_conversation_flattened(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, 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 = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_conversation( - 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_conversation_flattened_error(): - client = ConversationalSearchServiceClient( - credentials=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_conversation( - conversational_search_service.DeleteConversationRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_conversation_flattened_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, 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 = 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_conversation( - 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_conversation_flattened_error_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_conversation( - conversational_search_service.DeleteConversationRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - conversational_search_service.UpdateConversationRequest, - dict, -]) -def test_update_conversation(request_type, transport: str = 'grpc'): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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 = gcd_conversation.Conversation( - name='name_value', - state=gcd_conversation.Conversation.State.IN_PROGRESS, - user_pseudo_id='user_pseudo_id_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] - assert args[0] == conversational_search_service.UpdateConversationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_conversation.Conversation) - assert response.name == 'name_value' - assert response.state == gcd_conversation.Conversation.State.IN_PROGRESS - assert response.user_pseudo_id == 'user_pseudo_id_value' - - -def test_update_conversation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_conversation), - '__call__') as call: - client.update_conversation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversational_search_service.UpdateConversationRequest() - -@pytest.mark.asyncio -async def test_update_conversation_async(transport: str = 'grpc_asyncio', request_type=conversational_search_service.UpdateConversationRequest): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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(gcd_conversation.Conversation( - name='name_value', - state=gcd_conversation.Conversation.State.IN_PROGRESS, - user_pseudo_id='user_pseudo_id_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] - assert args[0] == conversational_search_service.UpdateConversationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_conversation.Conversation) - assert response.name == 'name_value' - assert response.state == gcd_conversation.Conversation.State.IN_PROGRESS - assert response.user_pseudo_id == 'user_pseudo_id_value' - - -@pytest.mark.asyncio -async def test_update_conversation_async_from_dict(): - await test_update_conversation_async(request_type=dict) - - -def test_update_conversation_field_headers(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversational_search_service.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 = gcd_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 = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversational_search_service.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(gcd_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 = ConversationalSearchServiceClient( - 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 = gcd_conversation.Conversation() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_conversation( - conversation=gcd_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 = gcd_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 = ConversationalSearchServiceClient( - credentials=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( - conversational_search_service.UpdateConversationRequest(), - conversation=gcd_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 = ConversationalSearchServiceAsyncClient( - 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 = gcd_conversation.Conversation() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_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=gcd_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 = gcd_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 = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_conversation( - conversational_search_service.UpdateConversationRequest(), - conversation=gcd_conversation.Conversation(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - conversational_search_service.GetConversationRequest, - dict, -]) -def test_get_conversation(request_type, transport: str = 'grpc'): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation.Conversation( - name='name_value', - state=conversation.Conversation.State.IN_PROGRESS, - user_pseudo_id='user_pseudo_id_value', - ) - response = client.get_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] == conversational_search_service.GetConversationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, conversation.Conversation) - assert response.name == 'name_value' - assert response.state == conversation.Conversation.State.IN_PROGRESS - assert response.user_pseudo_id == 'user_pseudo_id_value' - - -def test_get_conversation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_conversation), - '__call__') as call: - client.get_conversation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversational_search_service.GetConversationRequest() - -@pytest.mark.asyncio -async def test_get_conversation_async(transport: str = 'grpc_asyncio', request_type=conversational_search_service.GetConversationRequest): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation( - name='name_value', - state=conversation.Conversation.State.IN_PROGRESS, - user_pseudo_id='user_pseudo_id_value', - )) - response = await client.get_conversation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == conversational_search_service.GetConversationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, conversation.Conversation) - assert response.name == 'name_value' - assert response.state == conversation.Conversation.State.IN_PROGRESS - assert response.user_pseudo_id == 'user_pseudo_id_value' - - -@pytest.mark.asyncio -async def test_get_conversation_async_from_dict(): - await test_get_conversation_async(request_type=dict) - - -def test_get_conversation_field_headers(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversational_search_service.GetConversationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_conversation), - '__call__') as call: - call.return_value = conversation.Conversation() - client.get_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', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_conversation_field_headers_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversational_search_service.GetConversationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_conversation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation()) - await client.get_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', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_conversation_flattened(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation.Conversation() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_conversation( - 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_conversation_flattened_error(): - client = ConversationalSearchServiceClient( - credentials=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_conversation( - conversational_search_service.GetConversationRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_conversation_flattened_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation.Conversation() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_conversation( - 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_conversation_flattened_error_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_conversation( - conversational_search_service.GetConversationRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - conversational_search_service.ListConversationsRequest, - dict, -]) -def test_list_conversations(request_type, transport: str = 'grpc'): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_conversations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversational_search_service.ListConversationsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_conversations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == conversational_search_service.ListConversationsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConversationsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_conversations_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversations), - '__call__') as call: - client.list_conversations() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversational_search_service.ListConversationsRequest() - -@pytest.mark.asyncio -async def test_list_conversations_async(transport: str = 'grpc_asyncio', request_type=conversational_search_service.ListConversationsRequest): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_conversations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversational_search_service.ListConversationsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_conversations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == conversational_search_service.ListConversationsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConversationsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_conversations_async_from_dict(): - await test_list_conversations_async(request_type=dict) - - -def test_list_conversations_field_headers(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversational_search_service.ListConversationsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversations), - '__call__') as call: - call.return_value = conversational_search_service.ListConversationsResponse() - client.list_conversations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_conversations_field_headers_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversational_search_service.ListConversationsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversations), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversational_search_service.ListConversationsResponse()) - await client.list_conversations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_conversations_flattened(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversational_search_service.ListConversationsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_conversations( - 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_conversations_flattened_error(): - client = ConversationalSearchServiceClient( - credentials=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_conversations( - conversational_search_service.ListConversationsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_conversations_flattened_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversational_search_service.ListConversationsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversational_search_service.ListConversationsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_conversations( - 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_conversations_flattened_error_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_conversations( - conversational_search_service.ListConversationsRequest(), - parent='parent_value', - ) - - -def test_list_conversations_pager(transport_name: str = "grpc"): - client = ConversationalSearchServiceClient( - 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_conversations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - conversation.Conversation(), - ], - next_page_token='abc', - ), - conversational_search_service.ListConversationsResponse( - conversations=[], - next_page_token='def', - ), - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - ], - next_page_token='ghi', - ), - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_conversations(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, conversation.Conversation) - for i in results) -def test_list_conversations_pages(transport_name: str = "grpc"): - client = ConversationalSearchServiceClient( - 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_conversations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - conversation.Conversation(), - ], - next_page_token='abc', - ), - conversational_search_service.ListConversationsResponse( - conversations=[], - next_page_token='def', - ), - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - ], - next_page_token='ghi', - ), - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - ], - ), - RuntimeError, - ) - pages = list(client.list_conversations(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_conversations_async_pager(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - conversation.Conversation(), - ], - next_page_token='abc', - ), - conversational_search_service.ListConversationsResponse( - conversations=[], - next_page_token='def', - ), - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - ], - next_page_token='ghi', - ), - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_conversations(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, conversation.Conversation) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_conversations_async_pages(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - conversation.Conversation(), - ], - next_page_token='abc', - ), - conversational_search_service.ListConversationsResponse( - conversations=[], - next_page_token='def', - ), - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - ], - next_page_token='ghi', - ), - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_conversations(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", [ - conversational_search_service.ConverseConversationRequest, - dict, -]) -def test_converse_conversation_rest(request_type): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/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 = conversational_search_service.ConverseConversationResponse( - related_questions=['related_questions_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 = conversational_search_service.ConverseConversationResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.converse_conversation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, conversational_search_service.ConverseConversationResponse) - assert response.related_questions == ['related_questions_value'] - - -def test_converse_conversation_rest_required_fields(request_type=conversational_search_service.ConverseConversationRequest): - transport_class = transports.ConversationalSearchServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).converse_conversation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).converse_conversation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = conversational_search_service.ConverseConversationResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = conversational_search_service.ConverseConversationResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.converse_conversation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_converse_conversation_rest_unset_required_fields(): - transport = transports.ConversationalSearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.converse_conversation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "query", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_converse_conversation_rest_interceptors(null_interceptor): - transport = transports.ConversationalSearchServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationalSearchServiceRestInterceptor(), - ) - client = ConversationalSearchServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "post_converse_conversation") as post, \ - mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "pre_converse_conversation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversational_search_service.ConverseConversationRequest.pb(conversational_search_service.ConverseConversationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = conversational_search_service.ConverseConversationResponse.to_json(conversational_search_service.ConverseConversationResponse()) - - request = conversational_search_service.ConverseConversationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = conversational_search_service.ConverseConversationResponse() - - client.converse_conversation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_converse_conversation_rest_bad_request(transport: str = 'rest', request_type=conversational_search_service.ConverseConversationRequest): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.converse_conversation(request) - - -def test_converse_conversation_rest_flattened(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversational_search_service.ConverseConversationResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - query=conversation.TextInput(input='input_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 = conversational_search_service.ConverseConversationResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.converse_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/{name=projects/*/locations/*/dataStores/*/conversations/*}:converse" % client.transport._host, args[1]) - - -def test_converse_conversation_rest_flattened_error(transport: str = 'rest'): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.converse_conversation( - conversational_search_service.ConverseConversationRequest(), - name='name_value', - query=conversation.TextInput(input='input_value'), - ) - - -def test_converse_conversation_rest_error(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - conversational_search_service.CreateConversationRequest, - dict, -]) -def test_create_conversation_rest(request_type): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - request_init["conversation"] = {'name': 'name_value', 'state': 1, 'user_pseudo_id': 'user_pseudo_id_value', 'messages': [{'user_input': {'input': 'input_value', 'context': {'context_documents': ['context_documents_value1', 'context_documents_value2'], 'active_document': 'active_document_value'}}, 'reply': {'reply': 'reply_value', 'references': [{'uri': 'uri_value', 'anchor_text': 'anchor_text_value', 'start': 558, 'end': 311}], 'summary': {'summary_text': 'summary_text_value', 'summary_skipped_reasons': [1], 'safety_attributes': {'categories': ['categories_value1', 'categories_value2'], 'scores': [0.656, 0.657]}}}, 'create_time': {'seconds': 751, 'nanos': 543}}], 'start_time': {}, 'end_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 = conversational_search_service.CreateConversationRequest.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 = gcd_conversation.Conversation( - name='name_value', - state=gcd_conversation.Conversation.State.IN_PROGRESS, - user_pseudo_id='user_pseudo_id_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 = gcd_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 - response = client.create_conversation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_conversation.Conversation) - assert response.name == 'name_value' - assert response.state == gcd_conversation.Conversation.State.IN_PROGRESS - assert response.user_pseudo_id == 'user_pseudo_id_value' - - -def test_create_conversation_rest_required_fields(request_type=conversational_search_service.CreateConversationRequest): - transport_class = transports.ConversationalSearchServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_conversation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_conversation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_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': "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 = gcd_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 - - response = client.create_conversation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_conversation_rest_unset_required_fields(): - transport = transports.ConversationalSearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_conversation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "conversation", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_conversation_rest_interceptors(null_interceptor): - transport = transports.ConversationalSearchServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationalSearchServiceRestInterceptor(), - ) - client = ConversationalSearchServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "post_create_conversation") as post, \ - mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "pre_create_conversation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversational_search_service.CreateConversationRequest.pb(conversational_search_service.CreateConversationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_conversation.Conversation.to_json(gcd_conversation.Conversation()) - - request = conversational_search_service.CreateConversationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_conversation.Conversation() - - client.create_conversation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_conversation_rest_bad_request(transport: str = 'rest', request_type=conversational_search_service.CreateConversationRequest): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_conversation(request) - - -def test_create_conversation_rest_flattened(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_conversation.Conversation() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - conversation=gcd_conversation.Conversation(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 = gcd_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 - - client.create_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/{parent=projects/*/locations/*/dataStores/*}/conversations" % client.transport._host, args[1]) - - -def test_create_conversation_rest_flattened_error(transport: str = 'rest'): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.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_conversation( - conversational_search_service.CreateConversationRequest(), - parent='parent_value', - conversation=gcd_conversation.Conversation(name='name_value'), - ) - - -def test_create_conversation_rest_error(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - conversational_search_service.DeleteConversationRequest, - dict, -]) -def test_delete_conversation_rest(request_type): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/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 = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_conversation(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_conversation_rest_required_fields(request_type=conversational_search_service.DeleteConversationRequest): - transport_class = transports.ConversationalSearchServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_conversation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_conversation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ConversationalSearchServiceClient( - 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 - - response = client.delete_conversation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_conversation_rest_unset_required_fields(): - transport = transports.ConversationalSearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_conversation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_conversation_rest_interceptors(null_interceptor): - transport = transports.ConversationalSearchServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationalSearchServiceRestInterceptor(), - ) - client = ConversationalSearchServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "pre_delete_conversation") as pre: - pre.assert_not_called() - pb_message = conversational_search_service.DeleteConversationRequest.pb(conversational_search_service.DeleteConversationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = conversational_search_service.DeleteConversationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_conversation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_conversation_rest_bad_request(transport: str = 'rest', request_type=conversational_search_service.DeleteConversationRequest): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_conversation(request) - - -def test_delete_conversation_rest_flattened(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/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 = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_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/{name=projects/*/locations/*/dataStores/*/conversations/*}" % client.transport._host, args[1]) - - -def test_delete_conversation_rest_flattened_error(transport: str = 'rest'): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.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_conversation( - conversational_search_service.DeleteConversationRequest(), - name='name_value', - ) - - -def test_delete_conversation_rest_error(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - conversational_search_service.UpdateConversationRequest, - dict, -]) -def test_update_conversation_rest(request_type): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'conversation': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'}} - request_init["conversation"] = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4', 'state': 1, 'user_pseudo_id': 'user_pseudo_id_value', 'messages': [{'user_input': {'input': 'input_value', 'context': {'context_documents': ['context_documents_value1', 'context_documents_value2'], 'active_document': 'active_document_value'}}, 'reply': {'reply': 'reply_value', 'references': [{'uri': 'uri_value', 'anchor_text': 'anchor_text_value', 'start': 558, 'end': 311}], 'summary': {'summary_text': 'summary_text_value', 'summary_skipped_reasons': [1], 'safety_attributes': {'categories': ['categories_value1', 'categories_value2'], 'scores': [0.656, 0.657]}}}, 'create_time': {'seconds': 751, 'nanos': 543}}], 'start_time': {}, 'end_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 = conversational_search_service.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 = gcd_conversation.Conversation( - name='name_value', - state=gcd_conversation.Conversation.State.IN_PROGRESS, - user_pseudo_id='user_pseudo_id_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 = gcd_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 - response = client.update_conversation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_conversation.Conversation) - assert response.name == 'name_value' - assert response.state == gcd_conversation.Conversation.State.IN_PROGRESS - assert response.user_pseudo_id == 'user_pseudo_id_value' - - -def test_update_conversation_rest_required_fields(request_type=conversational_search_service.UpdateConversationRequest): - transport_class = transports.ConversationalSearchServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_conversation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_conversation._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_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 = gcd_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 - - response = client.update_conversation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_conversation_rest_unset_required_fields(): - transport = transports.ConversationalSearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_conversation._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("conversation", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_conversation_rest_interceptors(null_interceptor): - transport = transports.ConversationalSearchServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationalSearchServiceRestInterceptor(), - ) - client = ConversationalSearchServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "post_update_conversation") as post, \ - mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "pre_update_conversation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversational_search_service.UpdateConversationRequest.pb(conversational_search_service.UpdateConversationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_conversation.Conversation.to_json(gcd_conversation.Conversation()) - - request = conversational_search_service.UpdateConversationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_conversation.Conversation() - - client.update_conversation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_conversation_rest_bad_request(transport: str = 'rest', request_type=conversational_search_service.UpdateConversationRequest): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'conversation': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_conversation(request) - - -def test_update_conversation_rest_flattened(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_conversation.Conversation() - - # get arguments that satisfy an http rule for this method - sample_request = {'conversation': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'}} - - # get truthy value for each flattened field - mock_args = dict( - conversation=gcd_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 = gcd_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 - - 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/*/dataStores/*/conversations/*}" % client.transport._host, args[1]) - - -def test_update_conversation_rest_flattened_error(transport: str = 'rest'): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.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( - conversational_search_service.UpdateConversationRequest(), - conversation=gcd_conversation.Conversation(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_conversation_rest_error(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - conversational_search_service.GetConversationRequest, - dict, -]) -def test_get_conversation_rest(request_type): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/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 = conversation.Conversation( - name='name_value', - state=conversation.Conversation.State.IN_PROGRESS, - user_pseudo_id='user_pseudo_id_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 = 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 - response = client.get_conversation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, conversation.Conversation) - assert response.name == 'name_value' - assert response.state == conversation.Conversation.State.IN_PROGRESS - assert response.user_pseudo_id == 'user_pseudo_id_value' - - -def test_get_conversation_rest_required_fields(request_type=conversational_search_service.GetConversationRequest): - transport_class = transports.ConversationalSearchServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_conversation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_conversation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = 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': "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 = 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 - - response = client.get_conversation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_conversation_rest_unset_required_fields(): - transport = transports.ConversationalSearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_conversation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_conversation_rest_interceptors(null_interceptor): - transport = transports.ConversationalSearchServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationalSearchServiceRestInterceptor(), - ) - client = ConversationalSearchServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "post_get_conversation") as post, \ - mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "pre_get_conversation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversational_search_service.GetConversationRequest.pb(conversational_search_service.GetConversationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = conversation.Conversation.to_json(conversation.Conversation()) - - request = conversational_search_service.GetConversationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = conversation.Conversation() - - client.get_conversation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_conversation_rest_bad_request(transport: str = 'rest', request_type=conversational_search_service.GetConversationRequest): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_conversation(request) - - -def test_get_conversation_rest_flattened(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation.Conversation() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/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 = 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 - - client.get_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/{name=projects/*/locations/*/dataStores/*/conversations/*}" % client.transport._host, args[1]) - - -def test_get_conversation_rest_flattened_error(transport: str = 'rest'): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.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_conversation( - conversational_search_service.GetConversationRequest(), - name='name_value', - ) - - -def test_get_conversation_rest_error(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - conversational_search_service.ListConversationsRequest, - dict, -]) -def test_list_conversations_rest(request_type): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/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 = conversational_search_service.ListConversationsResponse( - next_page_token='next_page_token_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 = conversational_search_service.ListConversationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_conversations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConversationsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_conversations_rest_required_fields(request_type=conversational_search_service.ListConversationsRequest): - transport_class = transports.ConversationalSearchServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_conversations._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_conversations._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = conversational_search_service.ListConversationsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = conversational_search_service.ListConversationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_conversations(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_conversations_rest_unset_required_fields(): - transport = transports.ConversationalSearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_conversations._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_conversations_rest_interceptors(null_interceptor): - transport = transports.ConversationalSearchServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationalSearchServiceRestInterceptor(), - ) - client = ConversationalSearchServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "post_list_conversations") as post, \ - mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "pre_list_conversations") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversational_search_service.ListConversationsRequest.pb(conversational_search_service.ListConversationsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = conversational_search_service.ListConversationsResponse.to_json(conversational_search_service.ListConversationsResponse()) - - request = conversational_search_service.ListConversationsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = conversational_search_service.ListConversationsResponse() - - client.list_conversations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_conversations_rest_bad_request(transport: str = 'rest', request_type=conversational_search_service.ListConversationsRequest): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_conversations(request) - - -def test_list_conversations_rest_flattened(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversational_search_service.ListConversationsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/dataStores/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 = conversational_search_service.ListConversationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_conversations(**mock_args) - - # Establish that the underlying call 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/*/dataStores/*}/conversations" % client.transport._host, args[1]) - - -def test_list_conversations_rest_flattened_error(transport: str = 'rest'): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.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_conversations( - conversational_search_service.ListConversationsRequest(), - parent='parent_value', - ) - - -def test_list_conversations_rest_pager(transport: str = 'rest'): - client = ConversationalSearchServiceClient( - 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 = ( - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - conversation.Conversation(), - ], - next_page_token='abc', - ), - conversational_search_service.ListConversationsResponse( - conversations=[], - next_page_token='def', - ), - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - ], - next_page_token='ghi', - ), - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(conversational_search_service.ListConversationsResponse.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/dataStores/sample3'} - - pager = client.list_conversations(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, conversation.Conversation) - for i in results) - - pages = list(client.list_conversations(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.ConversationalSearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ConversationalSearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ConversationalSearchServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ConversationalSearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ConversationalSearchServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ConversationalSearchServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ConversationalSearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ConversationalSearchServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ConversationalSearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ConversationalSearchServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ConversationalSearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ConversationalSearchServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ConversationalSearchServiceGrpcTransport, - transports.ConversationalSearchServiceGrpcAsyncIOTransport, - transports.ConversationalSearchServiceRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = ConversationalSearchServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ConversationalSearchServiceGrpcTransport, - ) - -def test_conversational_search_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ConversationalSearchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_conversational_search_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.discoveryengine_v1alpha.services.conversational_search_service.transports.ConversationalSearchServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ConversationalSearchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'converse_conversation', - 'create_conversation', - 'delete_conversation', - 'update_conversation', - 'get_conversation', - 'list_conversations', - 'get_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_conversational_search_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.discoveryengine_v1alpha.services.conversational_search_service.transports.ConversationalSearchServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ConversationalSearchServiceTransport( - 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_conversational_search_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.discoveryengine_v1alpha.services.conversational_search_service.transports.ConversationalSearchServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ConversationalSearchServiceTransport() - adc.assert_called_once() - - -def test_conversational_search_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) - ConversationalSearchServiceClient() - 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.ConversationalSearchServiceGrpcTransport, - transports.ConversationalSearchServiceGrpcAsyncIOTransport, - ], -) -def test_conversational_search_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.ConversationalSearchServiceGrpcTransport, - transports.ConversationalSearchServiceGrpcAsyncIOTransport, - transports.ConversationalSearchServiceRestTransport, - ], -) -def test_conversational_search_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.ConversationalSearchServiceGrpcTransport, grpc_helpers), - (transports.ConversationalSearchServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_conversational_search_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ConversationalSearchServiceGrpcTransport, transports.ConversationalSearchServiceGrpcAsyncIOTransport]) -def test_conversational_search_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_conversational_search_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.ConversationalSearchServiceRestTransport ( - 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_conversational_search_service_host_no_port(transport_name): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_conversational_search_service_host_with_port(transport_name): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_conversational_search_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = ConversationalSearchServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = ConversationalSearchServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.converse_conversation._session - session2 = client2.transport.converse_conversation._session - assert session1 != session2 - session1 = client1.transport.create_conversation._session - session2 = client2.transport.create_conversation._session - assert session1 != session2 - 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 - session1 = client1.transport.list_conversations._session - session2 = client2.transport.list_conversations._session - assert session1 != session2 -def test_conversational_search_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ConversationalSearchServiceGrpcTransport( - 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_conversational_search_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ConversationalSearchServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.ConversationalSearchServiceGrpcTransport, transports.ConversationalSearchServiceGrpcAsyncIOTransport]) -def test_conversational_search_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.ConversationalSearchServiceGrpcTransport, transports.ConversationalSearchServiceGrpcAsyncIOTransport]) -def test_conversational_search_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_conversation_path(): - project = "squid" - location = "clam" - data_store = "whelk" - conversation = "octopus" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}/conversations/{conversation}".format(project=project, location=location, data_store=data_store, conversation=conversation, ) - actual = ConversationalSearchServiceClient.conversation_path(project, location, data_store, conversation) - assert expected == actual - - -def test_parse_conversation_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "data_store": "cuttlefish", - "conversation": "mussel", - } - path = ConversationalSearchServiceClient.conversation_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationalSearchServiceClient.parse_conversation_path(path) - assert expected == actual - -def test_data_store_path(): - project = "winkle" - location = "nautilus" - data_store = "scallop" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) - actual = ConversationalSearchServiceClient.data_store_path(project, location, data_store) - assert expected == actual - - -def test_parse_data_store_path(): - expected = { - "project": "abalone", - "location": "squid", - "data_store": "clam", - } - path = ConversationalSearchServiceClient.data_store_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationalSearchServiceClient.parse_data_store_path(path) - assert expected == actual - -def test_document_path(): - project = "whelk" - location = "octopus" - data_store = "oyster" - branch = "nudibranch" - document = "cuttlefish" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) - actual = ConversationalSearchServiceClient.document_path(project, location, data_store, branch, document) - assert expected == actual - - -def test_parse_document_path(): - expected = { - "project": "mussel", - "location": "winkle", - "data_store": "nautilus", - "branch": "scallop", - "document": "abalone", - } - path = ConversationalSearchServiceClient.document_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationalSearchServiceClient.parse_document_path(path) - assert expected == actual - -def test_serving_config_path(): - project = "squid" - location = "clam" - data_store = "whelk" - serving_config = "octopus" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}/servingConfigs/{serving_config}".format(project=project, location=location, data_store=data_store, serving_config=serving_config, ) - actual = ConversationalSearchServiceClient.serving_config_path(project, location, data_store, serving_config) - assert expected == actual - - -def test_parse_serving_config_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "data_store": "cuttlefish", - "serving_config": "mussel", - } - path = ConversationalSearchServiceClient.serving_config_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationalSearchServiceClient.parse_serving_config_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ConversationalSearchServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nautilus", - } - path = ConversationalSearchServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationalSearchServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "scallop" - expected = "folders/{folder}".format(folder=folder, ) - actual = ConversationalSearchServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "abalone", - } - path = ConversationalSearchServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationalSearchServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "squid" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ConversationalSearchServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "clam", - } - path = ConversationalSearchServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationalSearchServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "whelk" - expected = "projects/{project}".format(project=project, ) - actual = ConversationalSearchServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "octopus", - } - path = ConversationalSearchServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationalSearchServiceClient.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 = ConversationalSearchServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - } - path = ConversationalSearchServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationalSearchServiceClient.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.ConversationalSearchServiceTransport, '_prep_wrapped_messages') as prep: - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ConversationalSearchServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = ConversationalSearchServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_get_operation(transport: str = "grpc"): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = ConversationalSearchServiceClient( - 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 = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = ConversationalSearchServiceClient( - 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 = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = ConversationalSearchServiceClient( - 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", [ - (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport), - (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_document_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_document_service.py deleted file mode 100644 index a06548425c15..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_document_service.py +++ /dev/null @@ -1,4999 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.discoveryengine_v1alpha.services.document_service import DocumentServiceAsyncClient -from google.cloud.discoveryengine_v1alpha.services.document_service import DocumentServiceClient -from google.cloud.discoveryengine_v1alpha.services.document_service import pagers -from google.cloud.discoveryengine_v1alpha.services.document_service import transports -from google.cloud.discoveryengine_v1alpha.types import document -from google.cloud.discoveryengine_v1alpha.types import document as gcd_document -from google.cloud.discoveryengine_v1alpha.types import document_service -from google.cloud.discoveryengine_v1alpha.types import import_config -from google.cloud.discoveryengine_v1alpha.types import purge_config -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import struct_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert DocumentServiceClient._get_default_mtls_endpoint(None) is None - assert DocumentServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert DocumentServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert DocumentServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert DocumentServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert DocumentServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (DocumentServiceClient, "grpc"), - (DocumentServiceAsyncClient, "grpc_asyncio"), - (DocumentServiceClient, "rest"), -]) -def test_document_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.DocumentServiceGrpcTransport, "grpc"), - (transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.DocumentServiceRestTransport, "rest"), -]) -def test_document_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", [ - (DocumentServiceClient, "grpc"), - (DocumentServiceAsyncClient, "grpc_asyncio"), - (DocumentServiceClient, "rest"), -]) -def test_document_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -def test_document_service_client_get_transport_class(): - transport = DocumentServiceClient.get_transport_class() - available_transports = [ - transports.DocumentServiceGrpcTransport, - transports.DocumentServiceRestTransport, - ] - assert transport in available_transports - - transport = DocumentServiceClient.get_transport_class("grpc") - assert transport == transports.DocumentServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc"), - (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (DocumentServiceClient, transports.DocumentServiceRestTransport, "rest"), -]) -@mock.patch.object(DocumentServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceClient)) -@mock.patch.object(DocumentServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceAsyncClient)) -def test_document_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(DocumentServiceClient, '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(DocumentServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc", "true"), - (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc", "false"), - (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (DocumentServiceClient, transports.DocumentServiceRestTransport, "rest", "true"), - (DocumentServiceClient, transports.DocumentServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(DocumentServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceClient)) -@mock.patch.object(DocumentServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_document_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 - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - DocumentServiceClient, DocumentServiceAsyncClient -]) -@mock.patch.object(DocumentServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceClient)) -@mock.patch.object(DocumentServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceAsyncClient)) -def test_document_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc"), - (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (DocumentServiceClient, transports.DocumentServiceRestTransport, "rest"), -]) -def test_document_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, - 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", [ - (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc", grpc_helpers), - (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (DocumentServiceClient, transports.DocumentServiceRestTransport, "rest", None), -]) -def test_document_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, - scopes=None, - client_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_document_service_client_client_options_from_dict(): - with mock.patch('google.cloud.discoveryengine_v1alpha.services.document_service.transports.DocumentServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = DocumentServiceClient( - 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", [ - (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc", grpc_helpers), - (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_document_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, - scopes=None, - client_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - document_service.GetDocumentRequest, - dict, -]) -def test_get_document(request_type, transport: str = 'grpc'): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document.Document( - name='name_value', - id='id_value', - schema_id='schema_id_value', - parent_document_id='parent_document_id_value', - json_data='json_data_value', - ) - response = client.get_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.GetDocumentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, document.Document) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.schema_id == 'schema_id_value' - assert response.parent_document_id == 'parent_document_id_value' - - -def test_get_document_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_document), - '__call__') as call: - client.get_document() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.GetDocumentRequest() - -@pytest.mark.asyncio -async def test_get_document_async(transport: str = 'grpc_asyncio', request_type=document_service.GetDocumentRequest): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document.Document( - name='name_value', - id='id_value', - schema_id='schema_id_value', - parent_document_id='parent_document_id_value', - )) - response = await client.get_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.GetDocumentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, document.Document) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.schema_id == 'schema_id_value' - assert response.parent_document_id == 'parent_document_id_value' - - -@pytest.mark.asyncio -async def test_get_document_async_from_dict(): - await test_get_document_async(request_type=dict) - - -def test_get_document_field_headers(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.GetDocumentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_document), - '__call__') as call: - call.return_value = document.Document() - client.get_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_document_field_headers_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.GetDocumentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_document), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.Document()) - await client.get_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_document_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document.Document() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_document( - 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_document_flattened_error(): - client = DocumentServiceClient( - credentials=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_document( - document_service.GetDocumentRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_document_flattened_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document.Document() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.Document()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_document( - 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_document_flattened_error_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_document( - document_service.GetDocumentRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_service.ListDocumentsRequest, - dict, -]) -def test_list_documents(request_type, transport: str = 'grpc'): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_documents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_service.ListDocumentsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_documents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.ListDocumentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDocumentsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_documents_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_documents), - '__call__') as call: - client.list_documents() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.ListDocumentsRequest() - -@pytest.mark.asyncio -async def test_list_documents_async(transport: str = 'grpc_asyncio', request_type=document_service.ListDocumentsRequest): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_documents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document_service.ListDocumentsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_documents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.ListDocumentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDocumentsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_documents_async_from_dict(): - await test_list_documents_async(request_type=dict) - - -def test_list_documents_field_headers(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.ListDocumentsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_documents), - '__call__') as call: - call.return_value = document_service.ListDocumentsResponse() - client.list_documents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_documents_field_headers_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.ListDocumentsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_documents), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_service.ListDocumentsResponse()) - await client.list_documents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_documents_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_documents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_service.ListDocumentsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_documents( - 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_documents_flattened_error(): - client = DocumentServiceClient( - credentials=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_documents( - document_service.ListDocumentsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_documents_flattened_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_documents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_service.ListDocumentsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_service.ListDocumentsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_documents( - 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_documents_flattened_error_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_documents( - document_service.ListDocumentsRequest(), - parent='parent_value', - ) - - -def test_list_documents_pager(transport_name: str = "grpc"): - client = DocumentServiceClient( - 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_documents), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - document.Document(), - ], - next_page_token='abc', - ), - document_service.ListDocumentsResponse( - documents=[], - next_page_token='def', - ), - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - ], - next_page_token='ghi', - ), - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_documents(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, document.Document) - for i in results) -def test_list_documents_pages(transport_name: str = "grpc"): - client = DocumentServiceClient( - 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_documents), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - document.Document(), - ], - next_page_token='abc', - ), - document_service.ListDocumentsResponse( - documents=[], - next_page_token='def', - ), - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - ], - next_page_token='ghi', - ), - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - ], - ), - RuntimeError, - ) - pages = list(client.list_documents(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_documents_async_pager(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_documents), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - document.Document(), - ], - next_page_token='abc', - ), - document_service.ListDocumentsResponse( - documents=[], - next_page_token='def', - ), - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - ], - next_page_token='ghi', - ), - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_documents(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, document.Document) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_documents_async_pages(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_documents), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - document.Document(), - ], - next_page_token='abc', - ), - document_service.ListDocumentsResponse( - documents=[], - next_page_token='def', - ), - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - ], - next_page_token='ghi', - ), - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_documents(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", [ - document_service.CreateDocumentRequest, - dict, -]) -def test_create_document(request_type, transport: str = 'grpc'): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_document.Document( - name='name_value', - id='id_value', - schema_id='schema_id_value', - parent_document_id='parent_document_id_value', - json_data='json_data_value', - ) - response = client.create_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.CreateDocumentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_document.Document) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.schema_id == 'schema_id_value' - assert response.parent_document_id == 'parent_document_id_value' - - -def test_create_document_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_document), - '__call__') as call: - client.create_document() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.CreateDocumentRequest() - -@pytest.mark.asyncio -async def test_create_document_async(transport: str = 'grpc_asyncio', request_type=document_service.CreateDocumentRequest): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_document.Document( - name='name_value', - id='id_value', - schema_id='schema_id_value', - parent_document_id='parent_document_id_value', - )) - response = await client.create_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.CreateDocumentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_document.Document) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.schema_id == 'schema_id_value' - assert response.parent_document_id == 'parent_document_id_value' - - -@pytest.mark.asyncio -async def test_create_document_async_from_dict(): - await test_create_document_async(request_type=dict) - - -def test_create_document_field_headers(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.CreateDocumentRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_document), - '__call__') as call: - call.return_value = gcd_document.Document() - client.create_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_document_field_headers_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.CreateDocumentRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_document), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_document.Document()) - await client.create_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_document_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_document.Document() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_document( - parent='parent_value', - document=gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), - document_id='document_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].document - mock_val = gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})) - assert arg == mock_val - arg = args[0].document_id - mock_val = 'document_id_value' - assert arg == mock_val - - -def test_create_document_flattened_error(): - client = DocumentServiceClient( - credentials=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_document( - document_service.CreateDocumentRequest(), - parent='parent_value', - document=gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), - document_id='document_id_value', - ) - -@pytest.mark.asyncio -async def test_create_document_flattened_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_document.Document() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_document.Document()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_document( - parent='parent_value', - document=gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), - document_id='document_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].document - mock_val = gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})) - assert arg == mock_val - arg = args[0].document_id - mock_val = 'document_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_document_flattened_error_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_document( - document_service.CreateDocumentRequest(), - parent='parent_value', - document=gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), - document_id='document_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_service.UpdateDocumentRequest, - dict, -]) -def test_update_document(request_type, transport: str = 'grpc'): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document.Document( - name='name_value', - id='id_value', - schema_id='schema_id_value', - parent_document_id='parent_document_id_value', - json_data='json_data_value', - ) - response = client.update_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.UpdateDocumentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, document.Document) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.schema_id == 'schema_id_value' - assert response.parent_document_id == 'parent_document_id_value' - - -def test_update_document_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_document), - '__call__') as call: - client.update_document() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.UpdateDocumentRequest() - -@pytest.mark.asyncio -async def test_update_document_async(transport: str = 'grpc_asyncio', request_type=document_service.UpdateDocumentRequest): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document.Document( - name='name_value', - id='id_value', - schema_id='schema_id_value', - parent_document_id='parent_document_id_value', - )) - response = await client.update_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.UpdateDocumentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, document.Document) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.schema_id == 'schema_id_value' - assert response.parent_document_id == 'parent_document_id_value' - - -@pytest.mark.asyncio -async def test_update_document_async_from_dict(): - await test_update_document_async(request_type=dict) - - -def test_update_document_field_headers(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.UpdateDocumentRequest() - - request.document.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_document), - '__call__') as call: - call.return_value = document.Document() - client.update_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'document.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_document_field_headers_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.UpdateDocumentRequest() - - request.document.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_document), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.Document()) - await client.update_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'document.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - document_service.DeleteDocumentRequest, - dict, -]) -def test_delete_document(request_type, transport: str = 'grpc'): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.DeleteDocumentRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_document_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_document), - '__call__') as call: - client.delete_document() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.DeleteDocumentRequest() - -@pytest.mark.asyncio -async def test_delete_document_async(transport: str = 'grpc_asyncio', request_type=document_service.DeleteDocumentRequest): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.DeleteDocumentRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_document_async_from_dict(): - await test_delete_document_async(request_type=dict) - - -def test_delete_document_field_headers(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.DeleteDocumentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_document), - '__call__') as call: - call.return_value = None - client.delete_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_document_field_headers_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.DeleteDocumentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_document), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_document_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_document), - '__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_document( - 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_document_flattened_error(): - client = DocumentServiceClient( - credentials=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_document( - document_service.DeleteDocumentRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_document_flattened_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_document), - '__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_document( - 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_document_flattened_error_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_document( - document_service.DeleteDocumentRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportDocumentsRequest, - dict, -]) -def test_import_documents(request_type, transport: str = 'grpc'): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_documents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_documents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportDocumentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_documents_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_documents), - '__call__') as call: - client.import_documents() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportDocumentsRequest() - -@pytest.mark.asyncio -async def test_import_documents_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportDocumentsRequest): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_documents), - '__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_documents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportDocumentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_documents_async_from_dict(): - await test_import_documents_async(request_type=dict) - - -def test_import_documents_field_headers(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportDocumentsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_documents), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_documents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_import_documents_field_headers_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportDocumentsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_documents), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_documents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - purge_config.PurgeDocumentsRequest, - dict, -]) -def test_purge_documents(request_type, transport: str = 'grpc'): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_documents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.purge_documents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeDocumentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_purge_documents_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_documents), - '__call__') as call: - client.purge_documents() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeDocumentsRequest() - -@pytest.mark.asyncio -async def test_purge_documents_async(transport: str = 'grpc_asyncio', request_type=purge_config.PurgeDocumentsRequest): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_documents), - '__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.purge_documents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeDocumentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_purge_documents_async_from_dict(): - await test_purge_documents_async(request_type=dict) - - -def test_purge_documents_field_headers(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = purge_config.PurgeDocumentsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_documents), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.purge_documents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_purge_documents_field_headers_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = purge_config.PurgeDocumentsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_documents), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.purge_documents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - document_service.GetDocumentRequest, - dict, -]) -def test_get_document_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document.Document( - name='name_value', - id='id_value', - schema_id='schema_id_value', - parent_document_id='parent_document_id_value', - json_data='json_data_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 = document.Document.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_document(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, document.Document) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.schema_id == 'schema_id_value' - assert response.parent_document_id == 'parent_document_id_value' - - -def test_get_document_rest_required_fields(request_type=document_service.GetDocumentRequest): - transport_class = transports.DocumentServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document.Document() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = document.Document.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_document(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_document_rest_unset_required_fields(): - transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_document._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_document_rest_interceptors(null_interceptor): - transport = transports.DocumentServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), - ) - client = DocumentServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "post_get_document") as post, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_get_document") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_service.GetDocumentRequest.pb(document_service.GetDocumentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document.Document.to_json(document.Document()) - - request = document_service.GetDocumentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document.Document() - - client.get_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_document_rest_bad_request(transport: str = 'rest', request_type=document_service.GetDocumentRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_document(request) - - -def test_get_document_rest_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document.Document() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = document.Document.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_document(**mock_args) - - # Establish that the underlying call 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/*/dataStores/*/branches/*/documents/*}" % client.transport._host, args[1]) - - -def test_get_document_rest_flattened_error(transport: str = 'rest'): - client = DocumentServiceClient( - credentials=ga_credentials.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_document( - document_service.GetDocumentRequest(), - name='name_value', - ) - - -def test_get_document_rest_error(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_service.ListDocumentsRequest, - dict, -]) -def test_list_documents_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/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 = document_service.ListDocumentsResponse( - next_page_token='next_page_token_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 = document_service.ListDocumentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_documents(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDocumentsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_documents_rest_required_fields(request_type=document_service.ListDocumentsRequest): - transport_class = transports.DocumentServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_documents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_documents._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document_service.ListDocumentsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = document_service.ListDocumentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_documents(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_documents_rest_unset_required_fields(): - transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_documents._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_documents_rest_interceptors(null_interceptor): - transport = transports.DocumentServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), - ) - client = DocumentServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "post_list_documents") as post, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_list_documents") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_service.ListDocumentsRequest.pb(document_service.ListDocumentsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document_service.ListDocumentsResponse.to_json(document_service.ListDocumentsResponse()) - - request = document_service.ListDocumentsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document_service.ListDocumentsResponse() - - client.list_documents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_documents_rest_bad_request(transport: str = 'rest', request_type=document_service.ListDocumentsRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_documents(request) - - -def test_list_documents_rest_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_service.ListDocumentsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = document_service.ListDocumentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_documents(**mock_args) - - # Establish that the underlying call 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/*/dataStores/*/branches/*}/documents" % client.transport._host, args[1]) - - -def test_list_documents_rest_flattened_error(transport: str = 'rest'): - client = DocumentServiceClient( - credentials=ga_credentials.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_documents( - document_service.ListDocumentsRequest(), - parent='parent_value', - ) - - -def test_list_documents_rest_pager(transport: str = 'rest'): - client = DocumentServiceClient( - 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 = ( - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - document.Document(), - ], - next_page_token='abc', - ), - document_service.ListDocumentsResponse( - documents=[], - next_page_token='def', - ), - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - ], - next_page_token='ghi', - ), - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(document_service.ListDocumentsResponse.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/dataStores/sample3/branches/sample4'} - - pager = client.list_documents(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, document.Document) - for i in results) - - pages = list(client.list_documents(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - document_service.CreateDocumentRequest, - dict, -]) -def test_create_document_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} - request_init["document"] = {'struct_data': {'fields': {}}, 'json_data': 'json_data_value', 'name': 'name_value', 'id': 'id_value', 'schema_id': 'schema_id_value', 'content': {'raw_bytes': b'raw_bytes_blob', 'uri': 'uri_value', 'mime_type': 'mime_type_value'}, 'parent_document_id': 'parent_document_id_value', 'derived_struct_data': {}} - # 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 = document_service.CreateDocumentRequest.meta.fields["document"] - - 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["document"].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["document"][field])): - del request_init["document"][field][i][subfield] - else: - del request_init["document"][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 = gcd_document.Document( - name='name_value', - id='id_value', - schema_id='schema_id_value', - parent_document_id='parent_document_id_value', - json_data='json_data_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 = gcd_document.Document.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_document(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_document.Document) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.schema_id == 'schema_id_value' - assert response.parent_document_id == 'parent_document_id_value' - - -def test_create_document_rest_required_fields(request_type=document_service.CreateDocumentRequest): - transport_class = transports.DocumentServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["document_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "documentId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "documentId" in jsonified_request - assert jsonified_request["documentId"] == request_init["document_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["documentId"] = 'document_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_document._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("document_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "documentId" in jsonified_request - assert jsonified_request["documentId"] == 'document_id_value' - - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_document.Document() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcd_document.Document.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_document(request) - - expected_params = [ - ( - "documentId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_document_rest_unset_required_fields(): - transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_document._get_unset_required_fields({}) - assert set(unset_fields) == (set(("documentId", )) & set(("parent", "document", "documentId", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_document_rest_interceptors(null_interceptor): - transport = transports.DocumentServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), - ) - client = DocumentServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "post_create_document") as post, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_create_document") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_service.CreateDocumentRequest.pb(document_service.CreateDocumentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_document.Document.to_json(gcd_document.Document()) - - request = document_service.CreateDocumentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_document.Document() - - client.create_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_document_rest_bad_request(transport: str = 'rest', request_type=document_service.CreateDocumentRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_document(request) - - -def test_create_document_rest_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_document.Document() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - document=gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), - document_id='document_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 = gcd_document.Document.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_document(**mock_args) - - # Establish that the underlying call 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/*/dataStores/*/branches/*}/documents" % client.transport._host, args[1]) - - -def test_create_document_rest_flattened_error(transport: str = 'rest'): - client = DocumentServiceClient( - credentials=ga_credentials.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_document( - document_service.CreateDocumentRequest(), - parent='parent_value', - document=gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), - document_id='document_id_value', - ) - - -def test_create_document_rest_error(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_service.UpdateDocumentRequest, - dict, -]) -def test_update_document_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'document': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'}} - request_init["document"] = {'struct_data': {'fields': {}}, 'json_data': 'json_data_value', 'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5', 'id': 'id_value', 'schema_id': 'schema_id_value', 'content': {'raw_bytes': b'raw_bytes_blob', 'uri': 'uri_value', 'mime_type': 'mime_type_value'}, 'parent_document_id': 'parent_document_id_value', 'derived_struct_data': {}} - # 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 = document_service.UpdateDocumentRequest.meta.fields["document"] - - 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["document"].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["document"][field])): - del request_init["document"][field][i][subfield] - else: - del request_init["document"][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 = document.Document( - name='name_value', - id='id_value', - schema_id='schema_id_value', - parent_document_id='parent_document_id_value', - json_data='json_data_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 = document.Document.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_document(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, document.Document) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.schema_id == 'schema_id_value' - assert response.parent_document_id == 'parent_document_id_value' - - -def test_update_document_rest_required_fields(request_type=document_service.UpdateDocumentRequest): - transport_class = transports.DocumentServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_document._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_missing", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document.Document() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = document.Document.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_document(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_document_rest_unset_required_fields(): - transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_document._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowMissing", )) & set(("document", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_document_rest_interceptors(null_interceptor): - transport = transports.DocumentServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), - ) - client = DocumentServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "post_update_document") as post, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_update_document") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_service.UpdateDocumentRequest.pb(document_service.UpdateDocumentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document.Document.to_json(document.Document()) - - request = document_service.UpdateDocumentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document.Document() - - client.update_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_document_rest_bad_request(transport: str = 'rest', request_type=document_service.UpdateDocumentRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'document': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_document(request) - - -def test_update_document_rest_error(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_service.DeleteDocumentRequest, - dict, -]) -def test_delete_document_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_document(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_document_rest_required_fields(request_type=document_service.DeleteDocumentRequest): - transport_class = transports.DocumentServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentServiceClient( - 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 - - response = client.delete_document(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_document_rest_unset_required_fields(): - transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_document._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_document_rest_interceptors(null_interceptor): - transport = transports.DocumentServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), - ) - client = DocumentServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_delete_document") as pre: - pre.assert_not_called() - pb_message = document_service.DeleteDocumentRequest.pb(document_service.DeleteDocumentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = document_service.DeleteDocumentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_document_rest_bad_request(transport: str = 'rest', request_type=document_service.DeleteDocumentRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_document(request) - - -def test_delete_document_rest_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_document(**mock_args) - - # Establish that the underlying call 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/*/dataStores/*/branches/*/documents/*}" % client.transport._host, args[1]) - - -def test_delete_document_rest_flattened_error(transport: str = 'rest'): - client = DocumentServiceClient( - credentials=ga_credentials.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_document( - document_service.DeleteDocumentRequest(), - name='name_value', - ) - - -def test_delete_document_rest_error(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportDocumentsRequest, - dict, -]) -def test_import_documents_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.import_documents(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_import_documents_rest_required_fields(request_type=import_config.ImportDocumentsRequest): - transport_class = transports.DocumentServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_documents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_documents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.import_documents(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_import_documents_rest_unset_required_fields(): - transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.import_documents._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_import_documents_rest_interceptors(null_interceptor): - transport = transports.DocumentServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), - ) - client = DocumentServiceClient(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.DocumentServiceRestInterceptor, "post_import_documents") as post, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_import_documents") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = import_config.ImportDocumentsRequest.pb(import_config.ImportDocumentsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = import_config.ImportDocumentsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.import_documents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_import_documents_rest_bad_request(transport: str = 'rest', request_type=import_config.ImportDocumentsRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.import_documents(request) - - -def test_import_documents_rest_error(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - purge_config.PurgeDocumentsRequest, - dict, -]) -def test_purge_documents_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.purge_documents(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_purge_documents_rest_required_fields(request_type=purge_config.PurgeDocumentsRequest): - transport_class = transports.DocumentServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["filter"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).purge_documents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - jsonified_request["filter"] = 'filter_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).purge_documents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "filter" in jsonified_request - assert jsonified_request["filter"] == 'filter_value' - - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.purge_documents(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_purge_documents_rest_unset_required_fields(): - transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.purge_documents._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "filter", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_purge_documents_rest_interceptors(null_interceptor): - transport = transports.DocumentServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), - ) - client = DocumentServiceClient(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.DocumentServiceRestInterceptor, "post_purge_documents") as post, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_purge_documents") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = purge_config.PurgeDocumentsRequest.pb(purge_config.PurgeDocumentsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = purge_config.PurgeDocumentsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.purge_documents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_purge_documents_rest_bad_request(transport: str = 'rest', request_type=purge_config.PurgeDocumentsRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.purge_documents(request) - - -def test_purge_documents_rest_error(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.DocumentServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.DocumentServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DocumentServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.DocumentServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = DocumentServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = DocumentServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.DocumentServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DocumentServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.DocumentServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = DocumentServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.DocumentServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.DocumentServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.DocumentServiceGrpcTransport, - transports.DocumentServiceGrpcAsyncIOTransport, - transports.DocumentServiceRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = DocumentServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.DocumentServiceGrpcTransport, - ) - -def test_document_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.DocumentServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_document_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.discoveryengine_v1alpha.services.document_service.transports.DocumentServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.DocumentServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_document', - 'list_documents', - 'create_document', - 'update_document', - 'delete_document', - 'import_documents', - 'purge_documents', - 'get_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_document_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.discoveryengine_v1alpha.services.document_service.transports.DocumentServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DocumentServiceTransport( - 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_document_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.discoveryengine_v1alpha.services.document_service.transports.DocumentServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DocumentServiceTransport() - adc.assert_called_once() - - -def test_document_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) - DocumentServiceClient() - 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.DocumentServiceGrpcTransport, - transports.DocumentServiceGrpcAsyncIOTransport, - ], -) -def test_document_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.DocumentServiceGrpcTransport, - transports.DocumentServiceGrpcAsyncIOTransport, - transports.DocumentServiceRestTransport, - ], -) -def test_document_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.DocumentServiceGrpcTransport, grpc_helpers), - (transports.DocumentServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_document_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.DocumentServiceGrpcTransport, transports.DocumentServiceGrpcAsyncIOTransport]) -def test_document_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_document_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.DocumentServiceRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_document_service_rest_lro_client(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_document_service_host_no_port(transport_name): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_document_service_host_with_port(transport_name): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_document_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = DocumentServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = DocumentServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_document._session - session2 = client2.transport.get_document._session - assert session1 != session2 - session1 = client1.transport.list_documents._session - session2 = client2.transport.list_documents._session - assert session1 != session2 - session1 = client1.transport.create_document._session - session2 = client2.transport.create_document._session - assert session1 != session2 - session1 = client1.transport.update_document._session - session2 = client2.transport.update_document._session - assert session1 != session2 - session1 = client1.transport.delete_document._session - session2 = client2.transport.delete_document._session - assert session1 != session2 - session1 = client1.transport.import_documents._session - session2 = client2.transport.import_documents._session - assert session1 != session2 - session1 = client1.transport.purge_documents._session - session2 = client2.transport.purge_documents._session - assert session1 != session2 -def test_document_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DocumentServiceGrpcTransport( - 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_document_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DocumentServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.DocumentServiceGrpcTransport, transports.DocumentServiceGrpcAsyncIOTransport]) -def test_document_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.DocumentServiceGrpcTransport, transports.DocumentServiceGrpcAsyncIOTransport]) -def test_document_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_document_service_grpc_lro_client(): - client = DocumentServiceClient( - 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_document_service_grpc_lro_async_client(): - client = DocumentServiceAsyncClient( - 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_branch_path(): - project = "squid" - location = "clam" - data_store = "whelk" - branch = "octopus" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}".format(project=project, location=location, data_store=data_store, branch=branch, ) - actual = DocumentServiceClient.branch_path(project, location, data_store, branch) - assert expected == actual - - -def test_parse_branch_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "data_store": "cuttlefish", - "branch": "mussel", - } - path = DocumentServiceClient.branch_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentServiceClient.parse_branch_path(path) - assert expected == actual - -def test_document_path(): - project = "winkle" - location = "nautilus" - data_store = "scallop" - branch = "abalone" - document = "squid" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) - actual = DocumentServiceClient.document_path(project, location, data_store, branch, document) - assert expected == actual - - -def test_parse_document_path(): - expected = { - "project": "clam", - "location": "whelk", - "data_store": "octopus", - "branch": "oyster", - "document": "nudibranch", - } - path = DocumentServiceClient.document_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentServiceClient.parse_document_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = DocumentServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = DocumentServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = DocumentServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = DocumentServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = DocumentServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = DocumentServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = DocumentServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = DocumentServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = DocumentServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = DocumentServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentServiceClient.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.DocumentServiceTransport, '_prep_wrapped_messages') as prep: - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.DocumentServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = DocumentServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_get_operation(transport: str = "grpc"): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = DocumentServiceClient( - 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 = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = DocumentServiceClient( - 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 = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = DocumentServiceClient( - 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", [ - (DocumentServiceClient, transports.DocumentServiceGrpcTransport), - (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_recommendation_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_recommendation_service.py deleted file mode 100644 index 1919c3b20e9c..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_recommendation_service.py +++ /dev/null @@ -1,1952 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.discoveryengine_v1alpha.services.recommendation_service import RecommendationServiceAsyncClient -from google.cloud.discoveryengine_v1alpha.services.recommendation_service import RecommendationServiceClient -from google.cloud.discoveryengine_v1alpha.services.recommendation_service import transports -from google.cloud.discoveryengine_v1alpha.types import common -from google.cloud.discoveryengine_v1alpha.types import recommendation_service -from google.cloud.discoveryengine_v1alpha.types import user_event -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert RecommendationServiceClient._get_default_mtls_endpoint(None) is None - assert RecommendationServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert RecommendationServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert RecommendationServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert RecommendationServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert RecommendationServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (RecommendationServiceClient, "grpc"), - (RecommendationServiceAsyncClient, "grpc_asyncio"), - (RecommendationServiceClient, "rest"), -]) -def test_recommendation_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.RecommendationServiceGrpcTransport, "grpc"), - (transports.RecommendationServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.RecommendationServiceRestTransport, "rest"), -]) -def test_recommendation_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", [ - (RecommendationServiceClient, "grpc"), - (RecommendationServiceAsyncClient, "grpc_asyncio"), - (RecommendationServiceClient, "rest"), -]) -def test_recommendation_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -def test_recommendation_service_client_get_transport_class(): - transport = RecommendationServiceClient.get_transport_class() - available_transports = [ - transports.RecommendationServiceGrpcTransport, - transports.RecommendationServiceRestTransport, - ] - assert transport in available_transports - - transport = RecommendationServiceClient.get_transport_class("grpc") - assert transport == transports.RecommendationServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (RecommendationServiceClient, transports.RecommendationServiceGrpcTransport, "grpc"), - (RecommendationServiceAsyncClient, transports.RecommendationServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (RecommendationServiceClient, transports.RecommendationServiceRestTransport, "rest"), -]) -@mock.patch.object(RecommendationServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RecommendationServiceClient)) -@mock.patch.object(RecommendationServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RecommendationServiceAsyncClient)) -def test_recommendation_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(RecommendationServiceClient, '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(RecommendationServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (RecommendationServiceClient, transports.RecommendationServiceGrpcTransport, "grpc", "true"), - (RecommendationServiceAsyncClient, transports.RecommendationServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (RecommendationServiceClient, transports.RecommendationServiceGrpcTransport, "grpc", "false"), - (RecommendationServiceAsyncClient, transports.RecommendationServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (RecommendationServiceClient, transports.RecommendationServiceRestTransport, "rest", "true"), - (RecommendationServiceClient, transports.RecommendationServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(RecommendationServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RecommendationServiceClient)) -@mock.patch.object(RecommendationServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RecommendationServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_recommendation_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 - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - RecommendationServiceClient, RecommendationServiceAsyncClient -]) -@mock.patch.object(RecommendationServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RecommendationServiceClient)) -@mock.patch.object(RecommendationServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RecommendationServiceAsyncClient)) -def test_recommendation_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (RecommendationServiceClient, transports.RecommendationServiceGrpcTransport, "grpc"), - (RecommendationServiceAsyncClient, transports.RecommendationServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (RecommendationServiceClient, transports.RecommendationServiceRestTransport, "rest"), -]) -def test_recommendation_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, - 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", [ - (RecommendationServiceClient, transports.RecommendationServiceGrpcTransport, "grpc", grpc_helpers), - (RecommendationServiceAsyncClient, transports.RecommendationServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (RecommendationServiceClient, transports.RecommendationServiceRestTransport, "rest", None), -]) -def test_recommendation_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, - scopes=None, - client_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_recommendation_service_client_client_options_from_dict(): - with mock.patch('google.cloud.discoveryengine_v1alpha.services.recommendation_service.transports.RecommendationServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = RecommendationServiceClient( - 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", [ - (RecommendationServiceClient, transports.RecommendationServiceGrpcTransport, "grpc", grpc_helpers), - (RecommendationServiceAsyncClient, transports.RecommendationServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_recommendation_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, - scopes=None, - client_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - recommendation_service.RecommendRequest, - dict, -]) -def test_recommend(request_type, transport: str = 'grpc'): - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.recommend), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = recommendation_service.RecommendResponse( - attribution_token='attribution_token_value', - missing_ids=['missing_ids_value'], - validate_only=True, - ) - response = client.recommend(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == recommendation_service.RecommendRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, recommendation_service.RecommendResponse) - assert response.attribution_token == 'attribution_token_value' - assert response.missing_ids == ['missing_ids_value'] - assert response.validate_only is True - - -def test_recommend_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.recommend), - '__call__') as call: - client.recommend() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommendation_service.RecommendRequest() - -@pytest.mark.asyncio -async def test_recommend_async(transport: str = 'grpc_asyncio', request_type=recommendation_service.RecommendRequest): - client = RecommendationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.recommend), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(recommendation_service.RecommendResponse( - attribution_token='attribution_token_value', - missing_ids=['missing_ids_value'], - validate_only=True, - )) - response = await client.recommend(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == recommendation_service.RecommendRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, recommendation_service.RecommendResponse) - assert response.attribution_token == 'attribution_token_value' - assert response.missing_ids == ['missing_ids_value'] - assert response.validate_only is True - - -@pytest.mark.asyncio -async def test_recommend_async_from_dict(): - await test_recommend_async(request_type=dict) - - -def test_recommend_field_headers(): - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = recommendation_service.RecommendRequest() - - request.serving_config = 'serving_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.recommend), - '__call__') as call: - call.return_value = recommendation_service.RecommendResponse() - client.recommend(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config=serving_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_recommend_field_headers_async(): - client = RecommendationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = recommendation_service.RecommendRequest() - - request.serving_config = 'serving_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.recommend), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(recommendation_service.RecommendResponse()) - await client.recommend(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config=serving_config_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - recommendation_service.RecommendRequest, - dict, -]) -def test_recommend_rest(request_type): - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'serving_config': 'projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/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 = recommendation_service.RecommendResponse( - attribution_token='attribution_token_value', - missing_ids=['missing_ids_value'], - validate_only=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = recommendation_service.RecommendResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.recommend(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, recommendation_service.RecommendResponse) - assert response.attribution_token == 'attribution_token_value' - assert response.missing_ids == ['missing_ids_value'] - assert response.validate_only is True - - -def test_recommend_rest_required_fields(request_type=recommendation_service.RecommendRequest): - transport_class = transports.RecommendationServiceRestTransport - - request_init = {} - request_init["serving_config"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).recommend._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["servingConfig"] = 'serving_config_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).recommend._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "servingConfig" in jsonified_request - assert jsonified_request["servingConfig"] == 'serving_config_value' - - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = recommendation_service.RecommendResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = recommendation_service.RecommendResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.recommend(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_recommend_rest_unset_required_fields(): - transport = transports.RecommendationServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.recommend._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("servingConfig", "userEvent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_recommend_rest_interceptors(null_interceptor): - transport = transports.RecommendationServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RecommendationServiceRestInterceptor(), - ) - client = RecommendationServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RecommendationServiceRestInterceptor, "post_recommend") as post, \ - mock.patch.object(transports.RecommendationServiceRestInterceptor, "pre_recommend") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = recommendation_service.RecommendRequest.pb(recommendation_service.RecommendRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = recommendation_service.RecommendResponse.to_json(recommendation_service.RecommendResponse()) - - request = recommendation_service.RecommendRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = recommendation_service.RecommendResponse() - - client.recommend(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_recommend_rest_bad_request(transport: str = 'rest', request_type=recommendation_service.RecommendRequest): - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'serving_config': 'projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.recommend(request) - - -def test_recommend_rest_error(): - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.RecommendationServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.RecommendationServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RecommendationServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.RecommendationServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = RecommendationServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = RecommendationServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.RecommendationServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RecommendationServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.RecommendationServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = RecommendationServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.RecommendationServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.RecommendationServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.RecommendationServiceGrpcTransport, - transports.RecommendationServiceGrpcAsyncIOTransport, - transports.RecommendationServiceRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = RecommendationServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.RecommendationServiceGrpcTransport, - ) - -def test_recommendation_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.RecommendationServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_recommendation_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.discoveryengine_v1alpha.services.recommendation_service.transports.RecommendationServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.RecommendationServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'recommend', - 'get_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_recommendation_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.discoveryengine_v1alpha.services.recommendation_service.transports.RecommendationServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RecommendationServiceTransport( - 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_recommendation_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.discoveryengine_v1alpha.services.recommendation_service.transports.RecommendationServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RecommendationServiceTransport() - adc.assert_called_once() - - -def test_recommendation_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) - RecommendationServiceClient() - 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.RecommendationServiceGrpcTransport, - transports.RecommendationServiceGrpcAsyncIOTransport, - ], -) -def test_recommendation_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.RecommendationServiceGrpcTransport, - transports.RecommendationServiceGrpcAsyncIOTransport, - transports.RecommendationServiceRestTransport, - ], -) -def test_recommendation_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.RecommendationServiceGrpcTransport, grpc_helpers), - (transports.RecommendationServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_recommendation_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.RecommendationServiceGrpcTransport, transports.RecommendationServiceGrpcAsyncIOTransport]) -def test_recommendation_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_recommendation_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.RecommendationServiceRestTransport ( - 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_recommendation_service_host_no_port(transport_name): - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_recommendation_service_host_with_port(transport_name): - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_recommendation_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = RecommendationServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = RecommendationServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.recommend._session - session2 = client2.transport.recommend._session - assert session1 != session2 -def test_recommendation_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.RecommendationServiceGrpcTransport( - 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_recommendation_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.RecommendationServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.RecommendationServiceGrpcTransport, transports.RecommendationServiceGrpcAsyncIOTransport]) -def test_recommendation_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.RecommendationServiceGrpcTransport, transports.RecommendationServiceGrpcAsyncIOTransport]) -def test_recommendation_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_document_path(): - project = "squid" - location = "clam" - data_store = "whelk" - branch = "octopus" - document = "oyster" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) - actual = RecommendationServiceClient.document_path(project, location, data_store, branch, document) - assert expected == actual - - -def test_parse_document_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "data_store": "mussel", - "branch": "winkle", - "document": "nautilus", - } - path = RecommendationServiceClient.document_path(**expected) - - # Check that the path construction is reversible. - actual = RecommendationServiceClient.parse_document_path(path) - assert expected == actual - -def test_serving_config_path(): - project = "scallop" - location = "abalone" - data_store = "squid" - serving_config = "clam" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}/servingConfigs/{serving_config}".format(project=project, location=location, data_store=data_store, serving_config=serving_config, ) - actual = RecommendationServiceClient.serving_config_path(project, location, data_store, serving_config) - assert expected == actual - - -def test_parse_serving_config_path(): - expected = { - "project": "whelk", - "location": "octopus", - "data_store": "oyster", - "serving_config": "nudibranch", - } - path = RecommendationServiceClient.serving_config_path(**expected) - - # Check that the path construction is reversible. - actual = RecommendationServiceClient.parse_serving_config_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = RecommendationServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = RecommendationServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = RecommendationServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = RecommendationServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = RecommendationServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = RecommendationServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = RecommendationServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = RecommendationServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = RecommendationServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = RecommendationServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = RecommendationServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = RecommendationServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = RecommendationServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = RecommendationServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = RecommendationServiceClient.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.RecommendationServiceTransport, '_prep_wrapped_messages') as prep: - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.RecommendationServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = RecommendationServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = RecommendationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_get_operation(transport: str = "grpc"): - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = RecommendationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = RecommendationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = RecommendationServiceClient( - 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 = RecommendationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = RecommendationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = RecommendationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = RecommendationServiceClient( - 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 = RecommendationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = RecommendationServiceClient( - 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", [ - (RecommendationServiceClient, transports.RecommendationServiceGrpcTransport), - (RecommendationServiceAsyncClient, transports.RecommendationServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_schema_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_schema_service.py deleted file mode 100644 index 110f7d7236f5..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_schema_service.py +++ /dev/null @@ -1,4265 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.discoveryengine_v1alpha.services.schema_service import SchemaServiceAsyncClient -from google.cloud.discoveryengine_v1alpha.services.schema_service import SchemaServiceClient -from google.cloud.discoveryengine_v1alpha.services.schema_service import pagers -from google.cloud.discoveryengine_v1alpha.services.schema_service import transports -from google.cloud.discoveryengine_v1alpha.types import schema -from google.cloud.discoveryengine_v1alpha.types import schema as gcd_schema -from google.cloud.discoveryengine_v1alpha.types import schema_service -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert SchemaServiceClient._get_default_mtls_endpoint(None) is None - assert SchemaServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SchemaServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SchemaServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SchemaServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SchemaServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (SchemaServiceClient, "grpc"), - (SchemaServiceAsyncClient, "grpc_asyncio"), - (SchemaServiceClient, "rest"), -]) -def test_schema_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.SchemaServiceGrpcTransport, "grpc"), - (transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.SchemaServiceRestTransport, "rest"), -]) -def test_schema_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", [ - (SchemaServiceClient, "grpc"), - (SchemaServiceAsyncClient, "grpc_asyncio"), - (SchemaServiceClient, "rest"), -]) -def test_schema_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -def test_schema_service_client_get_transport_class(): - transport = SchemaServiceClient.get_transport_class() - available_transports = [ - transports.SchemaServiceGrpcTransport, - transports.SchemaServiceRestTransport, - ] - assert transport in available_transports - - transport = SchemaServiceClient.get_transport_class("grpc") - assert transport == transports.SchemaServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc"), - (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (SchemaServiceClient, transports.SchemaServiceRestTransport, "rest"), -]) -@mock.patch.object(SchemaServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceClient)) -@mock.patch.object(SchemaServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceAsyncClient)) -def test_schema_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(SchemaServiceClient, '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(SchemaServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc", "true"), - (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc", "false"), - (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (SchemaServiceClient, transports.SchemaServiceRestTransport, "rest", "true"), - (SchemaServiceClient, transports.SchemaServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(SchemaServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceClient)) -@mock.patch.object(SchemaServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_schema_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 - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - SchemaServiceClient, SchemaServiceAsyncClient -]) -@mock.patch.object(SchemaServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceClient)) -@mock.patch.object(SchemaServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceAsyncClient)) -def test_schema_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc"), - (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (SchemaServiceClient, transports.SchemaServiceRestTransport, "rest"), -]) -def test_schema_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, - 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", [ - (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc", grpc_helpers), - (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (SchemaServiceClient, transports.SchemaServiceRestTransport, "rest", None), -]) -def test_schema_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, - scopes=None, - client_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_schema_service_client_client_options_from_dict(): - with mock.patch('google.cloud.discoveryengine_v1alpha.services.schema_service.transports.SchemaServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SchemaServiceClient( - 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", [ - (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc", grpc_helpers), - (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_schema_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, - scopes=None, - client_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - schema_service.GetSchemaRequest, - dict, -]) -def test_get_schema(request_type, transport: str = 'grpc'): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema.Schema( - name='name_value', - json_schema='json_schema_value', - ) - response = client.get_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.GetSchemaRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, schema.Schema) - assert response.name == 'name_value' - - -def test_get_schema_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_schema), - '__call__') as call: - client.get_schema() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.GetSchemaRequest() - -@pytest.mark.asyncio -async def test_get_schema_async(transport: str = 'grpc_asyncio', request_type=schema_service.GetSchemaRequest): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(schema.Schema( - name='name_value', - )) - response = await client.get_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.GetSchemaRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, schema.Schema) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_schema_async_from_dict(): - await test_get_schema_async(request_type=dict) - - -def test_get_schema_field_headers(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema_service.GetSchemaRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_schema), - '__call__') as call: - call.return_value = schema.Schema() - client.get_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_schema_field_headers_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema_service.GetSchemaRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_schema), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.Schema()) - await client.get_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_schema_flattened(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema.Schema() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_schema( - 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_schema_flattened_error(): - client = SchemaServiceClient( - credentials=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_schema( - schema_service.GetSchemaRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_schema_flattened_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema.Schema() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.Schema()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_schema( - 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_schema_flattened_error_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_schema( - schema_service.GetSchemaRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - schema_service.ListSchemasRequest, - dict, -]) -def test_list_schemas(request_type, transport: str = 'grpc'): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_schemas), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema_service.ListSchemasResponse( - next_page_token='next_page_token_value', - ) - response = client.list_schemas(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.ListSchemasRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSchemasPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_schemas_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__') as call: - client.list_schemas() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.ListSchemasRequest() - -@pytest.mark.asyncio -async def test_list_schemas_async(transport: str = 'grpc_asyncio', request_type=schema_service.ListSchemasRequest): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_schemas), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(schema_service.ListSchemasResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_schemas(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.ListSchemasRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSchemasAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_schemas_async_from_dict(): - await test_list_schemas_async(request_type=dict) - - -def test_list_schemas_field_headers(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema_service.ListSchemasRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__') as call: - call.return_value = schema_service.ListSchemasResponse() - client.list_schemas(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_schemas_field_headers_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema_service.ListSchemasRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema_service.ListSchemasResponse()) - await client.list_schemas(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_schemas_flattened(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema_service.ListSchemasResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_schemas( - 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_schemas_flattened_error(): - client = SchemaServiceClient( - credentials=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_schemas( - schema_service.ListSchemasRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_schemas_flattened_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema_service.ListSchemasResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema_service.ListSchemasResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_schemas( - 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_schemas_flattened_error_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_schemas( - schema_service.ListSchemasRequest(), - parent='parent_value', - ) - - -def test_list_schemas_pager(transport_name: str = "grpc"): - client = SchemaServiceClient( - 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_schemas), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - schema.Schema(), - ], - next_page_token='abc', - ), - schema_service.ListSchemasResponse( - schemas=[], - next_page_token='def', - ), - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - ], - next_page_token='ghi', - ), - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_schemas(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, schema.Schema) - for i in results) -def test_list_schemas_pages(transport_name: str = "grpc"): - client = SchemaServiceClient( - 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_schemas), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - schema.Schema(), - ], - next_page_token='abc', - ), - schema_service.ListSchemasResponse( - schemas=[], - next_page_token='def', - ), - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - ], - next_page_token='ghi', - ), - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - ], - ), - RuntimeError, - ) - pages = list(client.list_schemas(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_schemas_async_pager(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - schema.Schema(), - ], - next_page_token='abc', - ), - schema_service.ListSchemasResponse( - schemas=[], - next_page_token='def', - ), - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - ], - next_page_token='ghi', - ), - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_schemas(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, schema.Schema) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_schemas_async_pages(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - schema.Schema(), - ], - next_page_token='abc', - ), - schema_service.ListSchemasResponse( - schemas=[], - next_page_token='def', - ), - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - ], - next_page_token='ghi', - ), - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_schemas(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", [ - schema_service.CreateSchemaRequest, - dict, -]) -def test_create_schema(request_type, transport: str = 'grpc'): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.CreateSchemaRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_schema_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_schema), - '__call__') as call: - client.create_schema() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.CreateSchemaRequest() - -@pytest.mark.asyncio -async def test_create_schema_async(transport: str = 'grpc_asyncio', request_type=schema_service.CreateSchemaRequest): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_schema), - '__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_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.CreateSchemaRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_schema_async_from_dict(): - await test_create_schema_async(request_type=dict) - - -def test_create_schema_field_headers(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema_service.CreateSchemaRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_schema), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_schema_field_headers_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema_service.CreateSchemaRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_schema), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_schema_flattened(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_schema), - '__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_schema( - parent='parent_value', - schema=gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), - schema_id='schema_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].schema - mock_val = gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})) - assert arg == mock_val - arg = args[0].schema_id - mock_val = 'schema_id_value' - assert arg == mock_val - - -def test_create_schema_flattened_error(): - client = SchemaServiceClient( - credentials=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_schema( - schema_service.CreateSchemaRequest(), - parent='parent_value', - schema=gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), - schema_id='schema_id_value', - ) - -@pytest.mark.asyncio -async def test_create_schema_flattened_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_schema), - '__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_schema( - parent='parent_value', - schema=gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), - schema_id='schema_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].schema - mock_val = gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})) - assert arg == mock_val - arg = args[0].schema_id - mock_val = 'schema_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_schema_flattened_error_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_schema( - schema_service.CreateSchemaRequest(), - parent='parent_value', - schema=gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), - schema_id='schema_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - schema_service.UpdateSchemaRequest, - dict, -]) -def test_update_schema(request_type, transport: str = 'grpc'): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.UpdateSchemaRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_schema_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_schema), - '__call__') as call: - client.update_schema() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.UpdateSchemaRequest() - -@pytest.mark.asyncio -async def test_update_schema_async(transport: str = 'grpc_asyncio', request_type=schema_service.UpdateSchemaRequest): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_schema), - '__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_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.UpdateSchemaRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_schema_async_from_dict(): - await test_update_schema_async(request_type=dict) - - -def test_update_schema_field_headers(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema_service.UpdateSchemaRequest() - - request.schema.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_schema), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'schema.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_schema_field_headers_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema_service.UpdateSchemaRequest() - - request.schema.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_schema), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'schema.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - schema_service.DeleteSchemaRequest, - dict, -]) -def test_delete_schema(request_type, transport: str = 'grpc'): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.DeleteSchemaRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_schema_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_schema), - '__call__') as call: - client.delete_schema() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.DeleteSchemaRequest() - -@pytest.mark.asyncio -async def test_delete_schema_async(transport: str = 'grpc_asyncio', request_type=schema_service.DeleteSchemaRequest): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_schema), - '__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_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.DeleteSchemaRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_schema_async_from_dict(): - await test_delete_schema_async(request_type=dict) - - -def test_delete_schema_field_headers(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema_service.DeleteSchemaRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_schema), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_schema_field_headers_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema_service.DeleteSchemaRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_schema), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_schema_flattened(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_schema), - '__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_schema( - 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_schema_flattened_error(): - client = SchemaServiceClient( - credentials=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_schema( - schema_service.DeleteSchemaRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_schema_flattened_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_schema), - '__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_schema( - 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_schema_flattened_error_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_schema( - schema_service.DeleteSchemaRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - schema_service.GetSchemaRequest, - dict, -]) -def test_get_schema_rest(request_type): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/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 = schema.Schema( - name='name_value', - json_schema='json_schema_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 = schema.Schema.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_schema(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, schema.Schema) - assert response.name == 'name_value' - - -def test_get_schema_rest_required_fields(request_type=schema_service.GetSchemaRequest): - transport_class = transports.SchemaServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_schema._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_schema._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = schema.Schema() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = schema.Schema.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_schema(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_schema_rest_unset_required_fields(): - transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_schema._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_schema_rest_interceptors(null_interceptor): - transport = transports.SchemaServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), - ) - client = SchemaServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SchemaServiceRestInterceptor, "post_get_schema") as post, \ - mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_get_schema") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = schema_service.GetSchemaRequest.pb(schema_service.GetSchemaRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = schema.Schema.to_json(schema.Schema()) - - request = schema_service.GetSchemaRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = schema.Schema() - - client.get_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_schema_rest_bad_request(transport: str = 'rest', request_type=schema_service.GetSchemaRequest): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_schema(request) - - -def test_get_schema_rest_flattened(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = schema.Schema() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/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 = schema.Schema.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_schema(**mock_args) - - # Establish that the underlying call 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/*/dataStores/*/schemas/*}" % client.transport._host, args[1]) - - -def test_get_schema_rest_flattened_error(transport: str = 'rest'): - client = SchemaServiceClient( - credentials=ga_credentials.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_schema( - schema_service.GetSchemaRequest(), - name='name_value', - ) - - -def test_get_schema_rest_error(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - schema_service.ListSchemasRequest, - dict, -]) -def test_list_schemas_rest(request_type): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/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 = schema_service.ListSchemasResponse( - next_page_token='next_page_token_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 = schema_service.ListSchemasResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_schemas(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSchemasPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_schemas_rest_required_fields(request_type=schema_service.ListSchemasRequest): - transport_class = transports.SchemaServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_schemas._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_schemas._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = schema_service.ListSchemasResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = schema_service.ListSchemasResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_schemas(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_schemas_rest_unset_required_fields(): - transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_schemas._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_schemas_rest_interceptors(null_interceptor): - transport = transports.SchemaServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), - ) - client = SchemaServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SchemaServiceRestInterceptor, "post_list_schemas") as post, \ - mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_list_schemas") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = schema_service.ListSchemasRequest.pb(schema_service.ListSchemasRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = schema_service.ListSchemasResponse.to_json(schema_service.ListSchemasResponse()) - - request = schema_service.ListSchemasRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = schema_service.ListSchemasResponse() - - client.list_schemas(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_schemas_rest_bad_request(transport: str = 'rest', request_type=schema_service.ListSchemasRequest): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_schemas(request) - - -def test_list_schemas_rest_flattened(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = schema_service.ListSchemasResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/dataStores/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 = schema_service.ListSchemasResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_schemas(**mock_args) - - # Establish that the underlying call 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/*/dataStores/*}/schemas" % client.transport._host, args[1]) - - -def test_list_schemas_rest_flattened_error(transport: str = 'rest'): - client = SchemaServiceClient( - credentials=ga_credentials.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_schemas( - schema_service.ListSchemasRequest(), - parent='parent_value', - ) - - -def test_list_schemas_rest_pager(transport: str = 'rest'): - client = SchemaServiceClient( - 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 = ( - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - schema.Schema(), - ], - next_page_token='abc', - ), - schema_service.ListSchemasResponse( - schemas=[], - next_page_token='def', - ), - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - ], - next_page_token='ghi', - ), - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(schema_service.ListSchemasResponse.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/dataStores/sample3'} - - pager = client.list_schemas(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, schema.Schema) - for i in results) - - pages = list(client.list_schemas(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - schema_service.CreateSchemaRequest, - dict, -]) -def test_create_schema_rest(request_type): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - request_init["schema"] = {'struct_schema': {'fields': {}}, 'json_schema': 'json_schema_value', 'name': 'name_value', 'field_configs': [{'field_path': 'field_path_value', 'field_type': 1, 'indexable_option': 1, 'dynamic_facetable_option': 1, 'searchable_option': 1, 'retrievable_option': 1, 'completable_option': 1, 'recs_filterable_option': 1, 'key_property_type': 'key_property_type_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 = schema_service.CreateSchemaRequest.meta.fields["schema"] - - 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["schema"].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["schema"][field])): - del request_init["schema"][field][i][subfield] - else: - del request_init["schema"][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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_schema(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_create_schema_rest_required_fields(request_type=schema_service.CreateSchemaRequest): - transport_class = transports.SchemaServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["schema_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "schemaId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_schema._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "schemaId" in jsonified_request - assert jsonified_request["schemaId"] == request_init["schema_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["schemaId"] = 'schema_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_schema._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("schema_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "schemaId" in jsonified_request - assert jsonified_request["schemaId"] == 'schema_id_value' - - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_schema(request) - - expected_params = [ - ( - "schemaId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_schema_rest_unset_required_fields(): - transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_schema._get_unset_required_fields({}) - assert set(unset_fields) == (set(("schemaId", )) & set(("parent", "schema", "schemaId", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_schema_rest_interceptors(null_interceptor): - transport = transports.SchemaServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), - ) - client = SchemaServiceClient(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.SchemaServiceRestInterceptor, "post_create_schema") as post, \ - mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_create_schema") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = schema_service.CreateSchemaRequest.pb(schema_service.CreateSchemaRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = schema_service.CreateSchemaRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_schema_rest_bad_request(transport: str = 'rest', request_type=schema_service.CreateSchemaRequest): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_schema(request) - - -def test_create_schema_rest_flattened(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.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/dataStores/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - schema=gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), - schema_id='schema_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_schema(**mock_args) - - # Establish that the underlying call 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/*/dataStores/*}/schemas" % client.transport._host, args[1]) - - -def test_create_schema_rest_flattened_error(transport: str = 'rest'): - client = SchemaServiceClient( - credentials=ga_credentials.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_schema( - schema_service.CreateSchemaRequest(), - parent='parent_value', - schema=gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), - schema_id='schema_id_value', - ) - - -def test_create_schema_rest_error(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - schema_service.UpdateSchemaRequest, - dict, -]) -def test_update_schema_rest(request_type): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'schema': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/sample4'}} - request_init["schema"] = {'struct_schema': {'fields': {}}, 'json_schema': 'json_schema_value', 'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/sample4', 'field_configs': [{'field_path': 'field_path_value', 'field_type': 1, 'indexable_option': 1, 'dynamic_facetable_option': 1, 'searchable_option': 1, 'retrievable_option': 1, 'completable_option': 1, 'recs_filterable_option': 1, 'key_property_type': 'key_property_type_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 = schema_service.UpdateSchemaRequest.meta.fields["schema"] - - 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["schema"].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["schema"][field])): - del request_init["schema"][field][i][subfield] - else: - del request_init["schema"][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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_schema(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_update_schema_rest_required_fields(request_type=schema_service.UpdateSchemaRequest): - transport_class = transports.SchemaServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_schema._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_schema._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_missing", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_schema(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_schema_rest_unset_required_fields(): - transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_schema._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowMissing", )) & set(("schema", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_schema_rest_interceptors(null_interceptor): - transport = transports.SchemaServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), - ) - client = SchemaServiceClient(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.SchemaServiceRestInterceptor, "post_update_schema") as post, \ - mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_update_schema") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = schema_service.UpdateSchemaRequest.pb(schema_service.UpdateSchemaRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = schema_service.UpdateSchemaRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_schema_rest_bad_request(transport: str = 'rest', request_type=schema_service.UpdateSchemaRequest): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'schema': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/sample4'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_schema(request) - - -def test_update_schema_rest_error(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - schema_service.DeleteSchemaRequest, - dict, -]) -def test_delete_schema_rest(request_type): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_schema(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_delete_schema_rest_required_fields(request_type=schema_service.DeleteSchemaRequest): - transport_class = transports.SchemaServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_schema._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_schema._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_schema(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_schema_rest_unset_required_fields(): - transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_schema._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_schema_rest_interceptors(null_interceptor): - transport = transports.SchemaServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), - ) - client = SchemaServiceClient(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.SchemaServiceRestInterceptor, "post_delete_schema") as post, \ - mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_delete_schema") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = schema_service.DeleteSchemaRequest.pb(schema_service.DeleteSchemaRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = schema_service.DeleteSchemaRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_schema_rest_bad_request(transport: str = 'rest', request_type=schema_service.DeleteSchemaRequest): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_schema(request) - - -def test_delete_schema_rest_flattened(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.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/dataStores/sample3/schemas/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_schema(**mock_args) - - # Establish that the underlying call 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/*/dataStores/*/schemas/*}" % client.transport._host, args[1]) - - -def test_delete_schema_rest_flattened_error(transport: str = 'rest'): - client = SchemaServiceClient( - credentials=ga_credentials.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_schema( - schema_service.DeleteSchemaRequest(), - name='name_value', - ) - - -def test_delete_schema_rest_error(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.SchemaServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SchemaServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SchemaServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.SchemaServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SchemaServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SchemaServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SchemaServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SchemaServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SchemaServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SchemaServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SchemaServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SchemaServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.SchemaServiceGrpcTransport, - transports.SchemaServiceGrpcAsyncIOTransport, - transports.SchemaServiceRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = SchemaServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.SchemaServiceGrpcTransport, - ) - -def test_schema_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.SchemaServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_schema_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.discoveryengine_v1alpha.services.schema_service.transports.SchemaServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SchemaServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_schema', - 'list_schemas', - 'create_schema', - 'update_schema', - 'delete_schema', - 'get_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_schema_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.discoveryengine_v1alpha.services.schema_service.transports.SchemaServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SchemaServiceTransport( - 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_schema_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.discoveryengine_v1alpha.services.schema_service.transports.SchemaServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SchemaServiceTransport() - adc.assert_called_once() - - -def test_schema_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) - SchemaServiceClient() - 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.SchemaServiceGrpcTransport, - transports.SchemaServiceGrpcAsyncIOTransport, - ], -) -def test_schema_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.SchemaServiceGrpcTransport, - transports.SchemaServiceGrpcAsyncIOTransport, - transports.SchemaServiceRestTransport, - ], -) -def test_schema_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.SchemaServiceGrpcTransport, grpc_helpers), - (transports.SchemaServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_schema_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.SchemaServiceGrpcTransport, transports.SchemaServiceGrpcAsyncIOTransport]) -def test_schema_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_schema_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.SchemaServiceRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_schema_service_rest_lro_client(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_schema_service_host_no_port(transport_name): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_schema_service_host_with_port(transport_name): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_schema_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = SchemaServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = SchemaServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_schema._session - session2 = client2.transport.get_schema._session - assert session1 != session2 - session1 = client1.transport.list_schemas._session - session2 = client2.transport.list_schemas._session - assert session1 != session2 - session1 = client1.transport.create_schema._session - session2 = client2.transport.create_schema._session - assert session1 != session2 - session1 = client1.transport.update_schema._session - session2 = client2.transport.update_schema._session - assert session1 != session2 - session1 = client1.transport.delete_schema._session - session2 = client2.transport.delete_schema._session - assert session1 != session2 -def test_schema_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SchemaServiceGrpcTransport( - 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_schema_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SchemaServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.SchemaServiceGrpcTransport, transports.SchemaServiceGrpcAsyncIOTransport]) -def test_schema_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.SchemaServiceGrpcTransport, transports.SchemaServiceGrpcAsyncIOTransport]) -def test_schema_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_schema_service_grpc_lro_client(): - client = SchemaServiceClient( - 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_schema_service_grpc_lro_async_client(): - client = SchemaServiceAsyncClient( - 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_data_store_path(): - project = "squid" - location = "clam" - data_store = "whelk" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) - actual = SchemaServiceClient.data_store_path(project, location, data_store) - assert expected == actual - - -def test_parse_data_store_path(): - expected = { - "project": "octopus", - "location": "oyster", - "data_store": "nudibranch", - } - path = SchemaServiceClient.data_store_path(**expected) - - # Check that the path construction is reversible. - actual = SchemaServiceClient.parse_data_store_path(path) - assert expected == actual - -def test_schema_path(): - project = "cuttlefish" - location = "mussel" - data_store = "winkle" - schema = "nautilus" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}/schemas/{schema}".format(project=project, location=location, data_store=data_store, schema=schema, ) - actual = SchemaServiceClient.schema_path(project, location, data_store, schema) - assert expected == actual - - -def test_parse_schema_path(): - expected = { - "project": "scallop", - "location": "abalone", - "data_store": "squid", - "schema": "clam", - } - path = SchemaServiceClient.schema_path(**expected) - - # Check that the path construction is reversible. - actual = SchemaServiceClient.parse_schema_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SchemaServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = SchemaServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SchemaServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = SchemaServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = SchemaServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SchemaServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SchemaServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = SchemaServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SchemaServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = SchemaServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = SchemaServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SchemaServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "scallop" - location = "abalone" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = SchemaServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = SchemaServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SchemaServiceClient.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.SchemaServiceTransport, '_prep_wrapped_messages') as prep: - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SchemaServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = SchemaServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_get_operation(transport: str = "grpc"): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SchemaServiceClient( - 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 = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SchemaServiceClient( - 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 = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = SchemaServiceClient( - 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", [ - (SchemaServiceClient, transports.SchemaServiceGrpcTransport), - (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_search_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_search_service.py deleted file mode 100644 index cdc04bdc2165..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_search_service.py +++ /dev/null @@ -1,2239 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.discoveryengine_v1alpha.services.search_service import SearchServiceAsyncClient -from google.cloud.discoveryengine_v1alpha.services.search_service import SearchServiceClient -from google.cloud.discoveryengine_v1alpha.services.search_service import pagers -from google.cloud.discoveryengine_v1alpha.services.search_service import transports -from google.cloud.discoveryengine_v1alpha.types import common -from google.cloud.discoveryengine_v1alpha.types import search_service -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import struct_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert SearchServiceClient._get_default_mtls_endpoint(None) is None - assert SearchServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (SearchServiceClient, "grpc"), - (SearchServiceAsyncClient, "grpc_asyncio"), - (SearchServiceClient, "rest"), -]) -def test_search_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.SearchServiceGrpcTransport, "grpc"), - (transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.SearchServiceRestTransport, "rest"), -]) -def test_search_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", [ - (SearchServiceClient, "grpc"), - (SearchServiceAsyncClient, "grpc_asyncio"), - (SearchServiceClient, "rest"), -]) -def test_search_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -def test_search_service_client_get_transport_class(): - transport = SearchServiceClient.get_transport_class() - available_transports = [ - transports.SearchServiceGrpcTransport, - transports.SearchServiceRestTransport, - ] - assert transport in available_transports - - transport = SearchServiceClient.get_transport_class("grpc") - assert transport == transports.SearchServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (SearchServiceClient, transports.SearchServiceRestTransport, "rest"), -]) -@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) -@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) -def test_search_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(SearchServiceClient, '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(SearchServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "true"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "false"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (SearchServiceClient, transports.SearchServiceRestTransport, "rest", "true"), - (SearchServiceClient, transports.SearchServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) -@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_search_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 - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - SearchServiceClient, SearchServiceAsyncClient -]) -@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) -@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) -def test_search_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (SearchServiceClient, transports.SearchServiceRestTransport, "rest"), -]) -def test_search_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, - 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", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (SearchServiceClient, transports.SearchServiceRestTransport, "rest", None), -]) -def test_search_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, - scopes=None, - client_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_search_service_client_client_options_from_dict(): - with mock.patch('google.cloud.discoveryengine_v1alpha.services.search_service.transports.SearchServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SearchServiceClient( - 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", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_search_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, - scopes=None, - client_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - search_service.SearchRequest, - dict, -]) -def test_search(request_type, transport: str = 'grpc'): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = search_service.SearchResponse( - total_size=1086, - attribution_token='attribution_token_value', - redirect_uri='redirect_uri_value', - next_page_token='next_page_token_value', - corrected_query='corrected_query_value', - applied_controls=['applied_controls_value'], - ) - response = client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchPager) - assert response.total_size == 1086 - assert response.attribution_token == 'attribution_token_value' - assert response.redirect_uri == 'redirect_uri_value' - assert response.next_page_token == 'next_page_token_value' - assert response.corrected_query == 'corrected_query_value' - assert response.applied_controls == ['applied_controls_value'] - - -def test_search_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - client.search() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - -@pytest.mark.asyncio -async def test_search_async(transport: str = 'grpc_asyncio', request_type=search_service.SearchRequest): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse( - total_size=1086, - attribution_token='attribution_token_value', - redirect_uri='redirect_uri_value', - next_page_token='next_page_token_value', - corrected_query='corrected_query_value', - applied_controls=['applied_controls_value'], - )) - response = await client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchAsyncPager) - assert response.total_size == 1086 - assert response.attribution_token == 'attribution_token_value' - assert response.redirect_uri == 'redirect_uri_value' - assert response.next_page_token == 'next_page_token_value' - assert response.corrected_query == 'corrected_query_value' - assert response.applied_controls == ['applied_controls_value'] - - -@pytest.mark.asyncio -async def test_search_async_from_dict(): - await test_search_async(request_type=dict) - - -def test_search_field_headers(): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = search_service.SearchRequest() - - request.serving_config = 'serving_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - call.return_value = search_service.SearchResponse() - client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config=serving_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_search_field_headers_async(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = search_service.SearchRequest() - - request.serving_config = 'serving_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse()) - await client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config=serving_config_value', - ) in kw['metadata'] - - -def test_search_pager(transport_name: str = "grpc"): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('serving_config', ''), - )), - ) - pager = client.search(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, search_service.SearchResponse.SearchResult) - for i in results) -def test_search_pages(transport_name: str = "grpc"): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - pages = list(client.search(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_search_async_pager(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.search(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, search_service.SearchResponse.SearchResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_search_async_pages(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.search(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", [ - search_service.SearchRequest, - dict, -]) -def test_search_rest(request_type): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'serving_config': 'projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/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 = search_service.SearchResponse( - total_size=1086, - attribution_token='attribution_token_value', - redirect_uri='redirect_uri_value', - next_page_token='next_page_token_value', - corrected_query='corrected_query_value', - applied_controls=['applied_controls_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 = search_service.SearchResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.search(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchPager) - assert response.total_size == 1086 - assert response.attribution_token == 'attribution_token_value' - assert response.redirect_uri == 'redirect_uri_value' - assert response.next_page_token == 'next_page_token_value' - assert response.corrected_query == 'corrected_query_value' - assert response.applied_controls == ['applied_controls_value'] - - -def test_search_rest_required_fields(request_type=search_service.SearchRequest): - transport_class = transports.SearchServiceRestTransport - - request_init = {} - request_init["serving_config"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["servingConfig"] = 'serving_config_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "servingConfig" in jsonified_request - assert jsonified_request["servingConfig"] == 'serving_config_value' - - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = search_service.SearchResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = search_service.SearchResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.search(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_search_rest_unset_required_fields(): - transport = transports.SearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.search._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("servingConfig", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_search_rest_interceptors(null_interceptor): - transport = transports.SearchServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SearchServiceRestInterceptor(), - ) - client = SearchServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SearchServiceRestInterceptor, "post_search") as post, \ - mock.patch.object(transports.SearchServiceRestInterceptor, "pre_search") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = search_service.SearchRequest.pb(search_service.SearchRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = search_service.SearchResponse.to_json(search_service.SearchResponse()) - - request = search_service.SearchRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = search_service.SearchResponse() - - client.search(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_search_rest_bad_request(transport: str = 'rest', request_type=search_service.SearchRequest): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'serving_config': 'projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.search(request) - - -def test_search_rest_pager(transport: str = 'rest'): - client = SearchServiceClient( - 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 = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(search_service.SearchResponse.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 = {'serving_config': 'projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/sample4'} - - pager = client.search(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, search_service.SearchResponse.SearchResult) - for i in results) - - pages = list(client.search(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.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SearchServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SearchServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.SearchServiceGrpcTransport, - transports.SearchServiceGrpcAsyncIOTransport, - transports.SearchServiceRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = SearchServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.SearchServiceGrpcTransport, - ) - -def test_search_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.SearchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_search_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.discoveryengine_v1alpha.services.search_service.transports.SearchServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SearchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'search', - 'get_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_search_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.discoveryengine_v1alpha.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SearchServiceTransport( - 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_search_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.discoveryengine_v1alpha.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SearchServiceTransport() - adc.assert_called_once() - - -def test_search_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) - SearchServiceClient() - 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.SearchServiceGrpcTransport, - transports.SearchServiceGrpcAsyncIOTransport, - ], -) -def test_search_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.SearchServiceGrpcTransport, - transports.SearchServiceGrpcAsyncIOTransport, - transports.SearchServiceRestTransport, - ], -) -def test_search_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.SearchServiceGrpcTransport, grpc_helpers), - (transports.SearchServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_search_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) -def test_search_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_search_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.SearchServiceRestTransport ( - 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_search_service_host_no_port(transport_name): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_search_service_host_with_port(transport_name): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_search_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = SearchServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = SearchServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.search._session - session2 = client2.transport.search._session - assert session1 != session2 -def test_search_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SearchServiceGrpcTransport( - 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_search_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SearchServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) -def test_search_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.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) -def test_search_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_branch_path(): - project = "squid" - location = "clam" - data_store = "whelk" - branch = "octopus" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}".format(project=project, location=location, data_store=data_store, branch=branch, ) - actual = SearchServiceClient.branch_path(project, location, data_store, branch) - assert expected == actual - - -def test_parse_branch_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "data_store": "cuttlefish", - "branch": "mussel", - } - path = SearchServiceClient.branch_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_branch_path(path) - assert expected == actual - -def test_document_path(): - project = "winkle" - location = "nautilus" - data_store = "scallop" - branch = "abalone" - document = "squid" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) - actual = SearchServiceClient.document_path(project, location, data_store, branch, document) - assert expected == actual - - -def test_parse_document_path(): - expected = { - "project": "clam", - "location": "whelk", - "data_store": "octopus", - "branch": "oyster", - "document": "nudibranch", - } - path = SearchServiceClient.document_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_document_path(path) - assert expected == actual - -def test_serving_config_path(): - project = "cuttlefish" - location = "mussel" - data_store = "winkle" - serving_config = "nautilus" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}/servingConfigs/{serving_config}".format(project=project, location=location, data_store=data_store, serving_config=serving_config, ) - actual = SearchServiceClient.serving_config_path(project, location, data_store, serving_config) - assert expected == actual - - -def test_parse_serving_config_path(): - expected = { - "project": "scallop", - "location": "abalone", - "data_store": "squid", - "serving_config": "clam", - } - path = SearchServiceClient.serving_config_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_serving_config_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SearchServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = SearchServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = SearchServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = SearchServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SearchServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = SearchServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = SearchServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = SearchServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "scallop" - location = "abalone" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = SearchServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = SearchServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.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.SearchServiceTransport, '_prep_wrapped_messages') as prep: - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = SearchServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_get_operation(transport: str = "grpc"): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SearchServiceClient( - 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 = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SearchServiceClient( - 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 = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = SearchServiceClient( - 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", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_site_search_engine_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_site_search_engine_service.py deleted file mode 100644 index f81202d1d8f6..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_site_search_engine_service.py +++ /dev/null @@ -1,1961 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.discoveryengine_v1alpha.services.site_search_engine_service import SiteSearchEngineServiceAsyncClient -from google.cloud.discoveryengine_v1alpha.services.site_search_engine_service import SiteSearchEngineServiceClient -from google.cloud.discoveryengine_v1alpha.services.site_search_engine_service import transports -from google.cloud.discoveryengine_v1alpha.types import site_search_engine_service -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert SiteSearchEngineServiceClient._get_default_mtls_endpoint(None) is None - assert SiteSearchEngineServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SiteSearchEngineServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SiteSearchEngineServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SiteSearchEngineServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SiteSearchEngineServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (SiteSearchEngineServiceClient, "grpc"), - (SiteSearchEngineServiceAsyncClient, "grpc_asyncio"), - (SiteSearchEngineServiceClient, "rest"), -]) -def test_site_search_engine_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.SiteSearchEngineServiceGrpcTransport, "grpc"), - (transports.SiteSearchEngineServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.SiteSearchEngineServiceRestTransport, "rest"), -]) -def test_site_search_engine_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", [ - (SiteSearchEngineServiceClient, "grpc"), - (SiteSearchEngineServiceAsyncClient, "grpc_asyncio"), - (SiteSearchEngineServiceClient, "rest"), -]) -def test_site_search_engine_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -def test_site_search_engine_service_client_get_transport_class(): - transport = SiteSearchEngineServiceClient.get_transport_class() - available_transports = [ - transports.SiteSearchEngineServiceGrpcTransport, - transports.SiteSearchEngineServiceRestTransport, - ] - assert transport in available_transports - - transport = SiteSearchEngineServiceClient.get_transport_class("grpc") - assert transport == transports.SiteSearchEngineServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SiteSearchEngineServiceClient, transports.SiteSearchEngineServiceGrpcTransport, "grpc"), - (SiteSearchEngineServiceAsyncClient, transports.SiteSearchEngineServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (SiteSearchEngineServiceClient, transports.SiteSearchEngineServiceRestTransport, "rest"), -]) -@mock.patch.object(SiteSearchEngineServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SiteSearchEngineServiceClient)) -@mock.patch.object(SiteSearchEngineServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SiteSearchEngineServiceAsyncClient)) -def test_site_search_engine_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(SiteSearchEngineServiceClient, '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(SiteSearchEngineServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (SiteSearchEngineServiceClient, transports.SiteSearchEngineServiceGrpcTransport, "grpc", "true"), - (SiteSearchEngineServiceAsyncClient, transports.SiteSearchEngineServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SiteSearchEngineServiceClient, transports.SiteSearchEngineServiceGrpcTransport, "grpc", "false"), - (SiteSearchEngineServiceAsyncClient, transports.SiteSearchEngineServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (SiteSearchEngineServiceClient, transports.SiteSearchEngineServiceRestTransport, "rest", "true"), - (SiteSearchEngineServiceClient, transports.SiteSearchEngineServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(SiteSearchEngineServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SiteSearchEngineServiceClient)) -@mock.patch.object(SiteSearchEngineServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SiteSearchEngineServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_site_search_engine_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 - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - SiteSearchEngineServiceClient, SiteSearchEngineServiceAsyncClient -]) -@mock.patch.object(SiteSearchEngineServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SiteSearchEngineServiceClient)) -@mock.patch.object(SiteSearchEngineServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SiteSearchEngineServiceAsyncClient)) -def test_site_search_engine_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SiteSearchEngineServiceClient, transports.SiteSearchEngineServiceGrpcTransport, "grpc"), - (SiteSearchEngineServiceAsyncClient, transports.SiteSearchEngineServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (SiteSearchEngineServiceClient, transports.SiteSearchEngineServiceRestTransport, "rest"), -]) -def test_site_search_engine_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, - 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", [ - (SiteSearchEngineServiceClient, transports.SiteSearchEngineServiceGrpcTransport, "grpc", grpc_helpers), - (SiteSearchEngineServiceAsyncClient, transports.SiteSearchEngineServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (SiteSearchEngineServiceClient, transports.SiteSearchEngineServiceRestTransport, "rest", None), -]) -def test_site_search_engine_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, - scopes=None, - client_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_site_search_engine_service_client_client_options_from_dict(): - with mock.patch('google.cloud.discoveryengine_v1alpha.services.site_search_engine_service.transports.SiteSearchEngineServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SiteSearchEngineServiceClient( - 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", [ - (SiteSearchEngineServiceClient, transports.SiteSearchEngineServiceGrpcTransport, "grpc", grpc_helpers), - (SiteSearchEngineServiceAsyncClient, transports.SiteSearchEngineServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_site_search_engine_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, - scopes=None, - client_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - site_search_engine_service.RecrawlUrisRequest, - dict, -]) -def test_recrawl_uris(request_type, transport: str = 'grpc'): - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.recrawl_uris), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.recrawl_uris(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == site_search_engine_service.RecrawlUrisRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_recrawl_uris_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.recrawl_uris), - '__call__') as call: - client.recrawl_uris() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == site_search_engine_service.RecrawlUrisRequest() - -@pytest.mark.asyncio -async def test_recrawl_uris_async(transport: str = 'grpc_asyncio', request_type=site_search_engine_service.RecrawlUrisRequest): - client = SiteSearchEngineServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.recrawl_uris), - '__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.recrawl_uris(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == site_search_engine_service.RecrawlUrisRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_recrawl_uris_async_from_dict(): - await test_recrawl_uris_async(request_type=dict) - - -def test_recrawl_uris_field_headers(): - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = site_search_engine_service.RecrawlUrisRequest() - - request.site_search_engine = 'site_search_engine_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.recrawl_uris), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.recrawl_uris(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'site_search_engine=site_search_engine_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_recrawl_uris_field_headers_async(): - client = SiteSearchEngineServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = site_search_engine_service.RecrawlUrisRequest() - - request.site_search_engine = 'site_search_engine_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.recrawl_uris), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.recrawl_uris(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'site_search_engine=site_search_engine_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - site_search_engine_service.RecrawlUrisRequest, - dict, -]) -def test_recrawl_uris_rest(request_type): - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'site_search_engine': 'projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.recrawl_uris(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_recrawl_uris_rest_required_fields(request_type=site_search_engine_service.RecrawlUrisRequest): - transport_class = transports.SiteSearchEngineServiceRestTransport - - request_init = {} - request_init["site_search_engine"] = "" - request_init["uris"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).recrawl_uris._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["siteSearchEngine"] = 'site_search_engine_value' - jsonified_request["uris"] = 'uris_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).recrawl_uris._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "siteSearchEngine" in jsonified_request - assert jsonified_request["siteSearchEngine"] == 'site_search_engine_value' - assert "uris" in jsonified_request - assert jsonified_request["uris"] == 'uris_value' - - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.recrawl_uris(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_recrawl_uris_rest_unset_required_fields(): - transport = transports.SiteSearchEngineServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.recrawl_uris._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("siteSearchEngine", "uris", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_recrawl_uris_rest_interceptors(null_interceptor): - transport = transports.SiteSearchEngineServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SiteSearchEngineServiceRestInterceptor(), - ) - client = SiteSearchEngineServiceClient(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.SiteSearchEngineServiceRestInterceptor, "post_recrawl_uris") as post, \ - mock.patch.object(transports.SiteSearchEngineServiceRestInterceptor, "pre_recrawl_uris") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = site_search_engine_service.RecrawlUrisRequest.pb(site_search_engine_service.RecrawlUrisRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = site_search_engine_service.RecrawlUrisRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.recrawl_uris(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_recrawl_uris_rest_bad_request(transport: str = 'rest', request_type=site_search_engine_service.RecrawlUrisRequest): - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'site_search_engine': 'projects/sample1/locations/sample2/dataStores/sample3/siteSearchEngine'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.recrawl_uris(request) - - -def test_recrawl_uris_rest_error(): - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.SiteSearchEngineServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SiteSearchEngineServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SiteSearchEngineServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.SiteSearchEngineServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SiteSearchEngineServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SiteSearchEngineServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SiteSearchEngineServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SiteSearchEngineServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SiteSearchEngineServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SiteSearchEngineServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SiteSearchEngineServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SiteSearchEngineServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.SiteSearchEngineServiceGrpcTransport, - transports.SiteSearchEngineServiceGrpcAsyncIOTransport, - transports.SiteSearchEngineServiceRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = SiteSearchEngineServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.SiteSearchEngineServiceGrpcTransport, - ) - -def test_site_search_engine_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.SiteSearchEngineServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_site_search_engine_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.discoveryengine_v1alpha.services.site_search_engine_service.transports.SiteSearchEngineServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SiteSearchEngineServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'recrawl_uris', - 'get_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_site_search_engine_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.discoveryengine_v1alpha.services.site_search_engine_service.transports.SiteSearchEngineServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SiteSearchEngineServiceTransport( - 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_site_search_engine_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.discoveryengine_v1alpha.services.site_search_engine_service.transports.SiteSearchEngineServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SiteSearchEngineServiceTransport() - adc.assert_called_once() - - -def test_site_search_engine_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) - SiteSearchEngineServiceClient() - 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.SiteSearchEngineServiceGrpcTransport, - transports.SiteSearchEngineServiceGrpcAsyncIOTransport, - ], -) -def test_site_search_engine_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.SiteSearchEngineServiceGrpcTransport, - transports.SiteSearchEngineServiceGrpcAsyncIOTransport, - transports.SiteSearchEngineServiceRestTransport, - ], -) -def test_site_search_engine_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.SiteSearchEngineServiceGrpcTransport, grpc_helpers), - (transports.SiteSearchEngineServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_site_search_engine_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.SiteSearchEngineServiceGrpcTransport, transports.SiteSearchEngineServiceGrpcAsyncIOTransport]) -def test_site_search_engine_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_site_search_engine_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.SiteSearchEngineServiceRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_site_search_engine_service_rest_lro_client(): - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_site_search_engine_service_host_no_port(transport_name): - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_site_search_engine_service_host_with_port(transport_name): - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_site_search_engine_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = SiteSearchEngineServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = SiteSearchEngineServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.recrawl_uris._session - session2 = client2.transport.recrawl_uris._session - assert session1 != session2 -def test_site_search_engine_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SiteSearchEngineServiceGrpcTransport( - 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_site_search_engine_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SiteSearchEngineServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.SiteSearchEngineServiceGrpcTransport, transports.SiteSearchEngineServiceGrpcAsyncIOTransport]) -def test_site_search_engine_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.SiteSearchEngineServiceGrpcTransport, transports.SiteSearchEngineServiceGrpcAsyncIOTransport]) -def test_site_search_engine_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_site_search_engine_service_grpc_lro_client(): - client = SiteSearchEngineServiceClient( - 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_site_search_engine_service_grpc_lro_async_client(): - client = SiteSearchEngineServiceAsyncClient( - 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_site_search_engine_path(): - project = "squid" - location = "clam" - data_store = "whelk" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}/siteSearchEngine".format(project=project, location=location, data_store=data_store, ) - actual = SiteSearchEngineServiceClient.site_search_engine_path(project, location, data_store) - assert expected == actual - - -def test_parse_site_search_engine_path(): - expected = { - "project": "octopus", - "location": "oyster", - "data_store": "nudibranch", - } - path = SiteSearchEngineServiceClient.site_search_engine_path(**expected) - - # Check that the path construction is reversible. - actual = SiteSearchEngineServiceClient.parse_site_search_engine_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SiteSearchEngineServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = SiteSearchEngineServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SiteSearchEngineServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = SiteSearchEngineServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = SiteSearchEngineServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SiteSearchEngineServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SiteSearchEngineServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = SiteSearchEngineServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SiteSearchEngineServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = SiteSearchEngineServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = SiteSearchEngineServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SiteSearchEngineServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = SiteSearchEngineServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = SiteSearchEngineServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SiteSearchEngineServiceClient.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.SiteSearchEngineServiceTransport, '_prep_wrapped_messages') as prep: - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SiteSearchEngineServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = SiteSearchEngineServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = SiteSearchEngineServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_get_operation(transport: str = "grpc"): - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = SiteSearchEngineServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SiteSearchEngineServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SiteSearchEngineServiceClient( - 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 = SiteSearchEngineServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = SiteSearchEngineServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SiteSearchEngineServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SiteSearchEngineServiceClient( - 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 = SiteSearchEngineServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = SiteSearchEngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = SiteSearchEngineServiceClient( - 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", [ - (SiteSearchEngineServiceClient, transports.SiteSearchEngineServiceGrpcTransport), - (SiteSearchEngineServiceAsyncClient, transports.SiteSearchEngineServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_user_event_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_user_event_service.py deleted file mode 100644 index 36088e10e67e..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_user_event_service.py +++ /dev/null @@ -1,3118 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.discoveryengine_v1alpha.services.user_event_service import UserEventServiceAsyncClient -from google.cloud.discoveryengine_v1alpha.services.user_event_service import UserEventServiceClient -from google.cloud.discoveryengine_v1alpha.services.user_event_service import transports -from google.cloud.discoveryengine_v1alpha.types import common -from google.cloud.discoveryengine_v1alpha.types import import_config -from google.cloud.discoveryengine_v1alpha.types import purge_config -from google.cloud.discoveryengine_v1alpha.types import user_event -from google.cloud.discoveryengine_v1alpha.types import user_event_service -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert UserEventServiceClient._get_default_mtls_endpoint(None) is None - assert UserEventServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (UserEventServiceClient, "grpc"), - (UserEventServiceAsyncClient, "grpc_asyncio"), - (UserEventServiceClient, "rest"), -]) -def test_user_event_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.UserEventServiceGrpcTransport, "grpc"), - (transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.UserEventServiceRestTransport, "rest"), -]) -def test_user_event_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", [ - (UserEventServiceClient, "grpc"), - (UserEventServiceAsyncClient, "grpc_asyncio"), - (UserEventServiceClient, "rest"), -]) -def test_user_event_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -def test_user_event_service_client_get_transport_class(): - transport = UserEventServiceClient.get_transport_class() - available_transports = [ - transports.UserEventServiceGrpcTransport, - transports.UserEventServiceRestTransport, - ] - assert transport in available_transports - - transport = UserEventServiceClient.get_transport_class("grpc") - assert transport == transports.UserEventServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (UserEventServiceClient, transports.UserEventServiceRestTransport, "rest"), -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -def test_user_event_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(UserEventServiceClient, '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(UserEventServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "true"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "false"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (UserEventServiceClient, transports.UserEventServiceRestTransport, "rest", "true"), - (UserEventServiceClient, transports.UserEventServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_user_event_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 - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - UserEventServiceClient, UserEventServiceAsyncClient -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -def test_user_event_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (UserEventServiceClient, transports.UserEventServiceRestTransport, "rest"), -]) -def test_user_event_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, - 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", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (UserEventServiceClient, transports.UserEventServiceRestTransport, "rest", None), -]) -def test_user_event_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, - scopes=None, - client_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_user_event_service_client_client_options_from_dict(): - with mock.patch('google.cloud.discoveryengine_v1alpha.services.user_event_service.transports.UserEventServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = UserEventServiceClient( - 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", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_user_event_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, - scopes=None, - client_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - user_event_service.WriteUserEventRequest, - dict, -]) -def test_write_user_event(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = user_event.UserEvent( - event_type='event_type_value', - user_pseudo_id='user_pseudo_id_value', - direct_user_request=True, - session_id='session_id_value', - attribution_token='attribution_token_value', - filter='filter_value', - tag_ids=['tag_ids_value'], - promotion_ids=['promotion_ids_value'], - ) - response = client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, user_event.UserEvent) - assert response.event_type == 'event_type_value' - assert response.user_pseudo_id == 'user_pseudo_id_value' - assert response.direct_user_request is True - assert response.session_id == 'session_id_value' - assert response.attribution_token == 'attribution_token_value' - assert response.filter == 'filter_value' - assert response.tag_ids == ['tag_ids_value'] - assert response.promotion_ids == ['promotion_ids_value'] - - -def test_write_user_event_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - client.write_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - -@pytest.mark.asyncio -async def test_write_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.WriteUserEventRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent( - event_type='event_type_value', - user_pseudo_id='user_pseudo_id_value', - direct_user_request=True, - session_id='session_id_value', - attribution_token='attribution_token_value', - filter='filter_value', - tag_ids=['tag_ids_value'], - promotion_ids=['promotion_ids_value'], - )) - response = await client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, user_event.UserEvent) - assert response.event_type == 'event_type_value' - assert response.user_pseudo_id == 'user_pseudo_id_value' - assert response.direct_user_request is True - assert response.session_id == 'session_id_value' - assert response.attribution_token == 'attribution_token_value' - assert response.filter == 'filter_value' - assert response.tag_ids == ['tag_ids_value'] - assert response.promotion_ids == ['promotion_ids_value'] - - -@pytest.mark.asyncio -async def test_write_user_event_async_from_dict(): - await test_write_user_event_async(request_type=dict) - - -def test_write_user_event_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.WriteUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - call.return_value = user_event.UserEvent() - client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_write_user_event_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.WriteUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent()) - await client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - user_event_service.CollectUserEventRequest, - dict, -]) -def test_collect_user_event(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - ) - response = client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -def test_collect_user_event_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - client.collect_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - -@pytest.mark.asyncio -async def test_collect_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.CollectUserEventRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - )) - response = await client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -@pytest.mark.asyncio -async def test_collect_user_event_async_from_dict(): - await test_collect_user_event_async(request_type=dict) - - -def test_collect_user_event_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.CollectUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - call.return_value = httpbody_pb2.HttpBody() - client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_collect_user_event_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.CollectUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody()) - await client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - purge_config.PurgeUserEventsRequest, - dict, -]) -def test_purge_user_events(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_purge_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - client.purge_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeUserEventsRequest() - -@pytest.mark.asyncio -async def test_purge_user_events_async(transport: str = 'grpc_asyncio', request_type=purge_config.PurgeUserEventsRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__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.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_purge_user_events_async_from_dict(): - await test_purge_user_events_async(request_type=dict) - - -def test_purge_user_events_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = purge_config.PurgeUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_purge_user_events_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = purge_config.PurgeUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_user_events), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.purge_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportUserEventsRequest, - dict, -]) -def test_import_user_events(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - client.import_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - -@pytest.mark.asyncio -async def test_import_user_events_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportUserEventsRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__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_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_user_events_async_from_dict(): - await test_import_user_events_async(request_type=dict) - - -def test_import_user_events_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_import_user_events_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - user_event_service.WriteUserEventRequest, - dict, -]) -def test_write_user_event_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - request_init["user_event"] = {'event_type': 'event_type_value', 'user_pseudo_id': 'user_pseudo_id_value', 'event_time': {'seconds': 751, 'nanos': 543}, 'user_info': {'user_id': 'user_id_value', 'user_agent': 'user_agent_value'}, 'direct_user_request': True, 'session_id': 'session_id_value', 'page_info': {'pageview_id': 'pageview_id_value', 'page_category': 'page_category_value', 'uri': 'uri_value', 'referrer_uri': 'referrer_uri_value'}, 'attribution_token': 'attribution_token_value', 'filter': 'filter_value', 'documents': [{'id': 'id_value', 'name': 'name_value', 'uri': 'uri_value', 'quantity': 895, 'promotion_ids': ['promotion_ids_value1', 'promotion_ids_value2']}], 'panel': {'panel_id': 'panel_id_value', 'display_name': 'display_name_value', 'panel_position': 1508, 'total_panels': 1286}, 'search_info': {'search_query': 'search_query_value', 'order_by': 'order_by_value', 'offset': 647}, 'completion_info': {'selected_suggestion': 'selected_suggestion_value', 'selected_position': 1821}, 'transaction_info': {'value': 0.541, 'currency': 'currency_value', 'transaction_id': 'transaction_id_value', 'tax': 0.333, 'cost': 0.441, 'discount_value': 0.1509}, 'tag_ids': ['tag_ids_value1', 'tag_ids_value2'], 'promotion_ids': ['promotion_ids_value1', 'promotion_ids_value2'], 'attributes': {}, 'media_info': {'media_progress_duration': {'seconds': 751, 'nanos': 543}, 'media_progress_percentage': 0.2641}} - # 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 = user_event_service.WriteUserEventRequest.meta.fields["user_event"] - - 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_event"].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_event"][field])): - del request_init["user_event"][field][i][subfield] - else: - del request_init["user_event"][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 = user_event.UserEvent( - event_type='event_type_value', - user_pseudo_id='user_pseudo_id_value', - direct_user_request=True, - session_id='session_id_value', - attribution_token='attribution_token_value', - filter='filter_value', - tag_ids=['tag_ids_value'], - promotion_ids=['promotion_ids_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 = user_event.UserEvent.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.write_user_event(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, user_event.UserEvent) - assert response.event_type == 'event_type_value' - assert response.user_pseudo_id == 'user_pseudo_id_value' - assert response.direct_user_request is True - assert response.session_id == 'session_id_value' - assert response.attribution_token == 'attribution_token_value' - assert response.filter == 'filter_value' - assert response.tag_ids == ['tag_ids_value'] - assert response.promotion_ids == ['promotion_ids_value'] - - -def test_write_user_event_rest_required_fields(request_type=user_event_service.WriteUserEventRequest): - transport_class = transports.UserEventServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).write_user_event._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).write_user_event._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = user_event.UserEvent() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = user_event.UserEvent.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.write_user_event(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_write_user_event_rest_unset_required_fields(): - transport = transports.UserEventServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.write_user_event._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "userEvent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_write_user_event_rest_interceptors(null_interceptor): - transport = transports.UserEventServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.UserEventServiceRestInterceptor(), - ) - client = UserEventServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.UserEventServiceRestInterceptor, "post_write_user_event") as post, \ - mock.patch.object(transports.UserEventServiceRestInterceptor, "pre_write_user_event") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = user_event_service.WriteUserEventRequest.pb(user_event_service.WriteUserEventRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = user_event.UserEvent.to_json(user_event.UserEvent()) - - request = user_event_service.WriteUserEventRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = user_event.UserEvent() - - client.write_user_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_write_user_event_rest_bad_request(transport: str = 'rest', request_type=user_event_service.WriteUserEventRequest): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.write_user_event(request) - - -def test_write_user_event_rest_error(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - user_event_service.CollectUserEventRequest, - dict, -]) -def test_collect_user_event_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/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 = httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.collect_user_event(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -def test_collect_user_event_rest_required_fields(request_type=user_event_service.CollectUserEventRequest): - transport_class = transports.UserEventServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["user_event"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "userEvent" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).collect_user_event._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "userEvent" in jsonified_request - assert jsonified_request["userEvent"] == request_init["user_event"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["userEvent"] = 'user_event_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).collect_user_event._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("ets", "uri", "user_event", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "userEvent" in jsonified_request - assert jsonified_request["userEvent"] == 'user_event_value' - - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = httpbody_pb2.HttpBody() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 - - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.collect_user_event(request) - - expected_params = [ - ( - "userEvent", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_collect_user_event_rest_unset_required_fields(): - transport = transports.UserEventServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.collect_user_event._get_unset_required_fields({}) - assert set(unset_fields) == (set(("ets", "uri", "userEvent", )) & set(("parent", "userEvent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_collect_user_event_rest_interceptors(null_interceptor): - transport = transports.UserEventServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.UserEventServiceRestInterceptor(), - ) - client = UserEventServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.UserEventServiceRestInterceptor, "post_collect_user_event") as post, \ - mock.patch.object(transports.UserEventServiceRestInterceptor, "pre_collect_user_event") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = user_event_service.CollectUserEventRequest.pb(user_event_service.CollectUserEventRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(httpbody_pb2.HttpBody()) - - request = user_event_service.CollectUserEventRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = httpbody_pb2.HttpBody() - - client.collect_user_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_collect_user_event_rest_bad_request(transport: str = 'rest', request_type=user_event_service.CollectUserEventRequest): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.collect_user_event(request) - - -def test_collect_user_event_rest_error(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - purge_config.PurgeUserEventsRequest, - dict, -]) -def test_purge_user_events_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.purge_user_events(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_purge_user_events_rest_required_fields(request_type=purge_config.PurgeUserEventsRequest): - transport_class = transports.UserEventServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["filter"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).purge_user_events._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - jsonified_request["filter"] = 'filter_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).purge_user_events._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "filter" in jsonified_request - assert jsonified_request["filter"] == 'filter_value' - - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.purge_user_events(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_purge_user_events_rest_unset_required_fields(): - transport = transports.UserEventServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.purge_user_events._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "filter", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_purge_user_events_rest_interceptors(null_interceptor): - transport = transports.UserEventServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.UserEventServiceRestInterceptor(), - ) - client = UserEventServiceClient(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.UserEventServiceRestInterceptor, "post_purge_user_events") as post, \ - mock.patch.object(transports.UserEventServiceRestInterceptor, "pre_purge_user_events") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = purge_config.PurgeUserEventsRequest.pb(purge_config.PurgeUserEventsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = purge_config.PurgeUserEventsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.purge_user_events(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_purge_user_events_rest_bad_request(transport: str = 'rest', request_type=purge_config.PurgeUserEventsRequest): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.purge_user_events(request) - - -def test_purge_user_events_rest_error(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportUserEventsRequest, - dict, -]) -def test_import_user_events_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.import_user_events(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_import_user_events_rest_required_fields(request_type=import_config.ImportUserEventsRequest): - transport_class = transports.UserEventServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_user_events._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_user_events._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.import_user_events(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_import_user_events_rest_unset_required_fields(): - transport = transports.UserEventServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.import_user_events._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_import_user_events_rest_interceptors(null_interceptor): - transport = transports.UserEventServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.UserEventServiceRestInterceptor(), - ) - client = UserEventServiceClient(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.UserEventServiceRestInterceptor, "post_import_user_events") as post, \ - mock.patch.object(transports.UserEventServiceRestInterceptor, "pre_import_user_events") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = import_config.ImportUserEventsRequest.pb(import_config.ImportUserEventsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = import_config.ImportUserEventsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.import_user_events(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_import_user_events_rest_bad_request(transport: str = 'rest', request_type=import_config.ImportUserEventsRequest): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.import_user_events(request) - - -def test_import_user_events_rest_error(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = UserEventServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.UserEventServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, - transports.UserEventServiceRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = UserEventServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.UserEventServiceGrpcTransport, - ) - -def test_user_event_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.UserEventServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_user_event_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.discoveryengine_v1alpha.services.user_event_service.transports.UserEventServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.UserEventServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'write_user_event', - 'collect_user_event', - 'purge_user_events', - 'import_user_events', - 'get_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_user_event_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.discoveryengine_v1alpha.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.UserEventServiceTransport( - 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_user_event_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.discoveryengine_v1alpha.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.UserEventServiceTransport() - adc.assert_called_once() - - -def test_user_event_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) - UserEventServiceClient() - 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.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, - ], -) -def test_user_event_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.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, - transports.UserEventServiceRestTransport, - ], -) -def test_user_event_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.UserEventServiceGrpcTransport, grpc_helpers), - (transports.UserEventServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_user_event_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_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_user_event_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.UserEventServiceRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_user_event_service_rest_lro_client(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_user_event_service_host_no_port(transport_name): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_user_event_service_host_with_port(transport_name): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_user_event_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = UserEventServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = UserEventServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.write_user_event._session - session2 = client2.transport.write_user_event._session - assert session1 != session2 - session1 = client1.transport.collect_user_event._session - session2 = client2.transport.collect_user_event._session - assert session1 != session2 - session1 = client1.transport.purge_user_events._session - session2 = client2.transport.purge_user_events._session - assert session1 != session2 - session1 = client1.transport.import_user_events._session - session2 = client2.transport.import_user_events._session - assert session1 != session2 -def test_user_event_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.UserEventServiceGrpcTransport( - 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_user_event_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.UserEventServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_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.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_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_user_event_service_grpc_lro_client(): - client = UserEventServiceClient( - 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_user_event_service_grpc_lro_async_client(): - client = UserEventServiceAsyncClient( - 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_data_store_path(): - project = "squid" - location = "clam" - data_store = "whelk" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) - actual = UserEventServiceClient.data_store_path(project, location, data_store) - assert expected == actual - - -def test_parse_data_store_path(): - expected = { - "project": "octopus", - "location": "oyster", - "data_store": "nudibranch", - } - path = UserEventServiceClient.data_store_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_data_store_path(path) - assert expected == actual - -def test_document_path(): - project = "cuttlefish" - location = "mussel" - data_store = "winkle" - branch = "nautilus" - document = "scallop" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) - actual = UserEventServiceClient.document_path(project, location, data_store, branch, document) - assert expected == actual - - -def test_parse_document_path(): - expected = { - "project": "abalone", - "location": "squid", - "data_store": "clam", - "branch": "whelk", - "document": "octopus", - } - path = UserEventServiceClient.document_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_document_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = UserEventServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = UserEventServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = UserEventServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = UserEventServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = UserEventServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = UserEventServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = UserEventServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = UserEventServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "squid" - location = "clam" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = UserEventServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = UserEventServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.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.UserEventServiceTransport, '_prep_wrapped_messages') as prep: - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = UserEventServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_get_operation(transport: str = "grpc"): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = UserEventServiceClient( - 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 = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = UserEventServiceClient( - 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 = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = UserEventServiceClient( - 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", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/.coveragerc b/owl-bot-staging/google-cloud-discoveryengine/v1beta/.coveragerc deleted file mode 100644 index f2c9bc595be9..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/discoveryengine/__init__.py - google/cloud/discoveryengine/gapic_version.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/.flake8 b/owl-bot-staging/google-cloud-discoveryengine/v1beta/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/MANIFEST.in b/owl-bot-staging/google-cloud-discoveryengine/v1beta/MANIFEST.in deleted file mode 100644 index a4ea2c8c7cd8..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/discoveryengine *.py -recursive-include google/cloud/discoveryengine_v1beta *.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/README.rst b/owl-bot-staging/google-cloud-discoveryengine/v1beta/README.rst deleted file mode 100644 index 25f579284266..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Discoveryengine API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Discoveryengine API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/_static/custom.css b/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/conf.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/conf.py deleted file mode 100644 index 9852ef988546..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-cloud-discoveryengine documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-cloud-discoveryengine" -copyright = u"2023, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = 'en' - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-discoveryengine-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-cloud-discoveryengine.tex", - u"google-cloud-discoveryengine Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - root_doc, - "google-cloud-discoveryengine", - u"Google Cloud Discoveryengine Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-cloud-discoveryengine", - u"google-cloud-discoveryengine Documentation", - author, - "google-cloud-discoveryengine", - "GAPIC library for Google Cloud Discoveryengine API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/completion_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/completion_service.rst deleted file mode 100644 index 9e9b191d4bcb..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/completion_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -CompletionService ------------------------------------ - -.. automodule:: google.cloud.discoveryengine_v1beta.services.completion_service - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/conversational_search_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/conversational_search_service.rst deleted file mode 100644 index c66aac5cccba..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/conversational_search_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -ConversationalSearchService ---------------------------------------------- - -.. automodule:: google.cloud.discoveryengine_v1beta.services.conversational_search_service - :members: - :inherited-members: - -.. automodule:: google.cloud.discoveryengine_v1beta.services.conversational_search_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/document_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/document_service.rst deleted file mode 100644 index edc7b754e3ff..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/document_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -DocumentService ---------------------------------- - -.. automodule:: google.cloud.discoveryengine_v1beta.services.document_service - :members: - :inherited-members: - -.. automodule:: google.cloud.discoveryengine_v1beta.services.document_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/recommendation_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/recommendation_service.rst deleted file mode 100644 index 97c376350840..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/recommendation_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -RecommendationService ---------------------------------------- - -.. automodule:: google.cloud.discoveryengine_v1beta.services.recommendation_service - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/schema_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/schema_service.rst deleted file mode 100644 index abb2fd929203..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/schema_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -SchemaService -------------------------------- - -.. automodule:: google.cloud.discoveryengine_v1beta.services.schema_service - :members: - :inherited-members: - -.. automodule:: google.cloud.discoveryengine_v1beta.services.schema_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/search_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/search_service.rst deleted file mode 100644 index 5d3bbc22240d..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/search_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -SearchService -------------------------------- - -.. automodule:: google.cloud.discoveryengine_v1beta.services.search_service - :members: - :inherited-members: - -.. automodule:: google.cloud.discoveryengine_v1beta.services.search_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/services_.rst b/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/services_.rst deleted file mode 100644 index ad346c2c29fe..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/services_.rst +++ /dev/null @@ -1,12 +0,0 @@ -Services for Google Cloud Discoveryengine v1beta API -==================================================== -.. toctree:: - :maxdepth: 2 - - completion_service - conversational_search_service - document_service - recommendation_service - schema_service - search_service - user_event_service diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/types_.rst b/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/types_.rst deleted file mode 100644 index 7dbc3a11568c..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Discoveryengine v1beta API -================================================= - -.. automodule:: google.cloud.discoveryengine_v1beta.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/user_event_service.rst b/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/user_event_service.rst deleted file mode 100644 index fe6a6dc5fd95..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/discoveryengine_v1beta/user_event_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -UserEventService ----------------------------------- - -.. automodule:: google.cloud.discoveryengine_v1beta.services.user_event_service - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/index.rst b/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/index.rst deleted file mode 100644 index 35629474edc6..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - discoveryengine_v1beta/services - discoveryengine_v1beta/types diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine/__init__.py deleted file mode 100644 index 634b5649e939..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine/__init__.py +++ /dev/null @@ -1,175 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.cloud.discoveryengine import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.discoveryengine_v1beta.services.completion_service.client import CompletionServiceClient -from google.cloud.discoveryengine_v1beta.services.completion_service.async_client import CompletionServiceAsyncClient -from google.cloud.discoveryengine_v1beta.services.conversational_search_service.client import ConversationalSearchServiceClient -from google.cloud.discoveryengine_v1beta.services.conversational_search_service.async_client import ConversationalSearchServiceAsyncClient -from google.cloud.discoveryengine_v1beta.services.document_service.client import DocumentServiceClient -from google.cloud.discoveryengine_v1beta.services.document_service.async_client import DocumentServiceAsyncClient -from google.cloud.discoveryengine_v1beta.services.recommendation_service.client import RecommendationServiceClient -from google.cloud.discoveryengine_v1beta.services.recommendation_service.async_client import RecommendationServiceAsyncClient -from google.cloud.discoveryengine_v1beta.services.schema_service.client import SchemaServiceClient -from google.cloud.discoveryengine_v1beta.services.schema_service.async_client import SchemaServiceAsyncClient -from google.cloud.discoveryengine_v1beta.services.search_service.client import SearchServiceClient -from google.cloud.discoveryengine_v1beta.services.search_service.async_client import SearchServiceAsyncClient -from google.cloud.discoveryengine_v1beta.services.user_event_service.client import UserEventServiceClient -from google.cloud.discoveryengine_v1beta.services.user_event_service.async_client import UserEventServiceAsyncClient - -from google.cloud.discoveryengine_v1beta.types.common import CustomAttribute -from google.cloud.discoveryengine_v1beta.types.common import DoubleList -from google.cloud.discoveryengine_v1beta.types.common import Interval -from google.cloud.discoveryengine_v1beta.types.common import UserInfo -from google.cloud.discoveryengine_v1beta.types.completion_service import CompleteQueryRequest -from google.cloud.discoveryengine_v1beta.types.completion_service import CompleteQueryResponse -from google.cloud.discoveryengine_v1beta.types.conversation import Conversation -from google.cloud.discoveryengine_v1beta.types.conversation import ConversationContext -from google.cloud.discoveryengine_v1beta.types.conversation import ConversationMessage -from google.cloud.discoveryengine_v1beta.types.conversation import Reply -from google.cloud.discoveryengine_v1beta.types.conversation import TextInput -from google.cloud.discoveryengine_v1beta.types.conversational_search_service import ConverseConversationRequest -from google.cloud.discoveryengine_v1beta.types.conversational_search_service import ConverseConversationResponse -from google.cloud.discoveryengine_v1beta.types.conversational_search_service import CreateConversationRequest -from google.cloud.discoveryengine_v1beta.types.conversational_search_service import DeleteConversationRequest -from google.cloud.discoveryengine_v1beta.types.conversational_search_service import GetConversationRequest -from google.cloud.discoveryengine_v1beta.types.conversational_search_service import ListConversationsRequest -from google.cloud.discoveryengine_v1beta.types.conversational_search_service import ListConversationsResponse -from google.cloud.discoveryengine_v1beta.types.conversational_search_service import UpdateConversationRequest -from google.cloud.discoveryengine_v1beta.types.document import Document -from google.cloud.discoveryengine_v1beta.types.document_service import CreateDocumentRequest -from google.cloud.discoveryengine_v1beta.types.document_service import DeleteDocumentRequest -from google.cloud.discoveryengine_v1beta.types.document_service import GetDocumentRequest -from google.cloud.discoveryengine_v1beta.types.document_service import ListDocumentsRequest -from google.cloud.discoveryengine_v1beta.types.document_service import ListDocumentsResponse -from google.cloud.discoveryengine_v1beta.types.document_service import UpdateDocumentRequest -from google.cloud.discoveryengine_v1beta.types.import_config import BigQuerySource -from google.cloud.discoveryengine_v1beta.types.import_config import GcsSource -from google.cloud.discoveryengine_v1beta.types.import_config import ImportDocumentsMetadata -from google.cloud.discoveryengine_v1beta.types.import_config import ImportDocumentsRequest -from google.cloud.discoveryengine_v1beta.types.import_config import ImportDocumentsResponse -from google.cloud.discoveryengine_v1beta.types.import_config import ImportErrorConfig -from google.cloud.discoveryengine_v1beta.types.import_config import ImportUserEventsMetadata -from google.cloud.discoveryengine_v1beta.types.import_config import ImportUserEventsRequest -from google.cloud.discoveryengine_v1beta.types.import_config import ImportUserEventsResponse -from google.cloud.discoveryengine_v1beta.types.purge_config import PurgeDocumentsMetadata -from google.cloud.discoveryengine_v1beta.types.purge_config import PurgeDocumentsRequest -from google.cloud.discoveryengine_v1beta.types.purge_config import PurgeDocumentsResponse -from google.cloud.discoveryengine_v1beta.types.recommendation_service import RecommendRequest -from google.cloud.discoveryengine_v1beta.types.recommendation_service import RecommendResponse -from google.cloud.discoveryengine_v1beta.types.schema import Schema -from google.cloud.discoveryengine_v1beta.types.schema_service import CreateSchemaMetadata -from google.cloud.discoveryengine_v1beta.types.schema_service import CreateSchemaRequest -from google.cloud.discoveryengine_v1beta.types.schema_service import DeleteSchemaMetadata -from google.cloud.discoveryengine_v1beta.types.schema_service import DeleteSchemaRequest -from google.cloud.discoveryengine_v1beta.types.schema_service import GetSchemaRequest -from google.cloud.discoveryengine_v1beta.types.schema_service import ListSchemasRequest -from google.cloud.discoveryengine_v1beta.types.schema_service import ListSchemasResponse -from google.cloud.discoveryengine_v1beta.types.schema_service import UpdateSchemaMetadata -from google.cloud.discoveryengine_v1beta.types.schema_service import UpdateSchemaRequest -from google.cloud.discoveryengine_v1beta.types.search_service import SearchRequest -from google.cloud.discoveryengine_v1beta.types.search_service import SearchResponse -from google.cloud.discoveryengine_v1beta.types.user_event import CompletionInfo -from google.cloud.discoveryengine_v1beta.types.user_event import DocumentInfo -from google.cloud.discoveryengine_v1beta.types.user_event import MediaInfo -from google.cloud.discoveryengine_v1beta.types.user_event import PageInfo -from google.cloud.discoveryengine_v1beta.types.user_event import PanelInfo -from google.cloud.discoveryengine_v1beta.types.user_event import SearchInfo -from google.cloud.discoveryengine_v1beta.types.user_event import TransactionInfo -from google.cloud.discoveryengine_v1beta.types.user_event import UserEvent -from google.cloud.discoveryengine_v1beta.types.user_event_service import CollectUserEventRequest -from google.cloud.discoveryengine_v1beta.types.user_event_service import WriteUserEventRequest - -__all__ = ('CompletionServiceClient', - 'CompletionServiceAsyncClient', - 'ConversationalSearchServiceClient', - 'ConversationalSearchServiceAsyncClient', - 'DocumentServiceClient', - 'DocumentServiceAsyncClient', - 'RecommendationServiceClient', - 'RecommendationServiceAsyncClient', - 'SchemaServiceClient', - 'SchemaServiceAsyncClient', - 'SearchServiceClient', - 'SearchServiceAsyncClient', - 'UserEventServiceClient', - 'UserEventServiceAsyncClient', - 'CustomAttribute', - 'DoubleList', - 'Interval', - 'UserInfo', - 'CompleteQueryRequest', - 'CompleteQueryResponse', - 'Conversation', - 'ConversationContext', - 'ConversationMessage', - 'Reply', - 'TextInput', - 'ConverseConversationRequest', - 'ConverseConversationResponse', - 'CreateConversationRequest', - 'DeleteConversationRequest', - 'GetConversationRequest', - 'ListConversationsRequest', - 'ListConversationsResponse', - 'UpdateConversationRequest', - 'Document', - 'CreateDocumentRequest', - 'DeleteDocumentRequest', - 'GetDocumentRequest', - 'ListDocumentsRequest', - 'ListDocumentsResponse', - 'UpdateDocumentRequest', - 'BigQuerySource', - 'GcsSource', - 'ImportDocumentsMetadata', - 'ImportDocumentsRequest', - 'ImportDocumentsResponse', - 'ImportErrorConfig', - 'ImportUserEventsMetadata', - 'ImportUserEventsRequest', - 'ImportUserEventsResponse', - 'PurgeDocumentsMetadata', - 'PurgeDocumentsRequest', - 'PurgeDocumentsResponse', - 'RecommendRequest', - 'RecommendResponse', - 'Schema', - 'CreateSchemaMetadata', - 'CreateSchemaRequest', - 'DeleteSchemaMetadata', - 'DeleteSchemaRequest', - 'GetSchemaRequest', - 'ListSchemasRequest', - 'ListSchemasResponse', - 'UpdateSchemaMetadata', - 'UpdateSchemaRequest', - 'SearchRequest', - 'SearchResponse', - 'CompletionInfo', - 'DocumentInfo', - 'MediaInfo', - 'PageInfo', - 'PanelInfo', - 'SearchInfo', - 'TransactionInfo', - 'UserEvent', - 'CollectUserEventRequest', - 'WriteUserEventRequest', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine/gapic_version.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine/gapic_version.py deleted file mode 100644 index 360a0d13ebdd..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine/py.typed b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine/py.typed deleted file mode 100644 index 2ff6437cf473..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-discoveryengine package uses inline types. diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/__init__.py deleted file mode 100644 index d49951ee6fba..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/__init__.py +++ /dev/null @@ -1,176 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.cloud.discoveryengine_v1beta import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.completion_service import CompletionServiceClient -from .services.completion_service import CompletionServiceAsyncClient -from .services.conversational_search_service import ConversationalSearchServiceClient -from .services.conversational_search_service import ConversationalSearchServiceAsyncClient -from .services.document_service import DocumentServiceClient -from .services.document_service import DocumentServiceAsyncClient -from .services.recommendation_service import RecommendationServiceClient -from .services.recommendation_service import RecommendationServiceAsyncClient -from .services.schema_service import SchemaServiceClient -from .services.schema_service import SchemaServiceAsyncClient -from .services.search_service import SearchServiceClient -from .services.search_service import SearchServiceAsyncClient -from .services.user_event_service import UserEventServiceClient -from .services.user_event_service import UserEventServiceAsyncClient - -from .types.common import CustomAttribute -from .types.common import DoubleList -from .types.common import Interval -from .types.common import UserInfo -from .types.completion_service import CompleteQueryRequest -from .types.completion_service import CompleteQueryResponse -from .types.conversation import Conversation -from .types.conversation import ConversationContext -from .types.conversation import ConversationMessage -from .types.conversation import Reply -from .types.conversation import TextInput -from .types.conversational_search_service import ConverseConversationRequest -from .types.conversational_search_service import ConverseConversationResponse -from .types.conversational_search_service import CreateConversationRequest -from .types.conversational_search_service import DeleteConversationRequest -from .types.conversational_search_service import GetConversationRequest -from .types.conversational_search_service import ListConversationsRequest -from .types.conversational_search_service import ListConversationsResponse -from .types.conversational_search_service import UpdateConversationRequest -from .types.document import Document -from .types.document_service import CreateDocumentRequest -from .types.document_service import DeleteDocumentRequest -from .types.document_service import GetDocumentRequest -from .types.document_service import ListDocumentsRequest -from .types.document_service import ListDocumentsResponse -from .types.document_service import UpdateDocumentRequest -from .types.import_config import BigQuerySource -from .types.import_config import GcsSource -from .types.import_config import ImportDocumentsMetadata -from .types.import_config import ImportDocumentsRequest -from .types.import_config import ImportDocumentsResponse -from .types.import_config import ImportErrorConfig -from .types.import_config import ImportUserEventsMetadata -from .types.import_config import ImportUserEventsRequest -from .types.import_config import ImportUserEventsResponse -from .types.purge_config import PurgeDocumentsMetadata -from .types.purge_config import PurgeDocumentsRequest -from .types.purge_config import PurgeDocumentsResponse -from .types.recommendation_service import RecommendRequest -from .types.recommendation_service import RecommendResponse -from .types.schema import Schema -from .types.schema_service import CreateSchemaMetadata -from .types.schema_service import CreateSchemaRequest -from .types.schema_service import DeleteSchemaMetadata -from .types.schema_service import DeleteSchemaRequest -from .types.schema_service import GetSchemaRequest -from .types.schema_service import ListSchemasRequest -from .types.schema_service import ListSchemasResponse -from .types.schema_service import UpdateSchemaMetadata -from .types.schema_service import UpdateSchemaRequest -from .types.search_service import SearchRequest -from .types.search_service import SearchResponse -from .types.user_event import CompletionInfo -from .types.user_event import DocumentInfo -from .types.user_event import MediaInfo -from .types.user_event import PageInfo -from .types.user_event import PanelInfo -from .types.user_event import SearchInfo -from .types.user_event import TransactionInfo -from .types.user_event import UserEvent -from .types.user_event_service import CollectUserEventRequest -from .types.user_event_service import WriteUserEventRequest - -__all__ = ( - 'CompletionServiceAsyncClient', - 'ConversationalSearchServiceAsyncClient', - 'DocumentServiceAsyncClient', - 'RecommendationServiceAsyncClient', - 'SchemaServiceAsyncClient', - 'SearchServiceAsyncClient', - 'UserEventServiceAsyncClient', -'BigQuerySource', -'CollectUserEventRequest', -'CompleteQueryRequest', -'CompleteQueryResponse', -'CompletionInfo', -'CompletionServiceClient', -'Conversation', -'ConversationContext', -'ConversationMessage', -'ConversationalSearchServiceClient', -'ConverseConversationRequest', -'ConverseConversationResponse', -'CreateConversationRequest', -'CreateDocumentRequest', -'CreateSchemaMetadata', -'CreateSchemaRequest', -'CustomAttribute', -'DeleteConversationRequest', -'DeleteDocumentRequest', -'DeleteSchemaMetadata', -'DeleteSchemaRequest', -'Document', -'DocumentInfo', -'DocumentServiceClient', -'DoubleList', -'GcsSource', -'GetConversationRequest', -'GetDocumentRequest', -'GetSchemaRequest', -'ImportDocumentsMetadata', -'ImportDocumentsRequest', -'ImportDocumentsResponse', -'ImportErrorConfig', -'ImportUserEventsMetadata', -'ImportUserEventsRequest', -'ImportUserEventsResponse', -'Interval', -'ListConversationsRequest', -'ListConversationsResponse', -'ListDocumentsRequest', -'ListDocumentsResponse', -'ListSchemasRequest', -'ListSchemasResponse', -'MediaInfo', -'PageInfo', -'PanelInfo', -'PurgeDocumentsMetadata', -'PurgeDocumentsRequest', -'PurgeDocumentsResponse', -'RecommendRequest', -'RecommendResponse', -'RecommendationServiceClient', -'Reply', -'Schema', -'SchemaServiceClient', -'SearchInfo', -'SearchRequest', -'SearchResponse', -'SearchServiceClient', -'TextInput', -'TransactionInfo', -'UpdateConversationRequest', -'UpdateDocumentRequest', -'UpdateSchemaMetadata', -'UpdateSchemaRequest', -'UserEvent', -'UserEventServiceClient', -'UserInfo', -'WriteUserEventRequest', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/gapic_metadata.json b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/gapic_metadata.json deleted file mode 100644 index 88141f3bd79e..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/gapic_metadata.json +++ /dev/null @@ -1,502 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.discoveryengine_v1beta", - "protoPackage": "google.cloud.discoveryengine.v1beta", - "schema": "1.0", - "services": { - "CompletionService": { - "clients": { - "grpc": { - "libraryClient": "CompletionServiceClient", - "rpcs": { - "CompleteQuery": { - "methods": [ - "complete_query" - ] - } - } - }, - "grpc-async": { - "libraryClient": "CompletionServiceAsyncClient", - "rpcs": { - "CompleteQuery": { - "methods": [ - "complete_query" - ] - } - } - }, - "rest": { - "libraryClient": "CompletionServiceClient", - "rpcs": { - "CompleteQuery": { - "methods": [ - "complete_query" - ] - } - } - } - } - }, - "ConversationalSearchService": { - "clients": { - "grpc": { - "libraryClient": "ConversationalSearchServiceClient", - "rpcs": { - "ConverseConversation": { - "methods": [ - "converse_conversation" - ] - }, - "CreateConversation": { - "methods": [ - "create_conversation" - ] - }, - "DeleteConversation": { - "methods": [ - "delete_conversation" - ] - }, - "GetConversation": { - "methods": [ - "get_conversation" - ] - }, - "ListConversations": { - "methods": [ - "list_conversations" - ] - }, - "UpdateConversation": { - "methods": [ - "update_conversation" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ConversationalSearchServiceAsyncClient", - "rpcs": { - "ConverseConversation": { - "methods": [ - "converse_conversation" - ] - }, - "CreateConversation": { - "methods": [ - "create_conversation" - ] - }, - "DeleteConversation": { - "methods": [ - "delete_conversation" - ] - }, - "GetConversation": { - "methods": [ - "get_conversation" - ] - }, - "ListConversations": { - "methods": [ - "list_conversations" - ] - }, - "UpdateConversation": { - "methods": [ - "update_conversation" - ] - } - } - }, - "rest": { - "libraryClient": "ConversationalSearchServiceClient", - "rpcs": { - "ConverseConversation": { - "methods": [ - "converse_conversation" - ] - }, - "CreateConversation": { - "methods": [ - "create_conversation" - ] - }, - "DeleteConversation": { - "methods": [ - "delete_conversation" - ] - }, - "GetConversation": { - "methods": [ - "get_conversation" - ] - }, - "ListConversations": { - "methods": [ - "list_conversations" - ] - }, - "UpdateConversation": { - "methods": [ - "update_conversation" - ] - } - } - } - } - }, - "DocumentService": { - "clients": { - "grpc": { - "libraryClient": "DocumentServiceClient", - "rpcs": { - "CreateDocument": { - "methods": [ - "create_document" - ] - }, - "DeleteDocument": { - "methods": [ - "delete_document" - ] - }, - "GetDocument": { - "methods": [ - "get_document" - ] - }, - "ImportDocuments": { - "methods": [ - "import_documents" - ] - }, - "ListDocuments": { - "methods": [ - "list_documents" - ] - }, - "PurgeDocuments": { - "methods": [ - "purge_documents" - ] - }, - "UpdateDocument": { - "methods": [ - "update_document" - ] - } - } - }, - "grpc-async": { - "libraryClient": "DocumentServiceAsyncClient", - "rpcs": { - "CreateDocument": { - "methods": [ - "create_document" - ] - }, - "DeleteDocument": { - "methods": [ - "delete_document" - ] - }, - "GetDocument": { - "methods": [ - "get_document" - ] - }, - "ImportDocuments": { - "methods": [ - "import_documents" - ] - }, - "ListDocuments": { - "methods": [ - "list_documents" - ] - }, - "PurgeDocuments": { - "methods": [ - "purge_documents" - ] - }, - "UpdateDocument": { - "methods": [ - "update_document" - ] - } - } - }, - "rest": { - "libraryClient": "DocumentServiceClient", - "rpcs": { - "CreateDocument": { - "methods": [ - "create_document" - ] - }, - "DeleteDocument": { - "methods": [ - "delete_document" - ] - }, - "GetDocument": { - "methods": [ - "get_document" - ] - }, - "ImportDocuments": { - "methods": [ - "import_documents" - ] - }, - "ListDocuments": { - "methods": [ - "list_documents" - ] - }, - "PurgeDocuments": { - "methods": [ - "purge_documents" - ] - }, - "UpdateDocument": { - "methods": [ - "update_document" - ] - } - } - } - } - }, - "RecommendationService": { - "clients": { - "grpc": { - "libraryClient": "RecommendationServiceClient", - "rpcs": { - "Recommend": { - "methods": [ - "recommend" - ] - } - } - }, - "grpc-async": { - "libraryClient": "RecommendationServiceAsyncClient", - "rpcs": { - "Recommend": { - "methods": [ - "recommend" - ] - } - } - }, - "rest": { - "libraryClient": "RecommendationServiceClient", - "rpcs": { - "Recommend": { - "methods": [ - "recommend" - ] - } - } - } - } - }, - "SchemaService": { - "clients": { - "grpc": { - "libraryClient": "SchemaServiceClient", - "rpcs": { - "CreateSchema": { - "methods": [ - "create_schema" - ] - }, - "DeleteSchema": { - "methods": [ - "delete_schema" - ] - }, - "GetSchema": { - "methods": [ - "get_schema" - ] - }, - "ListSchemas": { - "methods": [ - "list_schemas" - ] - }, - "UpdateSchema": { - "methods": [ - "update_schema" - ] - } - } - }, - "grpc-async": { - "libraryClient": "SchemaServiceAsyncClient", - "rpcs": { - "CreateSchema": { - "methods": [ - "create_schema" - ] - }, - "DeleteSchema": { - "methods": [ - "delete_schema" - ] - }, - "GetSchema": { - "methods": [ - "get_schema" - ] - }, - "ListSchemas": { - "methods": [ - "list_schemas" - ] - }, - "UpdateSchema": { - "methods": [ - "update_schema" - ] - } - } - }, - "rest": { - "libraryClient": "SchemaServiceClient", - "rpcs": { - "CreateSchema": { - "methods": [ - "create_schema" - ] - }, - "DeleteSchema": { - "methods": [ - "delete_schema" - ] - }, - "GetSchema": { - "methods": [ - "get_schema" - ] - }, - "ListSchemas": { - "methods": [ - "list_schemas" - ] - }, - "UpdateSchema": { - "methods": [ - "update_schema" - ] - } - } - } - } - }, - "SearchService": { - "clients": { - "grpc": { - "libraryClient": "SearchServiceClient", - "rpcs": { - "Search": { - "methods": [ - "search" - ] - } - } - }, - "grpc-async": { - "libraryClient": "SearchServiceAsyncClient", - "rpcs": { - "Search": { - "methods": [ - "search" - ] - } - } - }, - "rest": { - "libraryClient": "SearchServiceClient", - "rpcs": { - "Search": { - "methods": [ - "search" - ] - } - } - } - } - }, - "UserEventService": { - "clients": { - "grpc": { - "libraryClient": "UserEventServiceClient", - "rpcs": { - "CollectUserEvent": { - "methods": [ - "collect_user_event" - ] - }, - "ImportUserEvents": { - "methods": [ - "import_user_events" - ] - }, - "WriteUserEvent": { - "methods": [ - "write_user_event" - ] - } - } - }, - "grpc-async": { - "libraryClient": "UserEventServiceAsyncClient", - "rpcs": { - "CollectUserEvent": { - "methods": [ - "collect_user_event" - ] - }, - "ImportUserEvents": { - "methods": [ - "import_user_events" - ] - }, - "WriteUserEvent": { - "methods": [ - "write_user_event" - ] - } - } - }, - "rest": { - "libraryClient": "UserEventServiceClient", - "rpcs": { - "CollectUserEvent": { - "methods": [ - "collect_user_event" - ] - }, - "ImportUserEvents": { - "methods": [ - "import_user_events" - ] - }, - "WriteUserEvent": { - "methods": [ - "write_user_event" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/gapic_version.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/gapic_version.py deleted file mode 100644 index 360a0d13ebdd..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/py.typed b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/py.typed deleted file mode 100644 index 2ff6437cf473..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-discoveryengine package uses inline types. diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/__init__.py deleted file mode 100644 index 89a37dc92c5a..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/__init__.py deleted file mode 100644 index 440cbfb40963..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import CompletionServiceClient -from .async_client import CompletionServiceAsyncClient - -__all__ = ( - 'CompletionServiceClient', - 'CompletionServiceAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/async_client.py deleted file mode 100644 index b2bd38ba29cf..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/async_client.py +++ /dev/null @@ -1,386 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.discoveryengine_v1beta import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.discoveryengine_v1beta.types import completion_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport -from .client import CompletionServiceClient - - -class CompletionServiceAsyncClient: - """Service for Auto-Completion.""" - - _client: CompletionServiceClient - - DEFAULT_ENDPOINT = CompletionServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = CompletionServiceClient.DEFAULT_MTLS_ENDPOINT - - data_store_path = staticmethod(CompletionServiceClient.data_store_path) - parse_data_store_path = staticmethod(CompletionServiceClient.parse_data_store_path) - common_billing_account_path = staticmethod(CompletionServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(CompletionServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(CompletionServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(CompletionServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(CompletionServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(CompletionServiceClient.parse_common_organization_path) - common_project_path = staticmethod(CompletionServiceClient.common_project_path) - parse_common_project_path = staticmethod(CompletionServiceClient.parse_common_project_path) - common_location_path = staticmethod(CompletionServiceClient.common_location_path) - parse_common_location_path = staticmethod(CompletionServiceClient.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: - CompletionServiceAsyncClient: The constructed client. - """ - return CompletionServiceClient.from_service_account_info.__func__(CompletionServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceAsyncClient: The constructed client. - """ - return CompletionServiceClient.from_service_account_file.__func__(CompletionServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return CompletionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> CompletionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CompletionServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(CompletionServiceClient).get_transport_class, type(CompletionServiceClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, CompletionServiceTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the completion 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 (Union[str, ~.CompletionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = CompletionServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def complete_query(self, - request: Optional[Union[completion_service.CompleteQueryRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> completion_service.CompleteQueryResponse: - r"""Completes the specified user input with keyword - suggestions. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - async def sample_complete_query(): - # Create a client - client = discoveryengine_v1beta.CompletionServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.CompleteQueryRequest( - data_store="data_store_value", - query="query_value", - ) - - # Make the request - response = await client.complete_query(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1beta.types.CompleteQueryRequest, dict]]): - The request object. Request message for - [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1beta.CompletionService.CompleteQuery] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1beta.types.CompleteQueryResponse: - Response message for - [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1beta.CompletionService.CompleteQuery] - method. - - """ - # Create or coerce a protobuf request object. - request = completion_service.CompleteQueryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.complete_query, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("data_store", request.data_store), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "CompletionServiceAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "CompletionServiceAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/client.py deleted file mode 100644 index c19b68b93438..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/client.py +++ /dev/null @@ -1,594 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.discoveryengine_v1beta import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.discoveryengine_v1beta.types import completion_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .transports.base import CompletionServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import CompletionServiceGrpcTransport -from .transports.grpc_asyncio import CompletionServiceGrpcAsyncIOTransport -from .transports.rest import CompletionServiceRestTransport - - -class CompletionServiceClientMeta(type): - """Metaclass for the CompletionService 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[CompletionServiceTransport]] - _transport_registry["grpc"] = CompletionServiceGrpcTransport - _transport_registry["grpc_asyncio"] = CompletionServiceGrpcAsyncIOTransport - _transport_registry["rest"] = CompletionServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[CompletionServiceTransport]: - """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 CompletionServiceClient(metaclass=CompletionServiceClientMeta): - """Service for Auto-Completion.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - CompletionServiceClient: 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: - CompletionServiceClient: 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) -> CompletionServiceTransport: - """Returns the transport used by the client instance. - - Returns: - CompletionServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def data_store_path(project: str,location: str,data_store: str,) -> str: - """Returns a fully-qualified data_store string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) - - @staticmethod - def parse_data_store_path(path: str) -> Dict[str,str]: - """Parses a data_store path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, CompletionServiceTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the completion 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 (Union[str, CompletionServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, CompletionServiceTransport): - # transport is a CompletionServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def complete_query(self, - request: Optional[Union[completion_service.CompleteQueryRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> completion_service.CompleteQueryResponse: - r"""Completes the specified user input with keyword - suggestions. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - def sample_complete_query(): - # Create a client - client = discoveryengine_v1beta.CompletionServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.CompleteQueryRequest( - data_store="data_store_value", - query="query_value", - ) - - # Make the request - response = client.complete_query(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1beta.types.CompleteQueryRequest, dict]): - The request object. Request message for - [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1beta.CompletionService.CompleteQuery] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1beta.types.CompleteQueryResponse: - Response message for - [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1beta.CompletionService.CompleteQuery] - method. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a completion_service.CompleteQueryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, completion_service.CompleteQueryRequest): - request = completion_service.CompleteQueryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.complete_query] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("data_store", request.data_store), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "CompletionServiceClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - - - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "CompletionServiceClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/__init__.py deleted file mode 100644 index f32ad4419b13..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import CompletionServiceTransport -from .grpc import CompletionServiceGrpcTransport -from .grpc_asyncio import CompletionServiceGrpcAsyncIOTransport -from .rest import CompletionServiceRestTransport -from .rest import CompletionServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[CompletionServiceTransport]] -_transport_registry['grpc'] = CompletionServiceGrpcTransport -_transport_registry['grpc_asyncio'] = CompletionServiceGrpcAsyncIOTransport -_transport_registry['rest'] = CompletionServiceRestTransport - -__all__ = ( - 'CompletionServiceTransport', - 'CompletionServiceGrpcTransport', - 'CompletionServiceGrpcAsyncIOTransport', - 'CompletionServiceRestTransport', - 'CompletionServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/base.py deleted file mode 100644 index 2828065a3195..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/base.py +++ /dev/null @@ -1,168 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.discoveryengine_v1beta import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.discoveryengine_v1beta.types import completion_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class CompletionServiceTransport(abc.ABC): - """Abstract transport class for CompletionService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'discoveryengine.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.complete_query: gapic_v1.method.wrap_method( - self.complete_query, - 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 complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - Union[ - completion_service.CompleteQueryResponse, - Awaitable[completion_service.CompleteQueryResponse] - ]]: - 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 kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'CompletionServiceTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/grpc.py deleted file mode 100644 index 497a5bdf3aca..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/grpc.py +++ /dev/null @@ -1,303 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.discoveryengine_v1beta.types import completion_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO - - -class CompletionServiceGrpcTransport(CompletionServiceTransport): - """gRPC backend transport for CompletionService. - - Service for Auto-Completion. - - 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - completion_service.CompleteQueryResponse]: - r"""Return a callable for the complete query method over gRPC. - - Completes the specified user input with keyword - suggestions. - - Returns: - Callable[[~.CompleteQueryRequest], - ~.CompleteQueryResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'complete_query' not in self._stubs: - self._stubs['complete_query'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.CompletionService/CompleteQuery', - request_serializer=completion_service.CompleteQueryRequest.serialize, - response_deserializer=completion_service.CompleteQueryResponse.deserialize, - ) - return self._stubs['complete_query'] - - def close(self): - self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'CompletionServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/grpc_asyncio.py deleted file mode 100644 index 1a09ba0df8f6..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,302 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.discoveryengine_v1beta.types import completion_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import CompletionServiceGrpcTransport - - -class CompletionServiceGrpcAsyncIOTransport(CompletionServiceTransport): - """gRPC AsyncIO backend transport for CompletionService. - - Service for Auto-Completion. - - 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - Awaitable[completion_service.CompleteQueryResponse]]: - r"""Return a callable for the complete query method over gRPC. - - Completes the specified user input with keyword - suggestions. - - Returns: - Callable[[~.CompleteQueryRequest], - Awaitable[~.CompleteQueryResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'complete_query' not in self._stubs: - self._stubs['complete_query'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.CompletionService/CompleteQuery', - request_serializer=completion_service.CompleteQueryRequest.serialize, - response_deserializer=completion_service.CompleteQueryResponse.deserialize, - ) - return self._stubs['complete_query'] - - def close(self): - return self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - -__all__ = ( - 'CompletionServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/rest.py deleted file mode 100644 index e36c91d06daa..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/completion_service/transports/rest.py +++ /dev/null @@ -1,566 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.cloud.location import locations_pb2 # type: ignore -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.discoveryengine_v1beta.types import completion_service -from google.longrunning import operations_pb2 # type: ignore - -from .base import CompletionServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class CompletionServiceRestInterceptor: - """Interceptor for CompletionService. - - 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 CompletionServiceRestTransport. - - .. code-block:: python - class MyCustomCompletionServiceInterceptor(CompletionServiceRestInterceptor): - def pre_complete_query(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_complete_query(self, response): - logging.log(f"Received response: {response}") - return response - - transport = CompletionServiceRestTransport(interceptor=MyCustomCompletionServiceInterceptor()) - client = CompletionServiceClient(transport=transport) - - - """ - def pre_complete_query(self, request: completion_service.CompleteQueryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[completion_service.CompleteQueryRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for complete_query - - Override in a subclass to manipulate the request or metadata - before they are sent to the CompletionService server. - """ - return request, metadata - - def post_complete_query(self, response: completion_service.CompleteQueryResponse) -> completion_service.CompleteQueryResponse: - """Post-rpc interceptor for complete_query - - Override in a subclass to manipulate the response - after it is returned by the CompletionService server but before - it is returned to user code. - """ - return response - - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the CompletionService 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 CompletionService server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the CompletionService 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 CompletionService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class CompletionServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: CompletionServiceRestInterceptor - - -class CompletionServiceRestTransport(CompletionServiceTransport): - """REST backend transport for CompletionService. - - Service for Auto-Completion. - - 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 = 'discoveryengine.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[CompletionServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or CompletionServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _CompleteQuery(CompletionServiceRestStub): - def __hash__(self): - return hash("CompleteQuery") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "query" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: completion_service.CompleteQueryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> completion_service.CompleteQueryResponse: - r"""Call the complete query method over HTTP. - - Args: - request (~.completion_service.CompleteQueryRequest): - The request object. Request message for - [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1beta.CompletionService.CompleteQuery] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.completion_service.CompleteQueryResponse: - Response message for - [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1beta.CompletionService.CompleteQuery] - method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{data_store=projects/*/locations/*/dataStores/*}:completeQuery', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{data_store=projects/*/locations/*/collections/*/dataStores/*}:completeQuery', - }, - ] - request, metadata = self._interceptor.pre_complete_query(request, metadata) - pb_request = completion_service.CompleteQueryRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = completion_service.CompleteQueryResponse() - pb_resp = completion_service.CompleteQueryResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_complete_query(resp) - return resp - - @property - def complete_query(self) -> Callable[ - [completion_service.CompleteQueryRequest], - completion_service.CompleteQueryResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CompleteQuery(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(CompletionServiceRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(CompletionServiceRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'CompletionServiceRestTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/__init__.py deleted file mode 100644 index 4bf42b241a8b..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import ConversationalSearchServiceClient -from .async_client import ConversationalSearchServiceAsyncClient - -__all__ = ( - 'ConversationalSearchServiceClient', - 'ConversationalSearchServiceAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/async_client.py deleted file mode 100644 index d1253ea0826d..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/async_client.py +++ /dev/null @@ -1,971 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.discoveryengine_v1beta import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.discoveryengine_v1beta.services.conversational_search_service import pagers -from google.cloud.discoveryengine_v1beta.types import conversation -from google.cloud.discoveryengine_v1beta.types import conversation as gcd_conversation -from google.cloud.discoveryengine_v1beta.types import conversational_search_service -from google.cloud.discoveryengine_v1beta.types import search_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import ConversationalSearchServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ConversationalSearchServiceGrpcAsyncIOTransport -from .client import ConversationalSearchServiceClient - - -class ConversationalSearchServiceAsyncClient: - """Service for conversational search.""" - - _client: ConversationalSearchServiceClient - - DEFAULT_ENDPOINT = ConversationalSearchServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ConversationalSearchServiceClient.DEFAULT_MTLS_ENDPOINT - - conversation_path = staticmethod(ConversationalSearchServiceClient.conversation_path) - parse_conversation_path = staticmethod(ConversationalSearchServiceClient.parse_conversation_path) - data_store_path = staticmethod(ConversationalSearchServiceClient.data_store_path) - parse_data_store_path = staticmethod(ConversationalSearchServiceClient.parse_data_store_path) - document_path = staticmethod(ConversationalSearchServiceClient.document_path) - parse_document_path = staticmethod(ConversationalSearchServiceClient.parse_document_path) - serving_config_path = staticmethod(ConversationalSearchServiceClient.serving_config_path) - parse_serving_config_path = staticmethod(ConversationalSearchServiceClient.parse_serving_config_path) - common_billing_account_path = staticmethod(ConversationalSearchServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ConversationalSearchServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ConversationalSearchServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(ConversationalSearchServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(ConversationalSearchServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(ConversationalSearchServiceClient.parse_common_organization_path) - common_project_path = staticmethod(ConversationalSearchServiceClient.common_project_path) - parse_common_project_path = staticmethod(ConversationalSearchServiceClient.parse_common_project_path) - common_location_path = staticmethod(ConversationalSearchServiceClient.common_location_path) - parse_common_location_path = staticmethod(ConversationalSearchServiceClient.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: - ConversationalSearchServiceAsyncClient: The constructed client. - """ - return ConversationalSearchServiceClient.from_service_account_info.__func__(ConversationalSearchServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ConversationalSearchServiceAsyncClient: The constructed client. - """ - return ConversationalSearchServiceClient.from_service_account_file.__func__(ConversationalSearchServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return ConversationalSearchServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ConversationalSearchServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ConversationalSearchServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ConversationalSearchServiceClient).get_transport_class, type(ConversationalSearchServiceClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ConversationalSearchServiceTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the conversational search 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 (Union[str, ~.ConversationalSearchServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = ConversationalSearchServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def converse_conversation(self, - request: Optional[Union[conversational_search_service.ConverseConversationRequest, dict]] = None, - *, - name: Optional[str] = None, - query: Optional[conversation.TextInput] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversational_search_service.ConverseConversationResponse: - r"""Converses 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 discoveryengine_v1beta - - async def sample_converse_conversation(): - # Create a client - client = discoveryengine_v1beta.ConversationalSearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.ConverseConversationRequest( - name="name_value", - ) - - # Make the request - response = await client.converse_conversation(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1beta.types.ConverseConversationRequest, dict]]): - The request object. Request message for - [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1beta.ConversationalSearchService.ConverseConversation] - method. - name (:class:`str`): - Required. The resource name of the Conversation to get. - Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}``. - Use - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/-`` - to activate auto session mode, which automatically - creates a new conversation inside a ConverseConversation - session. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - query (:class:`google.cloud.discoveryengine_v1beta.types.TextInput`): - Required. Current user input. - This corresponds to the ``query`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1beta.types.ConverseConversationResponse: - Response message for - [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1beta.ConversationalSearchService.ConverseConversation] - method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, query]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = conversational_search_service.ConverseConversationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if query is not None: - request.query = query - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.converse_conversation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_conversation(self, - request: Optional[Union[conversational_search_service.CreateConversationRequest, dict]] = None, - *, - parent: Optional[str] = None, - conversation: Optional[gcd_conversation.Conversation] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_conversation.Conversation: - r"""Creates a Conversation. - - If the - [Conversation][google.cloud.discoveryengine.v1beta.Conversation] - to create already exists, an ALREADY_EXISTS error is returned. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - async def sample_create_conversation(): - # Create a client - client = discoveryengine_v1beta.ConversationalSearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.CreateConversationRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_conversation(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1beta.types.CreateConversationRequest, dict]]): - The request object. Request for CreateConversation - method. - parent (:class:`str`): - Required. Full resource name of parent data store. - Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - conversation (:class:`google.cloud.discoveryengine_v1beta.types.Conversation`): - Required. The conversation to create. - This corresponds to the ``conversation`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1beta.types.Conversation: - External conversation proto - definition. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, conversation]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = conversational_search_service.CreateConversationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if conversation is not None: - request.conversation = conversation - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_conversation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_conversation(self, - request: Optional[Union[conversational_search_service.DeleteConversationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a Conversation. - - If the - [Conversation][google.cloud.discoveryengine.v1beta.Conversation] - to delete does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - async def sample_delete_conversation(): - # Create a client - client = discoveryengine_v1beta.ConversationalSearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.DeleteConversationRequest( - name="name_value", - ) - - # Make the request - await client.delete_conversation(request=request) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1beta.types.DeleteConversationRequest, dict]]): - The request object. Request for DeleteConversation - method. - name (:class:`str`): - Required. The resource name of the Conversation to - delete. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = conversational_search_service.DeleteConversationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_conversation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def update_conversation(self, - request: Optional[Union[conversational_search_service.UpdateConversationRequest, dict]] = None, - *, - conversation: Optional[gcd_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, str]] = (), - ) -> gcd_conversation.Conversation: - r"""Updates a Conversation. - - [Conversation][google.cloud.discoveryengine.v1beta.Conversation] - action type cannot be changed. If the - [Conversation][google.cloud.discoveryengine.v1beta.Conversation] - to update does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - async def sample_update_conversation(): - # Create a client - client = discoveryengine_v1beta.ConversationalSearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.UpdateConversationRequest( - ) - - # Make the request - response = await client.update_conversation(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1beta.types.UpdateConversationRequest, dict]]): - The request object. Request for UpdateConversation - method. - conversation (:class:`google.cloud.discoveryengine_v1beta.types.Conversation`): - Required. The Conversation to update. - 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`): - Indicates which fields in the provided - [Conversation][google.cloud.discoveryengine.v1beta.Conversation] - to update. The following are NOT supported: - - - [conversation.name][] - - If not set or empty, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1beta.types.Conversation: - External conversation proto - definition. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([conversation, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = conversational_search_service.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 = gapic_v1.method_async.wrap_method( - self._client._transport.update_conversation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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), - )), - ) - - # 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[conversational_search_service.GetConversationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation.Conversation: - r"""Gets 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 discoveryengine_v1beta - - async def sample_get_conversation(): - # Create a client - client = discoveryengine_v1beta.ConversationalSearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.GetConversationRequest( - name="name_value", - ) - - # Make the request - response = await client.get_conversation(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1beta.types.GetConversationRequest, dict]]): - The request object. Request for GetConversation method. - name (:class:`str`): - Required. The resource name of the Conversation to get. - Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1beta.types.Conversation: - External conversation proto - definition. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = conversational_search_service.GetConversationRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_conversation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_conversations(self, - request: Optional[Union[conversational_search_service.ListConversationsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListConversationsAsyncPager: - r"""Lists all Conversations by their parent - [DataStore][google.cloud.discoveryengine.v1beta.DataStore]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - async def sample_list_conversations(): - # Create a client - client = discoveryengine_v1beta.ConversationalSearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.ListConversationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversations(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1beta.types.ListConversationsRequest, dict]]): - The request object. Request for ListConversations method. - parent (:class:`str`): - Required. The data store resource name. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1beta.services.conversational_search_service.pagers.ListConversationsAsyncPager: - Response for ListConversations - method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = conversational_search_service.ListConversationsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_conversations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListConversationsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "ConversationalSearchServiceAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "ConversationalSearchServiceAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/client.py deleted file mode 100644 index ec51b16e7090..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/client.py +++ /dev/null @@ -1,1205 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.discoveryengine_v1beta import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.discoveryengine_v1beta.services.conversational_search_service import pagers -from google.cloud.discoveryengine_v1beta.types import conversation -from google.cloud.discoveryengine_v1beta.types import conversation as gcd_conversation -from google.cloud.discoveryengine_v1beta.types import conversational_search_service -from google.cloud.discoveryengine_v1beta.types import search_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import ConversationalSearchServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ConversationalSearchServiceGrpcTransport -from .transports.grpc_asyncio import ConversationalSearchServiceGrpcAsyncIOTransport -from .transports.rest import ConversationalSearchServiceRestTransport - - -class ConversationalSearchServiceClientMeta(type): - """Metaclass for the ConversationalSearchService 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[ConversationalSearchServiceTransport]] - _transport_registry["grpc"] = ConversationalSearchServiceGrpcTransport - _transport_registry["grpc_asyncio"] = ConversationalSearchServiceGrpcAsyncIOTransport - _transport_registry["rest"] = ConversationalSearchServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[ConversationalSearchServiceTransport]: - """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 ConversationalSearchServiceClient(metaclass=ConversationalSearchServiceClientMeta): - """Service for conversational search.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ConversationalSearchServiceClient: 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: - ConversationalSearchServiceClient: 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) -> ConversationalSearchServiceTransport: - """Returns the transport used by the client instance. - - Returns: - ConversationalSearchServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def conversation_path(project: str,location: str,data_store: str,conversation: str,) -> str: - """Returns a fully-qualified conversation string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}/conversations/{conversation}".format(project=project, location=location, data_store=data_store, conversation=conversation, ) - - @staticmethod - def parse_conversation_path(path: str) -> Dict[str,str]: - """Parses a conversation path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/conversations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def data_store_path(project: str,location: str,data_store: str,) -> str: - """Returns a fully-qualified data_store string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) - - @staticmethod - def parse_data_store_path(path: str) -> Dict[str,str]: - """Parses a data_store path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def document_path(project: str,location: str,data_store: str,branch: str,document: str,) -> str: - """Returns a fully-qualified document string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) - - @staticmethod - def parse_document_path(path: str) -> Dict[str,str]: - """Parses a document path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)/documents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def serving_config_path(project: str,location: str,data_store: str,serving_config: str,) -> str: - """Returns a fully-qualified serving_config string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}/servingConfigs/{serving_config}".format(project=project, location=location, data_store=data_store, serving_config=serving_config, ) - - @staticmethod - def parse_serving_config_path(path: str) -> Dict[str,str]: - """Parses a serving_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/servingConfigs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ConversationalSearchServiceTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the conversational search 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 (Union[str, ConversationalSearchServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ConversationalSearchServiceTransport): - # transport is a ConversationalSearchServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def converse_conversation(self, - request: Optional[Union[conversational_search_service.ConverseConversationRequest, dict]] = None, - *, - name: Optional[str] = None, - query: Optional[conversation.TextInput] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversational_search_service.ConverseConversationResponse: - r"""Converses 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 discoveryengine_v1beta - - def sample_converse_conversation(): - # Create a client - client = discoveryengine_v1beta.ConversationalSearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.ConverseConversationRequest( - name="name_value", - ) - - # Make the request - response = client.converse_conversation(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1beta.types.ConverseConversationRequest, dict]): - The request object. Request message for - [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1beta.ConversationalSearchService.ConverseConversation] - method. - name (str): - Required. The resource name of the Conversation to get. - Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}``. - Use - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/-`` - to activate auto session mode, which automatically - creates a new conversation inside a ConverseConversation - session. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - query (google.cloud.discoveryengine_v1beta.types.TextInput): - Required. Current user input. - This corresponds to the ``query`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1beta.types.ConverseConversationResponse: - Response message for - [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1beta.ConversationalSearchService.ConverseConversation] - method. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, query]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a conversational_search_service.ConverseConversationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, conversational_search_service.ConverseConversationRequest): - request = conversational_search_service.ConverseConversationRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if query is not None: - request.query = query - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.converse_conversation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_conversation(self, - request: Optional[Union[conversational_search_service.CreateConversationRequest, dict]] = None, - *, - parent: Optional[str] = None, - conversation: Optional[gcd_conversation.Conversation] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_conversation.Conversation: - r"""Creates a Conversation. - - If the - [Conversation][google.cloud.discoveryengine.v1beta.Conversation] - to create already exists, an ALREADY_EXISTS error is returned. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - def sample_create_conversation(): - # Create a client - client = discoveryengine_v1beta.ConversationalSearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.CreateConversationRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_conversation(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1beta.types.CreateConversationRequest, dict]): - The request object. Request for CreateConversation - method. - parent (str): - Required. Full resource name of parent data store. - Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - conversation (google.cloud.discoveryengine_v1beta.types.Conversation): - Required. The conversation to create. - This corresponds to the ``conversation`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1beta.types.Conversation: - External conversation proto - definition. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, conversation]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a conversational_search_service.CreateConversationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, conversational_search_service.CreateConversationRequest): - request = conversational_search_service.CreateConversationRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if conversation is not None: - request.conversation = conversation - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_conversation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_conversation(self, - request: Optional[Union[conversational_search_service.DeleteConversationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a Conversation. - - If the - [Conversation][google.cloud.discoveryengine.v1beta.Conversation] - to delete does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - def sample_delete_conversation(): - # Create a client - client = discoveryengine_v1beta.ConversationalSearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.DeleteConversationRequest( - name="name_value", - ) - - # Make the request - client.delete_conversation(request=request) - - Args: - request (Union[google.cloud.discoveryengine_v1beta.types.DeleteConversationRequest, dict]): - The request object. Request for DeleteConversation - method. - name (str): - Required. The resource name of the Conversation to - delete. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a conversational_search_service.DeleteConversationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, conversational_search_service.DeleteConversationRequest): - request = conversational_search_service.DeleteConversationRequest(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_conversation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def update_conversation(self, - request: Optional[Union[conversational_search_service.UpdateConversationRequest, dict]] = None, - *, - conversation: Optional[gcd_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, str]] = (), - ) -> gcd_conversation.Conversation: - r"""Updates a Conversation. - - [Conversation][google.cloud.discoveryengine.v1beta.Conversation] - action type cannot be changed. If the - [Conversation][google.cloud.discoveryengine.v1beta.Conversation] - to update does not exist, a NOT_FOUND error is returned. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - def sample_update_conversation(): - # Create a client - client = discoveryengine_v1beta.ConversationalSearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.UpdateConversationRequest( - ) - - # Make the request - response = client.update_conversation(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1beta.types.UpdateConversationRequest, dict]): - The request object. Request for UpdateConversation - method. - conversation (google.cloud.discoveryengine_v1beta.types.Conversation): - Required. The Conversation to update. - 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): - Indicates which fields in the provided - [Conversation][google.cloud.discoveryengine.v1beta.Conversation] - to update. The following are NOT supported: - - - [conversation.name][] - - If not set or empty, all supported fields are updated. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1beta.types.Conversation: - External conversation proto - definition. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([conversation, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a conversational_search_service.UpdateConversationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, conversational_search_service.UpdateConversationRequest): - request = conversational_search_service.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), - )), - ) - - # 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[conversational_search_service.GetConversationRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> conversation.Conversation: - r"""Gets 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 discoveryengine_v1beta - - def sample_get_conversation(): - # Create a client - client = discoveryengine_v1beta.ConversationalSearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.GetConversationRequest( - name="name_value", - ) - - # Make the request - response = client.get_conversation(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1beta.types.GetConversationRequest, dict]): - The request object. Request for GetConversation method. - name (str): - Required. The resource name of the Conversation to get. - Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1beta.types.Conversation: - External conversation proto - definition. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a conversational_search_service.GetConversationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, conversational_search_service.GetConversationRequest): - request = conversational_search_service.GetConversationRequest(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_conversation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_conversations(self, - request: Optional[Union[conversational_search_service.ListConversationsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListConversationsPager: - r"""Lists all Conversations by their parent - [DataStore][google.cloud.discoveryengine.v1beta.DataStore]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - def sample_list_conversations(): - # Create a client - client = discoveryengine_v1beta.ConversationalSearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.ListConversationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversations(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1beta.types.ListConversationsRequest, dict]): - The request object. Request for ListConversations method. - parent (str): - Required. The data store resource name. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1beta.services.conversational_search_service.pagers.ListConversationsPager: - Response for ListConversations - method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a conversational_search_service.ListConversationsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, conversational_search_service.ListConversationsRequest): - request = conversational_search_service.ListConversationsRequest(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_conversations] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListConversationsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "ConversationalSearchServiceClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - - - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "ConversationalSearchServiceClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/pagers.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/pagers.py deleted file mode 100644 index d378dd65b0f9..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.discoveryengine_v1beta.types import conversation -from google.cloud.discoveryengine_v1beta.types import conversational_search_service - - -class ListConversationsPager: - """A pager for iterating through ``list_conversations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.discoveryengine_v1beta.types.ListConversationsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``conversations`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListConversations`` requests and continue to iterate - through the ``conversations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.discoveryengine_v1beta.types.ListConversationsResponse` - 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[..., conversational_search_service.ListConversationsResponse], - request: conversational_search_service.ListConversationsRequest, - response: conversational_search_service.ListConversationsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.discoveryengine_v1beta.types.ListConversationsRequest): - The initial request object. - response (google.cloud.discoveryengine_v1beta.types.ListConversationsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = conversational_search_service.ListConversationsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[conversational_search_service.ListConversationsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[conversation.Conversation]: - for page in self.pages: - yield from page.conversations - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListConversationsAsyncPager: - """A pager for iterating through ``list_conversations`` requests. - - This class thinly wraps an initial - :class:`google.cloud.discoveryengine_v1beta.types.ListConversationsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``conversations`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListConversations`` requests and continue to iterate - through the ``conversations`` field on the - corresponding responses. - - All the usual :class:`google.cloud.discoveryengine_v1beta.types.ListConversationsResponse` - 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[conversational_search_service.ListConversationsResponse]], - request: conversational_search_service.ListConversationsRequest, - response: conversational_search_service.ListConversationsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.discoveryengine_v1beta.types.ListConversationsRequest): - The initial request object. - response (google.cloud.discoveryengine_v1beta.types.ListConversationsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = conversational_search_service.ListConversationsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[conversational_search_service.ListConversationsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[conversation.Conversation]: - async def async_generator(): - async for page in self.pages: - for response in page.conversations: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/__init__.py deleted file mode 100644 index f49b63e4b6cd..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import ConversationalSearchServiceTransport -from .grpc import ConversationalSearchServiceGrpcTransport -from .grpc_asyncio import ConversationalSearchServiceGrpcAsyncIOTransport -from .rest import ConversationalSearchServiceRestTransport -from .rest import ConversationalSearchServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ConversationalSearchServiceTransport]] -_transport_registry['grpc'] = ConversationalSearchServiceGrpcTransport -_transport_registry['grpc_asyncio'] = ConversationalSearchServiceGrpcAsyncIOTransport -_transport_registry['rest'] = ConversationalSearchServiceRestTransport - -__all__ = ( - 'ConversationalSearchServiceTransport', - 'ConversationalSearchServiceGrpcTransport', - 'ConversationalSearchServiceGrpcAsyncIOTransport', - 'ConversationalSearchServiceRestTransport', - 'ConversationalSearchServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/base.py deleted file mode 100644 index c567612a8840..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/base.py +++ /dev/null @@ -1,241 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.discoveryengine_v1beta import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.discoveryengine_v1beta.types import conversation -from google.cloud.discoveryengine_v1beta.types import conversation as gcd_conversation -from google.cloud.discoveryengine_v1beta.types import conversational_search_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class ConversationalSearchServiceTransport(abc.ABC): - """Abstract transport class for ConversationalSearchService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'discoveryengine.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.converse_conversation: gapic_v1.method.wrap_method( - self.converse_conversation, - default_timeout=None, - client_info=client_info, - ), - self.create_conversation: gapic_v1.method.wrap_method( - self.create_conversation, - default_timeout=None, - client_info=client_info, - ), - self.delete_conversation: gapic_v1.method.wrap_method( - self.delete_conversation, - 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, - client_info=client_info, - ), - self.list_conversations: gapic_v1.method.wrap_method( - self.list_conversations, - 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 converse_conversation(self) -> Callable[ - [conversational_search_service.ConverseConversationRequest], - Union[ - conversational_search_service.ConverseConversationResponse, - Awaitable[conversational_search_service.ConverseConversationResponse] - ]]: - raise NotImplementedError() - - @property - def create_conversation(self) -> Callable[ - [conversational_search_service.CreateConversationRequest], - Union[ - gcd_conversation.Conversation, - Awaitable[gcd_conversation.Conversation] - ]]: - raise NotImplementedError() - - @property - def delete_conversation(self) -> Callable[ - [conversational_search_service.DeleteConversationRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def update_conversation(self) -> Callable[ - [conversational_search_service.UpdateConversationRequest], - Union[ - gcd_conversation.Conversation, - Awaitable[gcd_conversation.Conversation] - ]]: - raise NotImplementedError() - - @property - def get_conversation(self) -> Callable[ - [conversational_search_service.GetConversationRequest], - Union[ - conversation.Conversation, - Awaitable[conversation.Conversation] - ]]: - raise NotImplementedError() - - @property - def list_conversations(self) -> Callable[ - [conversational_search_service.ListConversationsRequest], - Union[ - conversational_search_service.ListConversationsResponse, - Awaitable[conversational_search_service.ListConversationsResponse] - ]]: - 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 kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ConversationalSearchServiceTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/grpc.py deleted file mode 100644 index b311f3141b76..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/grpc.py +++ /dev/null @@ -1,449 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.discoveryengine_v1beta.types import conversation -from google.cloud.discoveryengine_v1beta.types import conversation as gcd_conversation -from google.cloud.discoveryengine_v1beta.types import conversational_search_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import ConversationalSearchServiceTransport, DEFAULT_CLIENT_INFO - - -class ConversationalSearchServiceGrpcTransport(ConversationalSearchServiceTransport): - """gRPC backend transport for ConversationalSearchService. - - Service for conversational search. - - 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def converse_conversation(self) -> Callable[ - [conversational_search_service.ConverseConversationRequest], - conversational_search_service.ConverseConversationResponse]: - r"""Return a callable for the converse conversation method over gRPC. - - Converses a conversation. - - Returns: - Callable[[~.ConverseConversationRequest], - ~.ConverseConversationResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'converse_conversation' not in self._stubs: - self._stubs['converse_conversation'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.ConversationalSearchService/ConverseConversation', - request_serializer=conversational_search_service.ConverseConversationRequest.serialize, - response_deserializer=conversational_search_service.ConverseConversationResponse.deserialize, - ) - return self._stubs['converse_conversation'] - - @property - def create_conversation(self) -> Callable[ - [conversational_search_service.CreateConversationRequest], - gcd_conversation.Conversation]: - r"""Return a callable for the create conversation method over gRPC. - - Creates a Conversation. - - If the - [Conversation][google.cloud.discoveryengine.v1beta.Conversation] - to create already exists, an ALREADY_EXISTS error is returned. - - Returns: - Callable[[~.CreateConversationRequest], - ~.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 'create_conversation' not in self._stubs: - self._stubs['create_conversation'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.ConversationalSearchService/CreateConversation', - request_serializer=conversational_search_service.CreateConversationRequest.serialize, - response_deserializer=gcd_conversation.Conversation.deserialize, - ) - return self._stubs['create_conversation'] - - @property - def delete_conversation(self) -> Callable[ - [conversational_search_service.DeleteConversationRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete conversation method over gRPC. - - Deletes a Conversation. - - If the - [Conversation][google.cloud.discoveryengine.v1beta.Conversation] - to delete does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.DeleteConversationRequest], - ~.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_conversation' not in self._stubs: - self._stubs['delete_conversation'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.ConversationalSearchService/DeleteConversation', - request_serializer=conversational_search_service.DeleteConversationRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_conversation'] - - @property - def update_conversation(self) -> Callable[ - [conversational_search_service.UpdateConversationRequest], - gcd_conversation.Conversation]: - r"""Return a callable for the update conversation method over gRPC. - - Updates a Conversation. - - [Conversation][google.cloud.discoveryengine.v1beta.Conversation] - action type cannot be changed. If the - [Conversation][google.cloud.discoveryengine.v1beta.Conversation] - to update does not exist, a NOT_FOUND error is returned. - - 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.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.ConversationalSearchService/UpdateConversation', - request_serializer=conversational_search_service.UpdateConversationRequest.serialize, - response_deserializer=gcd_conversation.Conversation.deserialize, - ) - return self._stubs['update_conversation'] - - @property - def get_conversation(self) -> Callable[ - [conversational_search_service.GetConversationRequest], - conversation.Conversation]: - r"""Return a callable for the get conversation method over gRPC. - - Gets a Conversation. - - Returns: - Callable[[~.GetConversationRequest], - ~.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 'get_conversation' not in self._stubs: - self._stubs['get_conversation'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.ConversationalSearchService/GetConversation', - request_serializer=conversational_search_service.GetConversationRequest.serialize, - response_deserializer=conversation.Conversation.deserialize, - ) - return self._stubs['get_conversation'] - - @property - def list_conversations(self) -> Callable[ - [conversational_search_service.ListConversationsRequest], - conversational_search_service.ListConversationsResponse]: - r"""Return a callable for the list conversations method over gRPC. - - Lists all Conversations by their parent - [DataStore][google.cloud.discoveryengine.v1beta.DataStore]. - - Returns: - Callable[[~.ListConversationsRequest], - ~.ListConversationsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_conversations' not in self._stubs: - self._stubs['list_conversations'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.ConversationalSearchService/ListConversations', - request_serializer=conversational_search_service.ListConversationsRequest.serialize, - response_deserializer=conversational_search_service.ListConversationsResponse.deserialize, - ) - return self._stubs['list_conversations'] - - def close(self): - self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ConversationalSearchServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/grpc_asyncio.py deleted file mode 100644 index b0bcfa494853..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,448 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.discoveryengine_v1beta.types import conversation -from google.cloud.discoveryengine_v1beta.types import conversation as gcd_conversation -from google.cloud.discoveryengine_v1beta.types import conversational_search_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import ConversationalSearchServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import ConversationalSearchServiceGrpcTransport - - -class ConversationalSearchServiceGrpcAsyncIOTransport(ConversationalSearchServiceTransport): - """gRPC AsyncIO backend transport for ConversationalSearchService. - - Service for conversational search. - - 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def converse_conversation(self) -> Callable[ - [conversational_search_service.ConverseConversationRequest], - Awaitable[conversational_search_service.ConverseConversationResponse]]: - r"""Return a callable for the converse conversation method over gRPC. - - Converses a conversation. - - Returns: - Callable[[~.ConverseConversationRequest], - Awaitable[~.ConverseConversationResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'converse_conversation' not in self._stubs: - self._stubs['converse_conversation'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.ConversationalSearchService/ConverseConversation', - request_serializer=conversational_search_service.ConverseConversationRequest.serialize, - response_deserializer=conversational_search_service.ConverseConversationResponse.deserialize, - ) - return self._stubs['converse_conversation'] - - @property - def create_conversation(self) -> Callable[ - [conversational_search_service.CreateConversationRequest], - Awaitable[gcd_conversation.Conversation]]: - r"""Return a callable for the create conversation method over gRPC. - - Creates a Conversation. - - If the - [Conversation][google.cloud.discoveryengine.v1beta.Conversation] - to create already exists, an ALREADY_EXISTS error is returned. - - Returns: - Callable[[~.CreateConversationRequest], - 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 'create_conversation' not in self._stubs: - self._stubs['create_conversation'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.ConversationalSearchService/CreateConversation', - request_serializer=conversational_search_service.CreateConversationRequest.serialize, - response_deserializer=gcd_conversation.Conversation.deserialize, - ) - return self._stubs['create_conversation'] - - @property - def delete_conversation(self) -> Callable[ - [conversational_search_service.DeleteConversationRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete conversation method over gRPC. - - Deletes a Conversation. - - If the - [Conversation][google.cloud.discoveryengine.v1beta.Conversation] - to delete does not exist, a NOT_FOUND error is returned. - - Returns: - Callable[[~.DeleteConversationRequest], - 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_conversation' not in self._stubs: - self._stubs['delete_conversation'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.ConversationalSearchService/DeleteConversation', - request_serializer=conversational_search_service.DeleteConversationRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_conversation'] - - @property - def update_conversation(self) -> Callable[ - [conversational_search_service.UpdateConversationRequest], - Awaitable[gcd_conversation.Conversation]]: - r"""Return a callable for the update conversation method over gRPC. - - Updates a Conversation. - - [Conversation][google.cloud.discoveryengine.v1beta.Conversation] - action type cannot be changed. If the - [Conversation][google.cloud.discoveryengine.v1beta.Conversation] - to update does not exist, a NOT_FOUND error is returned. - - 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.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.ConversationalSearchService/UpdateConversation', - request_serializer=conversational_search_service.UpdateConversationRequest.serialize, - response_deserializer=gcd_conversation.Conversation.deserialize, - ) - return self._stubs['update_conversation'] - - @property - def get_conversation(self) -> Callable[ - [conversational_search_service.GetConversationRequest], - Awaitable[conversation.Conversation]]: - r"""Return a callable for the get conversation method over gRPC. - - Gets a Conversation. - - Returns: - Callable[[~.GetConversationRequest], - 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 'get_conversation' not in self._stubs: - self._stubs['get_conversation'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.ConversationalSearchService/GetConversation', - request_serializer=conversational_search_service.GetConversationRequest.serialize, - response_deserializer=conversation.Conversation.deserialize, - ) - return self._stubs['get_conversation'] - - @property - def list_conversations(self) -> Callable[ - [conversational_search_service.ListConversationsRequest], - Awaitable[conversational_search_service.ListConversationsResponse]]: - r"""Return a callable for the list conversations method over gRPC. - - Lists all Conversations by their parent - [DataStore][google.cloud.discoveryengine.v1beta.DataStore]. - - Returns: - Callable[[~.ListConversationsRequest], - Awaitable[~.ListConversationsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_conversations' not in self._stubs: - self._stubs['list_conversations'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.ConversationalSearchService/ListConversations', - request_serializer=conversational_search_service.ListConversationsRequest.serialize, - response_deserializer=conversational_search_service.ListConversationsResponse.deserialize, - ) - return self._stubs['list_conversations'] - - def close(self): - return self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - -__all__ = ( - 'ConversationalSearchServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/rest.py deleted file mode 100644 index 687df749d8a3..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/conversational_search_service/transports/rest.py +++ /dev/null @@ -1,1156 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.cloud.location import locations_pb2 # type: ignore -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.discoveryengine_v1beta.types import conversation -from google.cloud.discoveryengine_v1beta.types import conversation as gcd_conversation -from google.cloud.discoveryengine_v1beta.types import conversational_search_service -from google.protobuf import empty_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from .base import ConversationalSearchServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class ConversationalSearchServiceRestInterceptor: - """Interceptor for ConversationalSearchService. - - 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 ConversationalSearchServiceRestTransport. - - .. code-block:: python - class MyCustomConversationalSearchServiceInterceptor(ConversationalSearchServiceRestInterceptor): - def pre_converse_conversation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_converse_conversation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_conversation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_conversation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_conversation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_conversation(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_conversation(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_conversations(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_conversations(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 = ConversationalSearchServiceRestTransport(interceptor=MyCustomConversationalSearchServiceInterceptor()) - client = ConversationalSearchServiceClient(transport=transport) - - - """ - def pre_converse_conversation(self, request: conversational_search_service.ConverseConversationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversational_search_service.ConverseConversationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for converse_conversation - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationalSearchService server. - """ - return request, metadata - - def post_converse_conversation(self, response: conversational_search_service.ConverseConversationResponse) -> conversational_search_service.ConverseConversationResponse: - """Post-rpc interceptor for converse_conversation - - Override in a subclass to manipulate the response - after it is returned by the ConversationalSearchService server but before - it is returned to user code. - """ - return response - def pre_create_conversation(self, request: conversational_search_service.CreateConversationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversational_search_service.CreateConversationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_conversation - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationalSearchService server. - """ - return request, metadata - - def post_create_conversation(self, response: gcd_conversation.Conversation) -> gcd_conversation.Conversation: - """Post-rpc interceptor for create_conversation - - Override in a subclass to manipulate the response - after it is returned by the ConversationalSearchService server but before - it is returned to user code. - """ - return response - def pre_delete_conversation(self, request: conversational_search_service.DeleteConversationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversational_search_service.DeleteConversationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_conversation - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationalSearchService server. - """ - return request, metadata - - def pre_get_conversation(self, request: conversational_search_service.GetConversationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversational_search_service.GetConversationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_conversation - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationalSearchService server. - """ - return request, metadata - - def post_get_conversation(self, response: conversation.Conversation) -> conversation.Conversation: - """Post-rpc interceptor for get_conversation - - Override in a subclass to manipulate the response - after it is returned by the ConversationalSearchService server but before - it is returned to user code. - """ - return response - def pre_list_conversations(self, request: conversational_search_service.ListConversationsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversational_search_service.ListConversationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_conversations - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationalSearchService server. - """ - return request, metadata - - def post_list_conversations(self, response: conversational_search_service.ListConversationsResponse) -> conversational_search_service.ListConversationsResponse: - """Post-rpc interceptor for list_conversations - - Override in a subclass to manipulate the response - after it is returned by the ConversationalSearchService server but before - it is returned to user code. - """ - return response - def pre_update_conversation(self, request: conversational_search_service.UpdateConversationRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[conversational_search_service.UpdateConversationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_conversation - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationalSearchService server. - """ - return request, metadata - - def post_update_conversation(self, response: gcd_conversation.Conversation) -> gcd_conversation.Conversation: - """Post-rpc interceptor for update_conversation - - Override in a subclass to manipulate the response - after it is returned by the ConversationalSearchService server but before - it is returned to user code. - """ - return response - - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationalSearchService 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 ConversationalSearchService server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the ConversationalSearchService 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 ConversationalSearchService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class ConversationalSearchServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: ConversationalSearchServiceRestInterceptor - - -class ConversationalSearchServiceRestTransport(ConversationalSearchServiceTransport): - """REST backend transport for ConversationalSearchService. - - Service for conversational search. - - 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 = 'discoveryengine.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[ConversationalSearchServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or ConversationalSearchServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _ConverseConversation(ConversationalSearchServiceRestStub): - def __hash__(self): - return hash("ConverseConversation") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversational_search_service.ConverseConversationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> conversational_search_service.ConverseConversationResponse: - r"""Call the converse conversation method over HTTP. - - Args: - request (~.conversational_search_service.ConverseConversationRequest): - The request object. Request message for - [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1beta.ConversationalSearchService.ConverseConversation] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.conversational_search_service.ConverseConversationResponse: - Response message for - [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1beta.ConversationalSearchService.ConverseConversation] - method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/conversations/*}:converse', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/conversations/*}:converse', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_converse_conversation(request, metadata) - pb_request = conversational_search_service.ConverseConversationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = conversational_search_service.ConverseConversationResponse() - pb_resp = conversational_search_service.ConverseConversationResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_converse_conversation(resp) - return resp - - class _CreateConversation(ConversationalSearchServiceRestStub): - def __hash__(self): - return hash("CreateConversation") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversational_search_service.CreateConversationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_conversation.Conversation: - r"""Call the create conversation method over HTTP. - - Args: - request (~.conversational_search_service.CreateConversationRequest): - The request object. Request for CreateConversation - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcd_conversation.Conversation: - External conversation proto - definition. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta/{parent=projects/*/locations/*/dataStores/*}/conversations', - 'body': 'conversation', - }, -{ - 'method': 'post', - 'uri': '/v1beta/{parent=projects/*/locations/*/collections/*/dataStores/*}/conversations', - 'body': 'conversation', - }, - ] - request, metadata = self._interceptor.pre_create_conversation(request, metadata) - pb_request = conversational_search_service.CreateConversationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_conversation.Conversation() - pb_resp = gcd_conversation.Conversation.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_conversation(resp) - return resp - - class _DeleteConversation(ConversationalSearchServiceRestStub): - def __hash__(self): - return hash("DeleteConversation") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversational_search_service.DeleteConversationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete conversation method over HTTP. - - Args: - request (~.conversational_search_service.DeleteConversationRequest): - The request object. Request for DeleteConversation - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/conversations/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/conversations/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_conversation(request, metadata) - pb_request = conversational_search_service.DeleteConversationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _GetConversation(ConversationalSearchServiceRestStub): - def __hash__(self): - return hash("GetConversation") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversational_search_service.GetConversationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> conversation.Conversation: - r"""Call the get conversation method over HTTP. - - Args: - request (~.conversational_search_service.GetConversationRequest): - The request object. Request for GetConversation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.conversation.Conversation: - External conversation proto - definition. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/conversations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/conversations/*}', - }, - ] - request, metadata = self._interceptor.pre_get_conversation(request, metadata) - pb_request = conversational_search_service.GetConversationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = conversation.Conversation() - pb_resp = conversation.Conversation.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_conversation(resp) - return resp - - class _ListConversations(ConversationalSearchServiceRestStub): - def __hash__(self): - return hash("ListConversations") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversational_search_service.ListConversationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> conversational_search_service.ListConversationsResponse: - r"""Call the list conversations method over HTTP. - - Args: - request (~.conversational_search_service.ListConversationsRequest): - The request object. Request for ListConversations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.conversational_search_service.ListConversationsResponse: - Response for ListConversations - method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{parent=projects/*/locations/*/dataStores/*}/conversations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{parent=projects/*/locations/*/collections/*/dataStores/*}/conversations', - }, - ] - request, metadata = self._interceptor.pre_list_conversations(request, metadata) - pb_request = conversational_search_service.ListConversationsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = conversational_search_service.ListConversationsResponse() - pb_resp = conversational_search_service.ListConversationsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_conversations(resp) - return resp - - class _UpdateConversation(ConversationalSearchServiceRestStub): - def __hash__(self): - return hash("UpdateConversation") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: conversational_search_service.UpdateConversationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_conversation.Conversation: - r"""Call the update conversation method over HTTP. - - Args: - request (~.conversational_search_service.UpdateConversationRequest): - The request object. Request for UpdateConversation - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcd_conversation.Conversation: - External conversation proto - definition. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1beta/{conversation.name=projects/*/locations/*/dataStores/*/conversations/*}', - 'body': 'conversation', - }, -{ - 'method': 'patch', - 'uri': '/v1beta/{conversation.name=projects/*/locations/*/collections/*/dataStores/*/conversations/*}', - 'body': 'conversation', - }, - ] - request, metadata = self._interceptor.pre_update_conversation(request, metadata) - pb_request = conversational_search_service.UpdateConversationRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_conversation.Conversation() - pb_resp = gcd_conversation.Conversation.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_conversation(resp) - return resp - - @property - def converse_conversation(self) -> Callable[ - [conversational_search_service.ConverseConversationRequest], - conversational_search_service.ConverseConversationResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ConverseConversation(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_conversation(self) -> Callable[ - [conversational_search_service.CreateConversationRequest], - gcd_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._CreateConversation(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_conversation(self) -> Callable[ - [conversational_search_service.DeleteConversationRequest], - 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._DeleteConversation(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_conversation(self) -> Callable[ - [conversational_search_service.GetConversationRequest], - 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._GetConversation(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_conversations(self) -> Callable[ - [conversational_search_service.ListConversationsRequest], - conversational_search_service.ListConversationsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListConversations(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_conversation(self) -> Callable[ - [conversational_search_service.UpdateConversationRequest], - gcd_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_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(ConversationalSearchServiceRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(ConversationalSearchServiceRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'ConversationalSearchServiceRestTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/__init__.py deleted file mode 100644 index e4f0b808a498..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import DocumentServiceClient -from .async_client import DocumentServiceAsyncClient - -__all__ = ( - 'DocumentServiceClient', - 'DocumentServiceAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/async_client.py deleted file mode 100644 index 11462d9f2f62..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/async_client.py +++ /dev/null @@ -1,1112 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.discoveryengine_v1beta import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.discoveryengine_v1beta.services.document_service import pagers -from google.cloud.discoveryengine_v1beta.types import document -from google.cloud.discoveryengine_v1beta.types import document as gcd_document -from google.cloud.discoveryengine_v1beta.types import document_service -from google.cloud.discoveryengine_v1beta.types import import_config -from google.cloud.discoveryengine_v1beta.types import purge_config -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from .transports.base import DocumentServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import DocumentServiceGrpcAsyncIOTransport -from .client import DocumentServiceClient - - -class DocumentServiceAsyncClient: - """Service for ingesting - [Document][google.cloud.discoveryengine.v1beta.Document] information - of the customer's website. - """ - - _client: DocumentServiceClient - - DEFAULT_ENDPOINT = DocumentServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = DocumentServiceClient.DEFAULT_MTLS_ENDPOINT - - branch_path = staticmethod(DocumentServiceClient.branch_path) - parse_branch_path = staticmethod(DocumentServiceClient.parse_branch_path) - document_path = staticmethod(DocumentServiceClient.document_path) - parse_document_path = staticmethod(DocumentServiceClient.parse_document_path) - common_billing_account_path = staticmethod(DocumentServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(DocumentServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(DocumentServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(DocumentServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(DocumentServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(DocumentServiceClient.parse_common_organization_path) - common_project_path = staticmethod(DocumentServiceClient.common_project_path) - parse_common_project_path = staticmethod(DocumentServiceClient.parse_common_project_path) - common_location_path = staticmethod(DocumentServiceClient.common_location_path) - parse_common_location_path = staticmethod(DocumentServiceClient.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: - DocumentServiceAsyncClient: The constructed client. - """ - return DocumentServiceClient.from_service_account_info.__func__(DocumentServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DocumentServiceAsyncClient: The constructed client. - """ - return DocumentServiceClient.from_service_account_file.__func__(DocumentServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return DocumentServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> DocumentServiceTransport: - """Returns the transport used by the client instance. - - Returns: - DocumentServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(DocumentServiceClient).get_transport_class, type(DocumentServiceClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, DocumentServiceTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the document 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 (Union[str, ~.DocumentServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = DocumentServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def get_document(self, - request: Optional[Union[document_service.GetDocumentRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document.Document: - r"""Gets a [Document][google.cloud.discoveryengine.v1beta.Document]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - async def sample_get_document(): - # Create a client - client = discoveryengine_v1beta.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.GetDocumentRequest( - name="name_value", - ) - - # Make the request - response = await client.get_document(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1beta.types.GetDocumentRequest, dict]]): - The request object. Request message for - [DocumentService.GetDocument][google.cloud.discoveryengine.v1beta.DocumentService.GetDocument] - method. - name (:class:`str`): - Required. Full resource name of - [Document][google.cloud.discoveryengine.v1beta.Document], - such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. - - If the caller does not have permission to access the - [Document][google.cloud.discoveryengine.v1beta.Document], - regardless of whether or not it exists, a - ``PERMISSION_DENIED`` error is returned. - - If the requested - [Document][google.cloud.discoveryengine.v1beta.Document] - does not exist, a ``NOT_FOUND`` error is returned. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1beta.types.Document: - Document captures all raw metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = document_service.GetDocumentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_document, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_documents(self, - request: Optional[Union[document_service.ListDocumentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDocumentsAsyncPager: - r"""Gets a list of - [Document][google.cloud.discoveryengine.v1beta.Document]s. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - async def sample_list_documents(): - # Create a client - client = discoveryengine_v1beta.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.ListDocumentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_documents(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1beta.types.ListDocumentsRequest, dict]]): - The request object. Request message for - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1beta.DocumentService.ListDocuments] - method. - parent (:class:`str`): - Required. The parent branch resource name, such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. - Use ``default_branch`` as the branch ID, to list - documents under the default branch. - - If the caller does not have permission to list - [Document][google.cloud.discoveryengine.v1beta.Document]s - under this branch, regardless of whether or not this - branch exists, a ``PERMISSION_DENIED`` error is - returned. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1beta.services.document_service.pagers.ListDocumentsAsyncPager: - Response message for - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1beta.DocumentService.ListDocuments] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = document_service.ListDocumentsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_documents, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListDocumentsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_document(self, - request: Optional[Union[document_service.CreateDocumentRequest, dict]] = None, - *, - parent: Optional[str] = None, - document: Optional[gcd_document.Document] = None, - document_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_document.Document: - r"""Creates a - [Document][google.cloud.discoveryengine.v1beta.Document]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - async def sample_create_document(): - # Create a client - client = discoveryengine_v1beta.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.CreateDocumentRequest( - parent="parent_value", - document_id="document_id_value", - ) - - # Make the request - response = await client.create_document(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1beta.types.CreateDocumentRequest, dict]]): - The request object. Request message for - [DocumentService.CreateDocument][google.cloud.discoveryengine.v1beta.DocumentService.CreateDocument] - method. - parent (:class:`str`): - Required. The parent resource name, such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - document (:class:`google.cloud.discoveryengine_v1beta.types.Document`): - Required. The - [Document][google.cloud.discoveryengine.v1beta.Document] - to create. - - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - document_id (:class:`str`): - Required. The ID to use for the - [Document][google.cloud.discoveryengine.v1beta.Document], - which will become the final component of the - [Document.name][google.cloud.discoveryengine.v1beta.Document.name]. - - If the caller does not have permission to create the - [Document][google.cloud.discoveryengine.v1beta.Document], - regardless of whether or not it exists, a - ``PERMISSION_DENIED`` error is returned. - - This field must be unique among all - [Document][google.cloud.discoveryengine.v1beta.Document]s - with the same - [parent][google.cloud.discoveryengine.v1beta.CreateDocumentRequest.parent]. - Otherwise, an ``ALREADY_EXISTS`` error is returned. - - This field must conform to - `RFC-1034 `__ - standard with a length limit of 63 characters. - Otherwise, an ``INVALID_ARGUMENT`` error is returned. - - This corresponds to the ``document_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1beta.types.Document: - Document captures all raw metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, document, document_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = document_service.CreateDocumentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if document is not None: - request.document = document - if document_id is not None: - request.document_id = document_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_document, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_document(self, - request: Optional[Union[document_service.UpdateDocumentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document.Document: - r"""Updates a - [Document][google.cloud.discoveryengine.v1beta.Document]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - async def sample_update_document(): - # Create a client - client = discoveryengine_v1beta.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.UpdateDocumentRequest( - ) - - # Make the request - response = await client.update_document(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1beta.types.UpdateDocumentRequest, dict]]): - The request object. Request message for - [DocumentService.UpdateDocument][google.cloud.discoveryengine.v1beta.DocumentService.UpdateDocument] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1beta.types.Document: - Document captures all raw metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - request = document_service.UpdateDocumentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_document, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("document.name", request.document.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_document(self, - request: Optional[Union[document_service.DeleteDocumentRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a - [Document][google.cloud.discoveryengine.v1beta.Document]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - async def sample_delete_document(): - # Create a client - client = discoveryengine_v1beta.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.DeleteDocumentRequest( - name="name_value", - ) - - # Make the request - await client.delete_document(request=request) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1beta.types.DeleteDocumentRequest, dict]]): - The request object. Request message for - [DocumentService.DeleteDocument][google.cloud.discoveryengine.v1beta.DocumentService.DeleteDocument] - method. - name (:class:`str`): - Required. Full resource name of - [Document][google.cloud.discoveryengine.v1beta.Document], - such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. - - If the caller does not have permission to delete the - [Document][google.cloud.discoveryengine.v1beta.Document], - regardless of whether or not it exists, a - ``PERMISSION_DENIED`` error is returned. - - If the - [Document][google.cloud.discoveryengine.v1beta.Document] - to delete does not exist, a ``NOT_FOUND`` error is - returned. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = document_service.DeleteDocumentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_document, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def import_documents(self, - request: Optional[Union[import_config.ImportDocumentsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Bulk import of multiple - [Document][google.cloud.discoveryengine.v1beta.Document]s. - Request processing may be synchronous. Non-existing items will - be created. - - Note: It is possible for a subset of the - [Document][google.cloud.discoveryengine.v1beta.Document]s to be - successfully updated. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - async def sample_import_documents(): - # Create a client - client = discoveryengine_v1beta.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.ImportDocumentsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.import_documents(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1beta.types.ImportDocumentsRequest, dict]]): - The request object. Request message for Import methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.discoveryengine_v1beta.types.ImportDocumentsResponse` Response of the - [ImportDocumentsRequest][google.cloud.discoveryengine.v1beta.ImportDocumentsRequest]. - If the long running operation is done, then this - message is returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - request = import_config.ImportDocumentsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_documents, - default_retry=retries.Retry( -initial=1.0,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=300.0, - ), - default_timeout=300.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - import_config.ImportDocumentsResponse, - metadata_type=import_config.ImportDocumentsMetadata, - ) - - # Done; return the response. - return response - - async def purge_documents(self, - request: Optional[Union[purge_config.PurgeDocumentsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Permanently deletes all selected - [Document][google.cloud.discoveryengine.v1beta.Document]s in a - branch. - - This process is asynchronous. Depending on the number of - [Document][google.cloud.discoveryengine.v1beta.Document]s to be - deleted, this operation can take hours to complete. Before the - delete operation completes, some - [Document][google.cloud.discoveryengine.v1beta.Document]s might - still be returned by - [DocumentService.GetDocument][google.cloud.discoveryengine.v1beta.DocumentService.GetDocument] - or - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1beta.DocumentService.ListDocuments]. - - To get a list of the - [Document][google.cloud.discoveryengine.v1beta.Document]s to be - deleted, set - [PurgeDocumentsRequest.force][google.cloud.discoveryengine.v1beta.PurgeDocumentsRequest.force] - to false. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - async def sample_purge_documents(): - # Create a client - client = discoveryengine_v1beta.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.PurgeDocumentsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_documents(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1beta.types.PurgeDocumentsRequest, dict]]): - The request object. Request message for - [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1beta.DocumentService.PurgeDocuments] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.discoveryengine_v1beta.types.PurgeDocumentsResponse` Response message for - [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1beta.DocumentService.PurgeDocuments] - method. If the long running operation is successfully - done, then this message is returned by the - google.longrunning.Operations.response field. - - """ - # Create or coerce a protobuf request object. - request = purge_config.PurgeDocumentsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.purge_documents, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - purge_config.PurgeDocumentsResponse, - metadata_type=purge_config.PurgeDocumentsMetadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "DocumentServiceAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "DocumentServiceAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/client.py deleted file mode 100644 index 828d1d7ba421..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/client.py +++ /dev/null @@ -1,1325 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.discoveryengine_v1beta import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.discoveryengine_v1beta.services.document_service import pagers -from google.cloud.discoveryengine_v1beta.types import document -from google.cloud.discoveryengine_v1beta.types import document as gcd_document -from google.cloud.discoveryengine_v1beta.types import document_service -from google.cloud.discoveryengine_v1beta.types import import_config -from google.cloud.discoveryengine_v1beta.types import purge_config -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from .transports.base import DocumentServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import DocumentServiceGrpcTransport -from .transports.grpc_asyncio import DocumentServiceGrpcAsyncIOTransport -from .transports.rest import DocumentServiceRestTransport - - -class DocumentServiceClientMeta(type): - """Metaclass for the DocumentService 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[DocumentServiceTransport]] - _transport_registry["grpc"] = DocumentServiceGrpcTransport - _transport_registry["grpc_asyncio"] = DocumentServiceGrpcAsyncIOTransport - _transport_registry["rest"] = DocumentServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[DocumentServiceTransport]: - """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 DocumentServiceClient(metaclass=DocumentServiceClientMeta): - """Service for ingesting - [Document][google.cloud.discoveryengine.v1beta.Document] information - of the customer's website. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - DocumentServiceClient: 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: - DocumentServiceClient: 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) -> DocumentServiceTransport: - """Returns the transport used by the client instance. - - Returns: - DocumentServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def branch_path(project: str,location: str,data_store: str,branch: str,) -> str: - """Returns a fully-qualified branch string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}".format(project=project, location=location, data_store=data_store, branch=branch, ) - - @staticmethod - def parse_branch_path(path: str) -> Dict[str,str]: - """Parses a branch path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def document_path(project: str,location: str,data_store: str,branch: str,document: str,) -> str: - """Returns a fully-qualified document string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) - - @staticmethod - def parse_document_path(path: str) -> Dict[str,str]: - """Parses a document path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)/documents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, DocumentServiceTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the document 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 (Union[str, DocumentServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, DocumentServiceTransport): - # transport is a DocumentServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def get_document(self, - request: Optional[Union[document_service.GetDocumentRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document.Document: - r"""Gets a [Document][google.cloud.discoveryengine.v1beta.Document]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - def sample_get_document(): - # Create a client - client = discoveryengine_v1beta.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.GetDocumentRequest( - name="name_value", - ) - - # Make the request - response = client.get_document(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1beta.types.GetDocumentRequest, dict]): - The request object. Request message for - [DocumentService.GetDocument][google.cloud.discoveryengine.v1beta.DocumentService.GetDocument] - method. - name (str): - Required. Full resource name of - [Document][google.cloud.discoveryengine.v1beta.Document], - such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. - - If the caller does not have permission to access the - [Document][google.cloud.discoveryengine.v1beta.Document], - regardless of whether or not it exists, a - ``PERMISSION_DENIED`` error is returned. - - If the requested - [Document][google.cloud.discoveryengine.v1beta.Document] - does not exist, a ``NOT_FOUND`` error is returned. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1beta.types.Document: - Document captures all raw metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a document_service.GetDocumentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, document_service.GetDocumentRequest): - request = document_service.GetDocumentRequest(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_document] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_documents(self, - request: Optional[Union[document_service.ListDocumentsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDocumentsPager: - r"""Gets a list of - [Document][google.cloud.discoveryengine.v1beta.Document]s. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - def sample_list_documents(): - # Create a client - client = discoveryengine_v1beta.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.ListDocumentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_documents(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1beta.types.ListDocumentsRequest, dict]): - The request object. Request message for - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1beta.DocumentService.ListDocuments] - method. - parent (str): - Required. The parent branch resource name, such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. - Use ``default_branch`` as the branch ID, to list - documents under the default branch. - - If the caller does not have permission to list - [Document][google.cloud.discoveryengine.v1beta.Document]s - under this branch, regardless of whether or not this - branch exists, a ``PERMISSION_DENIED`` error is - returned. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1beta.services.document_service.pagers.ListDocumentsPager: - Response message for - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1beta.DocumentService.ListDocuments] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a document_service.ListDocumentsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, document_service.ListDocumentsRequest): - request = document_service.ListDocumentsRequest(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_documents] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListDocumentsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_document(self, - request: Optional[Union[document_service.CreateDocumentRequest, dict]] = None, - *, - parent: Optional[str] = None, - document: Optional[gcd_document.Document] = None, - document_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_document.Document: - r"""Creates a - [Document][google.cloud.discoveryengine.v1beta.Document]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - def sample_create_document(): - # Create a client - client = discoveryengine_v1beta.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.CreateDocumentRequest( - parent="parent_value", - document_id="document_id_value", - ) - - # Make the request - response = client.create_document(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1beta.types.CreateDocumentRequest, dict]): - The request object. Request message for - [DocumentService.CreateDocument][google.cloud.discoveryengine.v1beta.DocumentService.CreateDocument] - method. - parent (str): - Required. The parent resource name, such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - document (google.cloud.discoveryengine_v1beta.types.Document): - Required. The - [Document][google.cloud.discoveryengine.v1beta.Document] - to create. - - This corresponds to the ``document`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - document_id (str): - Required. The ID to use for the - [Document][google.cloud.discoveryengine.v1beta.Document], - which will become the final component of the - [Document.name][google.cloud.discoveryengine.v1beta.Document.name]. - - If the caller does not have permission to create the - [Document][google.cloud.discoveryengine.v1beta.Document], - regardless of whether or not it exists, a - ``PERMISSION_DENIED`` error is returned. - - This field must be unique among all - [Document][google.cloud.discoveryengine.v1beta.Document]s - with the same - [parent][google.cloud.discoveryengine.v1beta.CreateDocumentRequest.parent]. - Otherwise, an ``ALREADY_EXISTS`` error is returned. - - This field must conform to - `RFC-1034 `__ - standard with a length limit of 63 characters. - Otherwise, an ``INVALID_ARGUMENT`` error is returned. - - This corresponds to the ``document_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1beta.types.Document: - Document captures all raw metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, document, document_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a document_service.CreateDocumentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, document_service.CreateDocumentRequest): - request = document_service.CreateDocumentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if document is not None: - request.document = document - if document_id is not None: - request.document_id = document_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_document] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_document(self, - request: Optional[Union[document_service.UpdateDocumentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> document.Document: - r"""Updates a - [Document][google.cloud.discoveryengine.v1beta.Document]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - def sample_update_document(): - # Create a client - client = discoveryengine_v1beta.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.UpdateDocumentRequest( - ) - - # Make the request - response = client.update_document(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1beta.types.UpdateDocumentRequest, dict]): - The request object. Request message for - [DocumentService.UpdateDocument][google.cloud.discoveryengine.v1beta.DocumentService.UpdateDocument] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1beta.types.Document: - Document captures all raw metadata - information of items to be recommended - or searched. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a document_service.UpdateDocumentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, document_service.UpdateDocumentRequest): - request = document_service.UpdateDocumentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_document] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("document.name", request.document.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_document(self, - request: Optional[Union[document_service.DeleteDocumentRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a - [Document][google.cloud.discoveryengine.v1beta.Document]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - def sample_delete_document(): - # Create a client - client = discoveryengine_v1beta.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.DeleteDocumentRequest( - name="name_value", - ) - - # Make the request - client.delete_document(request=request) - - Args: - request (Union[google.cloud.discoveryengine_v1beta.types.DeleteDocumentRequest, dict]): - The request object. Request message for - [DocumentService.DeleteDocument][google.cloud.discoveryengine.v1beta.DocumentService.DeleteDocument] - method. - name (str): - Required. Full resource name of - [Document][google.cloud.discoveryengine.v1beta.Document], - such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. - - If the caller does not have permission to delete the - [Document][google.cloud.discoveryengine.v1beta.Document], - regardless of whether or not it exists, a - ``PERMISSION_DENIED`` error is returned. - - If the - [Document][google.cloud.discoveryengine.v1beta.Document] - to delete does not exist, a ``NOT_FOUND`` error is - returned. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a document_service.DeleteDocumentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, document_service.DeleteDocumentRequest): - request = document_service.DeleteDocumentRequest(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_document] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - def import_documents(self, - request: Optional[Union[import_config.ImportDocumentsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Bulk import of multiple - [Document][google.cloud.discoveryengine.v1beta.Document]s. - Request processing may be synchronous. Non-existing items will - be created. - - Note: It is possible for a subset of the - [Document][google.cloud.discoveryengine.v1beta.Document]s to be - successfully updated. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - def sample_import_documents(): - # Create a client - client = discoveryengine_v1beta.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.ImportDocumentsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.import_documents(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1beta.types.ImportDocumentsRequest, dict]): - The request object. Request message for Import methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.discoveryengine_v1beta.types.ImportDocumentsResponse` Response of the - [ImportDocumentsRequest][google.cloud.discoveryengine.v1beta.ImportDocumentsRequest]. - If the long running operation is done, then this - message is returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a import_config.ImportDocumentsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, import_config.ImportDocumentsRequest): - request = import_config.ImportDocumentsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_documents] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - import_config.ImportDocumentsResponse, - metadata_type=import_config.ImportDocumentsMetadata, - ) - - # Done; return the response. - return response - - def purge_documents(self, - request: Optional[Union[purge_config.PurgeDocumentsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Permanently deletes all selected - [Document][google.cloud.discoveryengine.v1beta.Document]s in a - branch. - - This process is asynchronous. Depending on the number of - [Document][google.cloud.discoveryengine.v1beta.Document]s to be - deleted, this operation can take hours to complete. Before the - delete operation completes, some - [Document][google.cloud.discoveryengine.v1beta.Document]s might - still be returned by - [DocumentService.GetDocument][google.cloud.discoveryengine.v1beta.DocumentService.GetDocument] - or - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1beta.DocumentService.ListDocuments]. - - To get a list of the - [Document][google.cloud.discoveryengine.v1beta.Document]s to be - deleted, set - [PurgeDocumentsRequest.force][google.cloud.discoveryengine.v1beta.PurgeDocumentsRequest.force] - to false. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - def sample_purge_documents(): - # Create a client - client = discoveryengine_v1beta.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.PurgeDocumentsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_documents(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1beta.types.PurgeDocumentsRequest, dict]): - The request object. Request message for - [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1beta.DocumentService.PurgeDocuments] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.discoveryengine_v1beta.types.PurgeDocumentsResponse` Response message for - [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1beta.DocumentService.PurgeDocuments] - method. If the long running operation is successfully - done, then this message is returned by the - google.longrunning.Operations.response field. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a purge_config.PurgeDocumentsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, purge_config.PurgeDocumentsRequest): - request = purge_config.PurgeDocumentsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.purge_documents] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - purge_config.PurgeDocumentsResponse, - metadata_type=purge_config.PurgeDocumentsMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "DocumentServiceClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - - - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "DocumentServiceClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/pagers.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/pagers.py deleted file mode 100644 index f6dcb0a142ce..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.discoveryengine_v1beta.types import document -from google.cloud.discoveryengine_v1beta.types import document_service - - -class ListDocumentsPager: - """A pager for iterating through ``list_documents`` requests. - - This class thinly wraps an initial - :class:`google.cloud.discoveryengine_v1beta.types.ListDocumentsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``documents`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListDocuments`` requests and continue to iterate - through the ``documents`` field on the - corresponding responses. - - All the usual :class:`google.cloud.discoveryengine_v1beta.types.ListDocumentsResponse` - 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[..., document_service.ListDocumentsResponse], - request: document_service.ListDocumentsRequest, - response: document_service.ListDocumentsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.discoveryengine_v1beta.types.ListDocumentsRequest): - The initial request object. - response (google.cloud.discoveryengine_v1beta.types.ListDocumentsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = document_service.ListDocumentsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[document_service.ListDocumentsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[document.Document]: - for page in self.pages: - yield from page.documents - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListDocumentsAsyncPager: - """A pager for iterating through ``list_documents`` requests. - - This class thinly wraps an initial - :class:`google.cloud.discoveryengine_v1beta.types.ListDocumentsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``documents`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListDocuments`` requests and continue to iterate - through the ``documents`` field on the - corresponding responses. - - All the usual :class:`google.cloud.discoveryengine_v1beta.types.ListDocumentsResponse` - 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[document_service.ListDocumentsResponse]], - request: document_service.ListDocumentsRequest, - response: document_service.ListDocumentsResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.discoveryengine_v1beta.types.ListDocumentsRequest): - The initial request object. - response (google.cloud.discoveryengine_v1beta.types.ListDocumentsResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = document_service.ListDocumentsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[document_service.ListDocumentsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[document.Document]: - async def async_generator(): - async for page in self.pages: - for response in page.documents: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/__init__.py deleted file mode 100644 index fb08db02f32c..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import DocumentServiceTransport -from .grpc import DocumentServiceGrpcTransport -from .grpc_asyncio import DocumentServiceGrpcAsyncIOTransport -from .rest import DocumentServiceRestTransport -from .rest import DocumentServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[DocumentServiceTransport]] -_transport_registry['grpc'] = DocumentServiceGrpcTransport -_transport_registry['grpc_asyncio'] = DocumentServiceGrpcAsyncIOTransport -_transport_registry['rest'] = DocumentServiceRestTransport - -__all__ = ( - 'DocumentServiceTransport', - 'DocumentServiceGrpcTransport', - 'DocumentServiceGrpcAsyncIOTransport', - 'DocumentServiceRestTransport', - 'DocumentServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/base.py deleted file mode 100644 index d78ce78eb3cd..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/base.py +++ /dev/null @@ -1,269 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.discoveryengine_v1beta import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.discoveryengine_v1beta.types import document -from google.cloud.discoveryengine_v1beta.types import document as gcd_document -from google.cloud.discoveryengine_v1beta.types import document_service -from google.cloud.discoveryengine_v1beta.types import import_config -from google.cloud.discoveryengine_v1beta.types import purge_config -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class DocumentServiceTransport(abc.ABC): - """Abstract transport class for DocumentService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'discoveryengine.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.get_document: gapic_v1.method.wrap_method( - self.get_document, - default_timeout=None, - client_info=client_info, - ), - self.list_documents: gapic_v1.method.wrap_method( - self.list_documents, - default_timeout=None, - client_info=client_info, - ), - self.create_document: gapic_v1.method.wrap_method( - self.create_document, - default_timeout=None, - client_info=client_info, - ), - self.update_document: gapic_v1.method.wrap_method( - self.update_document, - default_timeout=None, - client_info=client_info, - ), - self.delete_document: gapic_v1.method.wrap_method( - self.delete_document, - default_timeout=None, - client_info=client_info, - ), - self.import_documents: gapic_v1.method.wrap_method( - self.import_documents, - default_retry=retries.Retry( -initial=1.0,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=300.0, - ), - default_timeout=300.0, - client_info=client_info, - ), - self.purge_documents: gapic_v1.method.wrap_method( - self.purge_documents, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def get_document(self) -> Callable[ - [document_service.GetDocumentRequest], - Union[ - document.Document, - Awaitable[document.Document] - ]]: - raise NotImplementedError() - - @property - def list_documents(self) -> Callable[ - [document_service.ListDocumentsRequest], - Union[ - document_service.ListDocumentsResponse, - Awaitable[document_service.ListDocumentsResponse] - ]]: - raise NotImplementedError() - - @property - def create_document(self) -> Callable[ - [document_service.CreateDocumentRequest], - Union[ - gcd_document.Document, - Awaitable[gcd_document.Document] - ]]: - raise NotImplementedError() - - @property - def update_document(self) -> Callable[ - [document_service.UpdateDocumentRequest], - Union[ - document.Document, - Awaitable[document.Document] - ]]: - raise NotImplementedError() - - @property - def delete_document(self) -> Callable[ - [document_service.DeleteDocumentRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def import_documents(self) -> Callable[ - [import_config.ImportDocumentsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def purge_documents(self) -> Callable[ - [purge_config.PurgeDocumentsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'DocumentServiceTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/grpc.py deleted file mode 100644 index 9328ff2b0bd4..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/grpc.py +++ /dev/null @@ -1,512 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.discoveryengine_v1beta.types import document -from google.cloud.discoveryengine_v1beta.types import document as gcd_document -from google.cloud.discoveryengine_v1beta.types import document_service -from google.cloud.discoveryengine_v1beta.types import import_config -from google.cloud.discoveryengine_v1beta.types import purge_config -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import DocumentServiceTransport, DEFAULT_CLIENT_INFO - - -class DocumentServiceGrpcTransport(DocumentServiceTransport): - """gRPC backend transport for DocumentService. - - Service for ingesting - [Document][google.cloud.discoveryengine.v1beta.Document] information - of the customer's website. - - 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def get_document(self) -> Callable[ - [document_service.GetDocumentRequest], - document.Document]: - r"""Return a callable for the get document method over gRPC. - - Gets a [Document][google.cloud.discoveryengine.v1beta.Document]. - - Returns: - Callable[[~.GetDocumentRequest], - ~.Document]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_document' not in self._stubs: - self._stubs['get_document'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.DocumentService/GetDocument', - request_serializer=document_service.GetDocumentRequest.serialize, - response_deserializer=document.Document.deserialize, - ) - return self._stubs['get_document'] - - @property - def list_documents(self) -> Callable[ - [document_service.ListDocumentsRequest], - document_service.ListDocumentsResponse]: - r"""Return a callable for the list documents method over gRPC. - - Gets a list of - [Document][google.cloud.discoveryengine.v1beta.Document]s. - - Returns: - Callable[[~.ListDocumentsRequest], - ~.ListDocumentsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_documents' not in self._stubs: - self._stubs['list_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.DocumentService/ListDocuments', - request_serializer=document_service.ListDocumentsRequest.serialize, - response_deserializer=document_service.ListDocumentsResponse.deserialize, - ) - return self._stubs['list_documents'] - - @property - def create_document(self) -> Callable[ - [document_service.CreateDocumentRequest], - gcd_document.Document]: - r"""Return a callable for the create document method over gRPC. - - Creates a - [Document][google.cloud.discoveryengine.v1beta.Document]. - - Returns: - Callable[[~.CreateDocumentRequest], - ~.Document]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_document' not in self._stubs: - self._stubs['create_document'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.DocumentService/CreateDocument', - request_serializer=document_service.CreateDocumentRequest.serialize, - response_deserializer=gcd_document.Document.deserialize, - ) - return self._stubs['create_document'] - - @property - def update_document(self) -> Callable[ - [document_service.UpdateDocumentRequest], - document.Document]: - r"""Return a callable for the update document method over gRPC. - - Updates a - [Document][google.cloud.discoveryengine.v1beta.Document]. - - Returns: - Callable[[~.UpdateDocumentRequest], - ~.Document]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_document' not in self._stubs: - self._stubs['update_document'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.DocumentService/UpdateDocument', - request_serializer=document_service.UpdateDocumentRequest.serialize, - response_deserializer=document.Document.deserialize, - ) - return self._stubs['update_document'] - - @property - def delete_document(self) -> Callable[ - [document_service.DeleteDocumentRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete document method over gRPC. - - Deletes a - [Document][google.cloud.discoveryengine.v1beta.Document]. - - Returns: - Callable[[~.DeleteDocumentRequest], - ~.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_document' not in self._stubs: - self._stubs['delete_document'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.DocumentService/DeleteDocument', - request_serializer=document_service.DeleteDocumentRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_document'] - - @property - def import_documents(self) -> Callable[ - [import_config.ImportDocumentsRequest], - operations_pb2.Operation]: - r"""Return a callable for the import documents method over gRPC. - - Bulk import of multiple - [Document][google.cloud.discoveryengine.v1beta.Document]s. - Request processing may be synchronous. Non-existing items will - be created. - - Note: It is possible for a subset of the - [Document][google.cloud.discoveryengine.v1beta.Document]s to be - successfully updated. - - Returns: - Callable[[~.ImportDocumentsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_documents' not in self._stubs: - self._stubs['import_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.DocumentService/ImportDocuments', - request_serializer=import_config.ImportDocumentsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_documents'] - - @property - def purge_documents(self) -> Callable[ - [purge_config.PurgeDocumentsRequest], - operations_pb2.Operation]: - r"""Return a callable for the purge documents method over gRPC. - - Permanently deletes all selected - [Document][google.cloud.discoveryengine.v1beta.Document]s in a - branch. - - This process is asynchronous. Depending on the number of - [Document][google.cloud.discoveryengine.v1beta.Document]s to be - deleted, this operation can take hours to complete. Before the - delete operation completes, some - [Document][google.cloud.discoveryengine.v1beta.Document]s might - still be returned by - [DocumentService.GetDocument][google.cloud.discoveryengine.v1beta.DocumentService.GetDocument] - or - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1beta.DocumentService.ListDocuments]. - - To get a list of the - [Document][google.cloud.discoveryengine.v1beta.Document]s to be - deleted, set - [PurgeDocumentsRequest.force][google.cloud.discoveryengine.v1beta.PurgeDocumentsRequest.force] - to false. - - Returns: - Callable[[~.PurgeDocumentsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'purge_documents' not in self._stubs: - self._stubs['purge_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.DocumentService/PurgeDocuments', - request_serializer=purge_config.PurgeDocumentsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['purge_documents'] - - def close(self): - self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'DocumentServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/grpc_asyncio.py deleted file mode 100644 index 3d575402cda1..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,511 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.discoveryengine_v1beta.types import document -from google.cloud.discoveryengine_v1beta.types import document as gcd_document -from google.cloud.discoveryengine_v1beta.types import document_service -from google.cloud.discoveryengine_v1beta.types import import_config -from google.cloud.discoveryengine_v1beta.types import purge_config -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import DocumentServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import DocumentServiceGrpcTransport - - -class DocumentServiceGrpcAsyncIOTransport(DocumentServiceTransport): - """gRPC AsyncIO backend transport for DocumentService. - - Service for ingesting - [Document][google.cloud.discoveryengine.v1beta.Document] information - of the customer's website. - - 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def get_document(self) -> Callable[ - [document_service.GetDocumentRequest], - Awaitable[document.Document]]: - r"""Return a callable for the get document method over gRPC. - - Gets a [Document][google.cloud.discoveryengine.v1beta.Document]. - - Returns: - Callable[[~.GetDocumentRequest], - Awaitable[~.Document]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_document' not in self._stubs: - self._stubs['get_document'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.DocumentService/GetDocument', - request_serializer=document_service.GetDocumentRequest.serialize, - response_deserializer=document.Document.deserialize, - ) - return self._stubs['get_document'] - - @property - def list_documents(self) -> Callable[ - [document_service.ListDocumentsRequest], - Awaitable[document_service.ListDocumentsResponse]]: - r"""Return a callable for the list documents method over gRPC. - - Gets a list of - [Document][google.cloud.discoveryengine.v1beta.Document]s. - - Returns: - Callable[[~.ListDocumentsRequest], - Awaitable[~.ListDocumentsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_documents' not in self._stubs: - self._stubs['list_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.DocumentService/ListDocuments', - request_serializer=document_service.ListDocumentsRequest.serialize, - response_deserializer=document_service.ListDocumentsResponse.deserialize, - ) - return self._stubs['list_documents'] - - @property - def create_document(self) -> Callable[ - [document_service.CreateDocumentRequest], - Awaitable[gcd_document.Document]]: - r"""Return a callable for the create document method over gRPC. - - Creates a - [Document][google.cloud.discoveryengine.v1beta.Document]. - - Returns: - Callable[[~.CreateDocumentRequest], - Awaitable[~.Document]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_document' not in self._stubs: - self._stubs['create_document'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.DocumentService/CreateDocument', - request_serializer=document_service.CreateDocumentRequest.serialize, - response_deserializer=gcd_document.Document.deserialize, - ) - return self._stubs['create_document'] - - @property - def update_document(self) -> Callable[ - [document_service.UpdateDocumentRequest], - Awaitable[document.Document]]: - r"""Return a callable for the update document method over gRPC. - - Updates a - [Document][google.cloud.discoveryengine.v1beta.Document]. - - Returns: - Callable[[~.UpdateDocumentRequest], - Awaitable[~.Document]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_document' not in self._stubs: - self._stubs['update_document'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.DocumentService/UpdateDocument', - request_serializer=document_service.UpdateDocumentRequest.serialize, - response_deserializer=document.Document.deserialize, - ) - return self._stubs['update_document'] - - @property - def delete_document(self) -> Callable[ - [document_service.DeleteDocumentRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete document method over gRPC. - - Deletes a - [Document][google.cloud.discoveryengine.v1beta.Document]. - - Returns: - Callable[[~.DeleteDocumentRequest], - 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_document' not in self._stubs: - self._stubs['delete_document'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.DocumentService/DeleteDocument', - request_serializer=document_service.DeleteDocumentRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_document'] - - @property - def import_documents(self) -> Callable[ - [import_config.ImportDocumentsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import documents method over gRPC. - - Bulk import of multiple - [Document][google.cloud.discoveryengine.v1beta.Document]s. - Request processing may be synchronous. Non-existing items will - be created. - - Note: It is possible for a subset of the - [Document][google.cloud.discoveryengine.v1beta.Document]s to be - successfully updated. - - Returns: - Callable[[~.ImportDocumentsRequest], - 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 'import_documents' not in self._stubs: - self._stubs['import_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.DocumentService/ImportDocuments', - request_serializer=import_config.ImportDocumentsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_documents'] - - @property - def purge_documents(self) -> Callable[ - [purge_config.PurgeDocumentsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the purge documents method over gRPC. - - Permanently deletes all selected - [Document][google.cloud.discoveryengine.v1beta.Document]s in a - branch. - - This process is asynchronous. Depending on the number of - [Document][google.cloud.discoveryengine.v1beta.Document]s to be - deleted, this operation can take hours to complete. Before the - delete operation completes, some - [Document][google.cloud.discoveryengine.v1beta.Document]s might - still be returned by - [DocumentService.GetDocument][google.cloud.discoveryengine.v1beta.DocumentService.GetDocument] - or - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1beta.DocumentService.ListDocuments]. - - To get a list of the - [Document][google.cloud.discoveryengine.v1beta.Document]s to be - deleted, set - [PurgeDocumentsRequest.force][google.cloud.discoveryengine.v1beta.PurgeDocumentsRequest.force] - to false. - - Returns: - Callable[[~.PurgeDocumentsRequest], - 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 'purge_documents' not in self._stubs: - self._stubs['purge_documents'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.DocumentService/PurgeDocuments', - request_serializer=purge_config.PurgeDocumentsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['purge_documents'] - - def close(self): - return self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - -__all__ = ( - 'DocumentServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/rest.py deleted file mode 100644 index 4d4937514e59..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/document_service/transports/rest.py +++ /dev/null @@ -1,1429 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.cloud.location import locations_pb2 # type: ignore -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.discoveryengine_v1beta.types import document -from google.cloud.discoveryengine_v1beta.types import document as gcd_document -from google.cloud.discoveryengine_v1beta.types import document_service -from google.cloud.discoveryengine_v1beta.types import import_config -from google.cloud.discoveryengine_v1beta.types import purge_config -from google.protobuf import empty_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from .base import DocumentServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class DocumentServiceRestInterceptor: - """Interceptor for DocumentService. - - 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 DocumentServiceRestTransport. - - .. code-block:: python - class MyCustomDocumentServiceInterceptor(DocumentServiceRestInterceptor): - def pre_create_document(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_document(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_document(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_document(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_document(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_import_documents(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_import_documents(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_documents(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_documents(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_purge_documents(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_purge_documents(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_document(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_document(self, response): - logging.log(f"Received response: {response}") - return response - - transport = DocumentServiceRestTransport(interceptor=MyCustomDocumentServiceInterceptor()) - client = DocumentServiceClient(transport=transport) - - - """ - def pre_create_document(self, request: document_service.CreateDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_service.CreateDocumentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_document - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService server. - """ - return request, metadata - - def post_create_document(self, response: gcd_document.Document) -> gcd_document.Document: - """Post-rpc interceptor for create_document - - Override in a subclass to manipulate the response - after it is returned by the DocumentService server but before - it is returned to user code. - """ - return response - def pre_delete_document(self, request: document_service.DeleteDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_service.DeleteDocumentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_document - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService server. - """ - return request, metadata - - def pre_get_document(self, request: document_service.GetDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_service.GetDocumentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_document - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService server. - """ - return request, metadata - - def post_get_document(self, response: document.Document) -> document.Document: - """Post-rpc interceptor for get_document - - Override in a subclass to manipulate the response - after it is returned by the DocumentService server but before - it is returned to user code. - """ - return response - def pre_import_documents(self, request: import_config.ImportDocumentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[import_config.ImportDocumentsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for import_documents - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService server. - """ - return request, metadata - - def post_import_documents(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for import_documents - - Override in a subclass to manipulate the response - after it is returned by the DocumentService server but before - it is returned to user code. - """ - return response - def pre_list_documents(self, request: document_service.ListDocumentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_service.ListDocumentsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_documents - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService server. - """ - return request, metadata - - def post_list_documents(self, response: document_service.ListDocumentsResponse) -> document_service.ListDocumentsResponse: - """Post-rpc interceptor for list_documents - - Override in a subclass to manipulate the response - after it is returned by the DocumentService server but before - it is returned to user code. - """ - return response - def pre_purge_documents(self, request: purge_config.PurgeDocumentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[purge_config.PurgeDocumentsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for purge_documents - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService server. - """ - return request, metadata - - def post_purge_documents(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for purge_documents - - Override in a subclass to manipulate the response - after it is returned by the DocumentService server but before - it is returned to user code. - """ - return response - def pre_update_document(self, request: document_service.UpdateDocumentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[document_service.UpdateDocumentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_document - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService server. - """ - return request, metadata - - def post_update_document(self, response: document.Document) -> document.Document: - """Post-rpc interceptor for update_document - - Override in a subclass to manipulate the response - after it is returned by the DocumentService server but before - it is returned to user code. - """ - return response - - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService 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 DocumentService server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the DocumentService 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 DocumentService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class DocumentServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: DocumentServiceRestInterceptor - - -class DocumentServiceRestTransport(DocumentServiceTransport): - """REST backend transport for DocumentService. - - Service for ingesting - [Document][google.cloud.discoveryengine.v1beta.Document] information - of the customer's website. - - 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 = 'discoveryengine.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[DocumentServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or DocumentServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*}/operations', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1beta") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _CreateDocument(DocumentServiceRestStub): - def __hash__(self): - return hash("CreateDocument") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "documentId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_service.CreateDocumentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_document.Document: - r"""Call the create document method over HTTP. - - Args: - request (~.document_service.CreateDocumentRequest): - The request object. Request message for - [DocumentService.CreateDocument][google.cloud.discoveryengine.v1beta.DocumentService.CreateDocument] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcd_document.Document: - Document captures all raw metadata - information of items to be recommended - or searched. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta/{parent=projects/*/locations/*/dataStores/*/branches/*}/documents', - 'body': 'document', - }, -{ - 'method': 'post', - 'uri': '/v1beta/{parent=projects/*/locations/*/collections/*/dataStores/*/branches/*}/documents', - 'body': 'document', - }, - ] - request, metadata = self._interceptor.pre_create_document(request, metadata) - pb_request = document_service.CreateDocumentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = gcd_document.Document() - pb_resp = gcd_document.Document.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_document(resp) - return resp - - class _DeleteDocument(DocumentServiceRestStub): - def __hash__(self): - return hash("DeleteDocument") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_service.DeleteDocumentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete document method over HTTP. - - Args: - request (~.document_service.DeleteDocumentRequest): - The request object. Request message for - [DocumentService.DeleteDocument][google.cloud.discoveryengine.v1beta.DocumentService.DeleteDocument] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/documents/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/documents/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_document(request, metadata) - pb_request = document_service.DeleteDocumentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _GetDocument(DocumentServiceRestStub): - def __hash__(self): - return hash("GetDocument") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_service.GetDocumentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document.Document: - r"""Call the get document method over HTTP. - - Args: - request (~.document_service.GetDocumentRequest): - The request object. Request message for - [DocumentService.GetDocument][google.cloud.discoveryengine.v1beta.DocumentService.GetDocument] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.document.Document: - Document captures all raw metadata - information of items to be recommended - or searched. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/documents/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/documents/*}', - }, - ] - request, metadata = self._interceptor.pre_get_document(request, metadata) - pb_request = document_service.GetDocumentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document.Document() - pb_resp = document.Document.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_document(resp) - return resp - - class _ImportDocuments(DocumentServiceRestStub): - def __hash__(self): - return hash("ImportDocuments") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: import_config.ImportDocumentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the import documents method over HTTP. - - Args: - request (~.import_config.ImportDocumentsRequest): - The request object. Request message for Import methods. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta/{parent=projects/*/locations/*/dataStores/*/branches/*}/documents:import', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1beta/{parent=projects/*/locations/*/collections/*/dataStores/*/branches/*}/documents:import', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_import_documents(request, metadata) - pb_request = import_config.ImportDocumentsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_import_documents(resp) - return resp - - class _ListDocuments(DocumentServiceRestStub): - def __hash__(self): - return hash("ListDocuments") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_service.ListDocumentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document_service.ListDocumentsResponse: - r"""Call the list documents method over HTTP. - - Args: - request (~.document_service.ListDocumentsRequest): - The request object. Request message for - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1beta.DocumentService.ListDocuments] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.document_service.ListDocumentsResponse: - Response message for - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1beta.DocumentService.ListDocuments] - method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{parent=projects/*/locations/*/dataStores/*/branches/*}/documents', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{parent=projects/*/locations/*/collections/*/dataStores/*/branches/*}/documents', - }, - ] - request, metadata = self._interceptor.pre_list_documents(request, metadata) - pb_request = document_service.ListDocumentsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document_service.ListDocumentsResponse() - pb_resp = document_service.ListDocumentsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_documents(resp) - return resp - - class _PurgeDocuments(DocumentServiceRestStub): - def __hash__(self): - return hash("PurgeDocuments") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: purge_config.PurgeDocumentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the purge documents method over HTTP. - - Args: - request (~.purge_config.PurgeDocumentsRequest): - The request object. Request message for - [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1beta.DocumentService.PurgeDocuments] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta/{parent=projects/*/locations/*/dataStores/*/branches/*}/documents:purge', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1beta/{parent=projects/*/locations/*/collections/*/dataStores/*/branches/*}/documents:purge', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_purge_documents(request, metadata) - pb_request = purge_config.PurgeDocumentsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_purge_documents(resp) - return resp - - class _UpdateDocument(DocumentServiceRestStub): - def __hash__(self): - return hash("UpdateDocument") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: document_service.UpdateDocumentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> document.Document: - r"""Call the update document method over HTTP. - - Args: - request (~.document_service.UpdateDocumentRequest): - The request object. Request message for - [DocumentService.UpdateDocument][google.cloud.discoveryengine.v1beta.DocumentService.UpdateDocument] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.document.Document: - Document captures all raw metadata - information of items to be recommended - or searched. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1beta/{document.name=projects/*/locations/*/dataStores/*/branches/*/documents/*}', - 'body': 'document', - }, -{ - 'method': 'patch', - 'uri': '/v1beta/{document.name=projects/*/locations/*/collections/*/dataStores/*/branches/*/documents/*}', - 'body': 'document', - }, - ] - request, metadata = self._interceptor.pre_update_document(request, metadata) - pb_request = document_service.UpdateDocumentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = document.Document() - pb_resp = document.Document.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_document(resp) - return resp - - @property - def create_document(self) -> Callable[ - [document_service.CreateDocumentRequest], - gcd_document.Document]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateDocument(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_document(self) -> Callable[ - [document_service.DeleteDocumentRequest], - 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._DeleteDocument(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_document(self) -> Callable[ - [document_service.GetDocumentRequest], - document.Document]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetDocument(self._session, self._host, self._interceptor) # type: ignore - - @property - def import_documents(self) -> Callable[ - [import_config.ImportDocumentsRequest], - 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._ImportDocuments(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_documents(self) -> Callable[ - [document_service.ListDocumentsRequest], - document_service.ListDocumentsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListDocuments(self._session, self._host, self._interceptor) # type: ignore - - @property - def purge_documents(self) -> Callable[ - [purge_config.PurgeDocumentsRequest], - 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._PurgeDocuments(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_document(self) -> Callable[ - [document_service.UpdateDocumentRequest], - document.Document]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateDocument(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(DocumentServiceRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(DocumentServiceRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'DocumentServiceRestTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/__init__.py deleted file mode 100644 index ad8f24a9e055..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import RecommendationServiceClient -from .async_client import RecommendationServiceAsyncClient - -__all__ = ( - 'RecommendationServiceClient', - 'RecommendationServiceAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/async_client.py deleted file mode 100644 index d30e8ef14c51..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/async_client.py +++ /dev/null @@ -1,389 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.discoveryengine_v1beta import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.discoveryengine_v1beta.types import recommendation_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .transports.base import RecommendationServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import RecommendationServiceGrpcAsyncIOTransport -from .client import RecommendationServiceClient - - -class RecommendationServiceAsyncClient: - """Service for making recommendations.""" - - _client: RecommendationServiceClient - - DEFAULT_ENDPOINT = RecommendationServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = RecommendationServiceClient.DEFAULT_MTLS_ENDPOINT - - document_path = staticmethod(RecommendationServiceClient.document_path) - parse_document_path = staticmethod(RecommendationServiceClient.parse_document_path) - serving_config_path = staticmethod(RecommendationServiceClient.serving_config_path) - parse_serving_config_path = staticmethod(RecommendationServiceClient.parse_serving_config_path) - common_billing_account_path = staticmethod(RecommendationServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(RecommendationServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(RecommendationServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(RecommendationServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(RecommendationServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(RecommendationServiceClient.parse_common_organization_path) - common_project_path = staticmethod(RecommendationServiceClient.common_project_path) - parse_common_project_path = staticmethod(RecommendationServiceClient.parse_common_project_path) - common_location_path = staticmethod(RecommendationServiceClient.common_location_path) - parse_common_location_path = staticmethod(RecommendationServiceClient.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: - RecommendationServiceAsyncClient: The constructed client. - """ - return RecommendationServiceClient.from_service_account_info.__func__(RecommendationServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RecommendationServiceAsyncClient: The constructed client. - """ - return RecommendationServiceClient.from_service_account_file.__func__(RecommendationServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return RecommendationServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> RecommendationServiceTransport: - """Returns the transport used by the client instance. - - Returns: - RecommendationServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(RecommendationServiceClient).get_transport_class, type(RecommendationServiceClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, RecommendationServiceTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the recommendation 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 (Union[str, ~.RecommendationServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = RecommendationServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def recommend(self, - request: Optional[Union[recommendation_service.RecommendRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> recommendation_service.RecommendResponse: - r"""Makes a recommendation, which requires a contextual - user event. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - async def sample_recommend(): - # Create a client - client = discoveryengine_v1beta.RecommendationServiceAsyncClient() - - # Initialize request argument(s) - user_event = discoveryengine_v1beta.UserEvent() - user_event.event_type = "event_type_value" - user_event.user_pseudo_id = "user_pseudo_id_value" - - request = discoveryengine_v1beta.RecommendRequest( - serving_config="serving_config_value", - user_event=user_event, - ) - - # Make the request - response = await client.recommend(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1beta.types.RecommendRequest, dict]]): - The request object. Request message for Recommend method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1beta.types.RecommendResponse: - Response message for Recommend - method. - - """ - # Create or coerce a protobuf request object. - request = recommendation_service.RecommendRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.recommend, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config", request.serving_config), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "RecommendationServiceAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "RecommendationServiceAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/client.py deleted file mode 100644 index b532de6a9a8a..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/client.py +++ /dev/null @@ -1,606 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.discoveryengine_v1beta import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.discoveryengine_v1beta.types import recommendation_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .transports.base import RecommendationServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import RecommendationServiceGrpcTransport -from .transports.grpc_asyncio import RecommendationServiceGrpcAsyncIOTransport -from .transports.rest import RecommendationServiceRestTransport - - -class RecommendationServiceClientMeta(type): - """Metaclass for the RecommendationService 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[RecommendationServiceTransport]] - _transport_registry["grpc"] = RecommendationServiceGrpcTransport - _transport_registry["grpc_asyncio"] = RecommendationServiceGrpcAsyncIOTransport - _transport_registry["rest"] = RecommendationServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[RecommendationServiceTransport]: - """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 RecommendationServiceClient(metaclass=RecommendationServiceClientMeta): - """Service for making recommendations.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RecommendationServiceClient: 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: - RecommendationServiceClient: 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) -> RecommendationServiceTransport: - """Returns the transport used by the client instance. - - Returns: - RecommendationServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def document_path(project: str,location: str,data_store: str,branch: str,document: str,) -> str: - """Returns a fully-qualified document string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) - - @staticmethod - def parse_document_path(path: str) -> Dict[str,str]: - """Parses a document path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)/documents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def serving_config_path(project: str,location: str,data_store: str,serving_config: str,) -> str: - """Returns a fully-qualified serving_config string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}/servingConfigs/{serving_config}".format(project=project, location=location, data_store=data_store, serving_config=serving_config, ) - - @staticmethod - def parse_serving_config_path(path: str) -> Dict[str,str]: - """Parses a serving_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/servingConfigs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, RecommendationServiceTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the recommendation 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 (Union[str, RecommendationServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, RecommendationServiceTransport): - # transport is a RecommendationServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def recommend(self, - request: Optional[Union[recommendation_service.RecommendRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> recommendation_service.RecommendResponse: - r"""Makes a recommendation, which requires a contextual - user event. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - def sample_recommend(): - # Create a client - client = discoveryengine_v1beta.RecommendationServiceClient() - - # Initialize request argument(s) - user_event = discoveryengine_v1beta.UserEvent() - user_event.event_type = "event_type_value" - user_event.user_pseudo_id = "user_pseudo_id_value" - - request = discoveryengine_v1beta.RecommendRequest( - serving_config="serving_config_value", - user_event=user_event, - ) - - # Make the request - response = client.recommend(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1beta.types.RecommendRequest, dict]): - The request object. Request message for Recommend method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1beta.types.RecommendResponse: - Response message for Recommend - method. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a recommendation_service.RecommendRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, recommendation_service.RecommendRequest): - request = recommendation_service.RecommendRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.recommend] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config", request.serving_config), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "RecommendationServiceClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - - - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "RecommendationServiceClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/__init__.py deleted file mode 100644 index ce9f9edfd346..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import RecommendationServiceTransport -from .grpc import RecommendationServiceGrpcTransport -from .grpc_asyncio import RecommendationServiceGrpcAsyncIOTransport -from .rest import RecommendationServiceRestTransport -from .rest import RecommendationServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[RecommendationServiceTransport]] -_transport_registry['grpc'] = RecommendationServiceGrpcTransport -_transport_registry['grpc_asyncio'] = RecommendationServiceGrpcAsyncIOTransport -_transport_registry['rest'] = RecommendationServiceRestTransport - -__all__ = ( - 'RecommendationServiceTransport', - 'RecommendationServiceGrpcTransport', - 'RecommendationServiceGrpcAsyncIOTransport', - 'RecommendationServiceRestTransport', - 'RecommendationServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/base.py deleted file mode 100644 index 9ec66c3afaac..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/base.py +++ /dev/null @@ -1,168 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.discoveryengine_v1beta import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.discoveryengine_v1beta.types import recommendation_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class RecommendationServiceTransport(abc.ABC): - """Abstract transport class for RecommendationService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'discoveryengine.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.recommend: gapic_v1.method.wrap_method( - self.recommend, - 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 recommend(self) -> Callable[ - [recommendation_service.RecommendRequest], - Union[ - recommendation_service.RecommendResponse, - Awaitable[recommendation_service.RecommendResponse] - ]]: - 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 kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'RecommendationServiceTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/grpc.py deleted file mode 100644 index bef973446851..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/grpc.py +++ /dev/null @@ -1,303 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.discoveryengine_v1beta.types import recommendation_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import RecommendationServiceTransport, DEFAULT_CLIENT_INFO - - -class RecommendationServiceGrpcTransport(RecommendationServiceTransport): - """gRPC backend transport for RecommendationService. - - Service for making recommendations. - - 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def recommend(self) -> Callable[ - [recommendation_service.RecommendRequest], - recommendation_service.RecommendResponse]: - r"""Return a callable for the recommend method over gRPC. - - Makes a recommendation, which requires a contextual - user event. - - Returns: - Callable[[~.RecommendRequest], - ~.RecommendResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'recommend' not in self._stubs: - self._stubs['recommend'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.RecommendationService/Recommend', - request_serializer=recommendation_service.RecommendRequest.serialize, - response_deserializer=recommendation_service.RecommendResponse.deserialize, - ) - return self._stubs['recommend'] - - def close(self): - self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'RecommendationServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/grpc_asyncio.py deleted file mode 100644 index 730f83fb04be..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,302 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.discoveryengine_v1beta.types import recommendation_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import RecommendationServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import RecommendationServiceGrpcTransport - - -class RecommendationServiceGrpcAsyncIOTransport(RecommendationServiceTransport): - """gRPC AsyncIO backend transport for RecommendationService. - - Service for making recommendations. - - 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def recommend(self) -> Callable[ - [recommendation_service.RecommendRequest], - Awaitable[recommendation_service.RecommendResponse]]: - r"""Return a callable for the recommend method over gRPC. - - Makes a recommendation, which requires a contextual - user event. - - Returns: - Callable[[~.RecommendRequest], - Awaitable[~.RecommendResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'recommend' not in self._stubs: - self._stubs['recommend'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.RecommendationService/Recommend', - request_serializer=recommendation_service.RecommendRequest.serialize, - response_deserializer=recommendation_service.RecommendResponse.deserialize, - ) - return self._stubs['recommend'] - - def close(self): - return self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - -__all__ = ( - 'RecommendationServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/rest.py deleted file mode 100644 index 83d301a7013d..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/recommendation_service/transports/rest.py +++ /dev/null @@ -1,573 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.cloud.location import locations_pb2 # type: ignore -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.discoveryengine_v1beta.types import recommendation_service -from google.longrunning import operations_pb2 # type: ignore - -from .base import RecommendationServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class RecommendationServiceRestInterceptor: - """Interceptor for RecommendationService. - - 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 RecommendationServiceRestTransport. - - .. code-block:: python - class MyCustomRecommendationServiceInterceptor(RecommendationServiceRestInterceptor): - def pre_recommend(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_recommend(self, response): - logging.log(f"Received response: {response}") - return response - - transport = RecommendationServiceRestTransport(interceptor=MyCustomRecommendationServiceInterceptor()) - client = RecommendationServiceClient(transport=transport) - - - """ - def pre_recommend(self, request: recommendation_service.RecommendRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[recommendation_service.RecommendRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for recommend - - Override in a subclass to manipulate the request or metadata - before they are sent to the RecommendationService server. - """ - return request, metadata - - def post_recommend(self, response: recommendation_service.RecommendResponse) -> recommendation_service.RecommendResponse: - """Post-rpc interceptor for recommend - - Override in a subclass to manipulate the response - after it is returned by the RecommendationService server but before - it is returned to user code. - """ - return response - - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the RecommendationService 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 RecommendationService server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the RecommendationService 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 RecommendationService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class RecommendationServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: RecommendationServiceRestInterceptor - - -class RecommendationServiceRestTransport(RecommendationServiceTransport): - """REST backend transport for RecommendationService. - - Service for making recommendations. - - 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 = 'discoveryengine.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[RecommendationServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or RecommendationServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _Recommend(RecommendationServiceRestStub): - def __hash__(self): - return hash("Recommend") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: recommendation_service.RecommendRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> recommendation_service.RecommendResponse: - r"""Call the recommend method over HTTP. - - Args: - request (~.recommendation_service.RecommendRequest): - The request object. Request message for Recommend method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.recommendation_service.RecommendResponse: - Response message for Recommend - method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta/{serving_config=projects/*/locations/*/dataStores/*/servingConfigs/*}:recommend', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1beta/{serving_config=projects/*/locations/*/collections/*/dataStores/*/servingConfigs/*}:recommend', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_recommend(request, metadata) - pb_request = recommendation_service.RecommendRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = recommendation_service.RecommendResponse() - pb_resp = recommendation_service.RecommendResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_recommend(resp) - return resp - - @property - def recommend(self) -> Callable[ - [recommendation_service.RecommendRequest], - recommendation_service.RecommendResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._Recommend(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(RecommendationServiceRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(RecommendationServiceRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'RecommendationServiceRestTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/__init__.py deleted file mode 100644 index 4e9455a921b6..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import SchemaServiceClient -from .async_client import SchemaServiceAsyncClient - -__all__ = ( - 'SchemaServiceClient', - 'SchemaServiceAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/async_client.py deleted file mode 100644 index 7c4686176c93..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/async_client.py +++ /dev/null @@ -1,902 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.discoveryengine_v1beta import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.discoveryengine_v1beta.services.schema_service import pagers -from google.cloud.discoveryengine_v1beta.types import schema -from google.cloud.discoveryengine_v1beta.types import schema as gcd_schema -from google.cloud.discoveryengine_v1beta.types import schema_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from .transports.base import SchemaServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import SchemaServiceGrpcAsyncIOTransport -from .client import SchemaServiceClient - - -class SchemaServiceAsyncClient: - """Service for managing - [Schema][google.cloud.discoveryengine.v1beta.Schema]s. - """ - - _client: SchemaServiceClient - - DEFAULT_ENDPOINT = SchemaServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SchemaServiceClient.DEFAULT_MTLS_ENDPOINT - - data_store_path = staticmethod(SchemaServiceClient.data_store_path) - parse_data_store_path = staticmethod(SchemaServiceClient.parse_data_store_path) - schema_path = staticmethod(SchemaServiceClient.schema_path) - parse_schema_path = staticmethod(SchemaServiceClient.parse_schema_path) - common_billing_account_path = staticmethod(SchemaServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(SchemaServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(SchemaServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(SchemaServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(SchemaServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(SchemaServiceClient.parse_common_organization_path) - common_project_path = staticmethod(SchemaServiceClient.common_project_path) - parse_common_project_path = staticmethod(SchemaServiceClient.parse_common_project_path) - common_location_path = staticmethod(SchemaServiceClient.common_location_path) - parse_common_location_path = staticmethod(SchemaServiceClient.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: - SchemaServiceAsyncClient: The constructed client. - """ - return SchemaServiceClient.from_service_account_info.__func__(SchemaServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SchemaServiceAsyncClient: The constructed client. - """ - return SchemaServiceClient.from_service_account_file.__func__(SchemaServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return SchemaServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> SchemaServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SchemaServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(SchemaServiceClient).get_transport_class, type(SchemaServiceClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, SchemaServiceTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the schema 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 (Union[str, ~.SchemaServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = SchemaServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def get_schema(self, - request: Optional[Union[schema_service.GetSchemaRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> schema.Schema: - r"""Gets a [Schema][google.cloud.discoveryengine.v1beta.Schema]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - async def sample_get_schema(): - # Create a client - client = discoveryengine_v1beta.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.GetSchemaRequest( - name="name_value", - ) - - # Make the request - response = await client.get_schema(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1beta.types.GetSchemaRequest, dict]]): - The request object. Request message for - [SchemaService.GetSchema][google.cloud.discoveryengine.v1beta.SchemaService.GetSchema] - method. - name (:class:`str`): - Required. The full resource name of the schema, in the - format of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1beta.types.Schema: - Defines the structure and layout of a - type of document data. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = schema_service.GetSchemaRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_schema, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_schemas(self, - request: Optional[Union[schema_service.ListSchemasRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSchemasAsyncPager: - r"""Gets a list of - [Schema][google.cloud.discoveryengine.v1beta.Schema]s. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - async def sample_list_schemas(): - # Create a client - client = discoveryengine_v1beta.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.ListSchemasRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_schemas(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1beta.types.ListSchemasRequest, dict]]): - The request object. Request message for - [SchemaService.ListSchemas][google.cloud.discoveryengine.v1beta.SchemaService.ListSchemas] - method. - parent (:class:`str`): - Required. The parent data store resource name, in the - format of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1beta.services.schema_service.pagers.ListSchemasAsyncPager: - Response message for - [SchemaService.ListSchemas][google.cloud.discoveryengine.v1beta.SchemaService.ListSchemas] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = schema_service.ListSchemasRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_schemas, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListSchemasAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_schema(self, - request: Optional[Union[schema_service.CreateSchemaRequest, dict]] = None, - *, - parent: Optional[str] = None, - schema: Optional[gcd_schema.Schema] = None, - schema_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a [Schema][google.cloud.discoveryengine.v1beta.Schema]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - async def sample_create_schema(): - # Create a client - client = discoveryengine_v1beta.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.CreateSchemaRequest( - parent="parent_value", - schema_id="schema_id_value", - ) - - # Make the request - operation = client.create_schema(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1beta.types.CreateSchemaRequest, dict]]): - The request object. Request message for - [SchemaService.CreateSchema][google.cloud.discoveryengine.v1beta.SchemaService.CreateSchema] - method. - parent (:class:`str`): - Required. The parent data store resource name, in the - format of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - schema (:class:`google.cloud.discoveryengine_v1beta.types.Schema`): - Required. The - [Schema][google.cloud.discoveryengine.v1beta.Schema] to - create. - - This corresponds to the ``schema`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - schema_id (:class:`str`): - Required. The ID to use for the - [Schema][google.cloud.discoveryengine.v1beta.Schema], - which will become the final component of the - [Schema.name][google.cloud.discoveryengine.v1beta.Schema.name]. - - This field should conform to - `RFC-1034 `__ - standard with a length limit of 63 characters. - - This corresponds to the ``schema_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.discoveryengine_v1beta.types.Schema` - Defines the structure and layout of a type of document - data. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, schema, schema_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = schema_service.CreateSchemaRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if schema is not None: - request.schema = schema - if schema_id is not None: - request.schema_id = schema_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_schema, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - gcd_schema.Schema, - metadata_type=schema_service.CreateSchemaMetadata, - ) - - # Done; return the response. - return response - - async def update_schema(self, - request: Optional[Union[schema_service.UpdateSchemaRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates a [Schema][google.cloud.discoveryengine.v1beta.Schema]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - async def sample_update_schema(): - # Create a client - client = discoveryengine_v1beta.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.UpdateSchemaRequest( - ) - - # Make the request - operation = client.update_schema(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1beta.types.UpdateSchemaRequest, dict]]): - The request object. Request message for - [SchemaService.UpdateSchema][google.cloud.discoveryengine.v1beta.SchemaService.UpdateSchema] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.discoveryengine_v1beta.types.Schema` - Defines the structure and layout of a type of document - data. - - """ - # Create or coerce a protobuf request object. - request = schema_service.UpdateSchemaRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_schema, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("schema.name", request.schema.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - schema.Schema, - metadata_type=schema_service.UpdateSchemaMetadata, - ) - - # Done; return the response. - return response - - async def delete_schema(self, - request: Optional[Union[schema_service.DeleteSchemaRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a [Schema][google.cloud.discoveryengine.v1beta.Schema]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - async def sample_delete_schema(): - # Create a client - client = discoveryengine_v1beta.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.DeleteSchemaRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_schema(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1beta.types.DeleteSchemaRequest, dict]]): - The request object. Request message for - [SchemaService.DeleteSchema][google.cloud.discoveryengine.v1beta.SchemaService.DeleteSchema] - method. - name (:class:`str`): - Required. The full resource name of the schema, in the - format of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = schema_service.DeleteSchemaRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_schema, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=schema_service.DeleteSchemaMetadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "SchemaServiceAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "SchemaServiceAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/client.py deleted file mode 100644 index dac2c8a8e5b1..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/client.py +++ /dev/null @@ -1,1119 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.discoveryengine_v1beta import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.discoveryengine_v1beta.services.schema_service import pagers -from google.cloud.discoveryengine_v1beta.types import schema -from google.cloud.discoveryengine_v1beta.types import schema as gcd_schema -from google.cloud.discoveryengine_v1beta.types import schema_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from .transports.base import SchemaServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SchemaServiceGrpcTransport -from .transports.grpc_asyncio import SchemaServiceGrpcAsyncIOTransport -from .transports.rest import SchemaServiceRestTransport - - -class SchemaServiceClientMeta(type): - """Metaclass for the SchemaService 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[SchemaServiceTransport]] - _transport_registry["grpc"] = SchemaServiceGrpcTransport - _transport_registry["grpc_asyncio"] = SchemaServiceGrpcAsyncIOTransport - _transport_registry["rest"] = SchemaServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[SchemaServiceTransport]: - """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 SchemaServiceClient(metaclass=SchemaServiceClientMeta): - """Service for managing - [Schema][google.cloud.discoveryengine.v1beta.Schema]s. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SchemaServiceClient: 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: - SchemaServiceClient: 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) -> SchemaServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SchemaServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def data_store_path(project: str,location: str,data_store: str,) -> str: - """Returns a fully-qualified data_store string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) - - @staticmethod - def parse_data_store_path(path: str) -> Dict[str,str]: - """Parses a data_store path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def schema_path(project: str,location: str,data_store: str,schema: str,) -> str: - """Returns a fully-qualified schema string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}/schemas/{schema}".format(project=project, location=location, data_store=data_store, schema=schema, ) - - @staticmethod - def parse_schema_path(path: str) -> Dict[str,str]: - """Parses a schema path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/schemas/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, SchemaServiceTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the schema 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 (Union[str, SchemaServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, SchemaServiceTransport): - # transport is a SchemaServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def get_schema(self, - request: Optional[Union[schema_service.GetSchemaRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> schema.Schema: - r"""Gets a [Schema][google.cloud.discoveryengine.v1beta.Schema]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - def sample_get_schema(): - # Create a client - client = discoveryengine_v1beta.SchemaServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.GetSchemaRequest( - name="name_value", - ) - - # Make the request - response = client.get_schema(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1beta.types.GetSchemaRequest, dict]): - The request object. Request message for - [SchemaService.GetSchema][google.cloud.discoveryengine.v1beta.SchemaService.GetSchema] - method. - name (str): - Required. The full resource name of the schema, in the - format of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1beta.types.Schema: - Defines the structure and layout of a - type of document data. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a schema_service.GetSchemaRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, schema_service.GetSchemaRequest): - request = schema_service.GetSchemaRequest(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_schema] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_schemas(self, - request: Optional[Union[schema_service.ListSchemasRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSchemasPager: - r"""Gets a list of - [Schema][google.cloud.discoveryengine.v1beta.Schema]s. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - def sample_list_schemas(): - # Create a client - client = discoveryengine_v1beta.SchemaServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.ListSchemasRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_schemas(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1beta.types.ListSchemasRequest, dict]): - The request object. Request message for - [SchemaService.ListSchemas][google.cloud.discoveryengine.v1beta.SchemaService.ListSchemas] - method. - parent (str): - Required. The parent data store resource name, in the - format of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1beta.services.schema_service.pagers.ListSchemasPager: - Response message for - [SchemaService.ListSchemas][google.cloud.discoveryengine.v1beta.SchemaService.ListSchemas] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a schema_service.ListSchemasRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, schema_service.ListSchemasRequest): - request = schema_service.ListSchemasRequest(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_schemas] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListSchemasPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_schema(self, - request: Optional[Union[schema_service.CreateSchemaRequest, dict]] = None, - *, - parent: Optional[str] = None, - schema: Optional[gcd_schema.Schema] = None, - schema_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a [Schema][google.cloud.discoveryengine.v1beta.Schema]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - def sample_create_schema(): - # Create a client - client = discoveryengine_v1beta.SchemaServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.CreateSchemaRequest( - parent="parent_value", - schema_id="schema_id_value", - ) - - # Make the request - operation = client.create_schema(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1beta.types.CreateSchemaRequest, dict]): - The request object. Request message for - [SchemaService.CreateSchema][google.cloud.discoveryengine.v1beta.SchemaService.CreateSchema] - method. - parent (str): - Required. The parent data store resource name, in the - format of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - schema (google.cloud.discoveryengine_v1beta.types.Schema): - Required. The - [Schema][google.cloud.discoveryengine.v1beta.Schema] to - create. - - This corresponds to the ``schema`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - schema_id (str): - Required. The ID to use for the - [Schema][google.cloud.discoveryengine.v1beta.Schema], - which will become the final component of the - [Schema.name][google.cloud.discoveryengine.v1beta.Schema.name]. - - This field should conform to - `RFC-1034 `__ - standard with a length limit of 63 characters. - - This corresponds to the ``schema_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.discoveryengine_v1beta.types.Schema` - Defines the structure and layout of a type of document - data. - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, schema, schema_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a schema_service.CreateSchemaRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, schema_service.CreateSchemaRequest): - request = schema_service.CreateSchemaRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if schema is not None: - request.schema = schema - if schema_id is not None: - request.schema_id = schema_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_schema] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - gcd_schema.Schema, - metadata_type=schema_service.CreateSchemaMetadata, - ) - - # Done; return the response. - return response - - def update_schema(self, - request: Optional[Union[schema_service.UpdateSchemaRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates a [Schema][google.cloud.discoveryengine.v1beta.Schema]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - def sample_update_schema(): - # Create a client - client = discoveryengine_v1beta.SchemaServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.UpdateSchemaRequest( - ) - - # Make the request - operation = client.update_schema(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1beta.types.UpdateSchemaRequest, dict]): - The request object. Request message for - [SchemaService.UpdateSchema][google.cloud.discoveryengine.v1beta.SchemaService.UpdateSchema] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.discoveryengine_v1beta.types.Schema` - Defines the structure and layout of a type of document - data. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a schema_service.UpdateSchemaRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, schema_service.UpdateSchemaRequest): - request = schema_service.UpdateSchemaRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_schema] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("schema.name", request.schema.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - schema.Schema, - metadata_type=schema_service.UpdateSchemaMetadata, - ) - - # Done; return the response. - return response - - def delete_schema(self, - request: Optional[Union[schema_service.DeleteSchemaRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes a [Schema][google.cloud.discoveryengine.v1beta.Schema]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - def sample_delete_schema(): - # Create a client - client = discoveryengine_v1beta.SchemaServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.DeleteSchemaRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_schema(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1beta.types.DeleteSchemaRequest, dict]): - The request object. Request message for - [SchemaService.DeleteSchema][google.cloud.discoveryengine.v1beta.SchemaService.DeleteSchema] - method. - name (str): - Required. The full resource name of the schema, in the - format of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a schema_service.DeleteSchemaRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, schema_service.DeleteSchemaRequest): - request = schema_service.DeleteSchemaRequest(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_schema] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=schema_service.DeleteSchemaMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "SchemaServiceClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - - - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "SchemaServiceClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/pagers.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/pagers.py deleted file mode 100644 index 02dc508d2620..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.discoveryengine_v1beta.types import schema -from google.cloud.discoveryengine_v1beta.types import schema_service - - -class ListSchemasPager: - """A pager for iterating through ``list_schemas`` requests. - - This class thinly wraps an initial - :class:`google.cloud.discoveryengine_v1beta.types.ListSchemasResponse` object, and - provides an ``__iter__`` method to iterate through its - ``schemas`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListSchemas`` requests and continue to iterate - through the ``schemas`` field on the - corresponding responses. - - All the usual :class:`google.cloud.discoveryengine_v1beta.types.ListSchemasResponse` - 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[..., schema_service.ListSchemasResponse], - request: schema_service.ListSchemasRequest, - response: schema_service.ListSchemasResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.discoveryengine_v1beta.types.ListSchemasRequest): - The initial request object. - response (google.cloud.discoveryengine_v1beta.types.ListSchemasResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = schema_service.ListSchemasRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[schema_service.ListSchemasResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[schema.Schema]: - for page in self.pages: - yield from page.schemas - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSchemasAsyncPager: - """A pager for iterating through ``list_schemas`` requests. - - This class thinly wraps an initial - :class:`google.cloud.discoveryengine_v1beta.types.ListSchemasResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``schemas`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListSchemas`` requests and continue to iterate - through the ``schemas`` field on the - corresponding responses. - - All the usual :class:`google.cloud.discoveryengine_v1beta.types.ListSchemasResponse` - 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[schema_service.ListSchemasResponse]], - request: schema_service.ListSchemasRequest, - response: schema_service.ListSchemasResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.discoveryengine_v1beta.types.ListSchemasRequest): - The initial request object. - response (google.cloud.discoveryengine_v1beta.types.ListSchemasResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = schema_service.ListSchemasRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[schema_service.ListSchemasResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[schema.Schema]: - async def async_generator(): - async for page in self.pages: - for response in page.schemas: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/__init__.py deleted file mode 100644 index d5ebd14e657b..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import SchemaServiceTransport -from .grpc import SchemaServiceGrpcTransport -from .grpc_asyncio import SchemaServiceGrpcAsyncIOTransport -from .rest import SchemaServiceRestTransport -from .rest import SchemaServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SchemaServiceTransport]] -_transport_registry['grpc'] = SchemaServiceGrpcTransport -_transport_registry['grpc_asyncio'] = SchemaServiceGrpcAsyncIOTransport -_transport_registry['rest'] = SchemaServiceRestTransport - -__all__ = ( - 'SchemaServiceTransport', - 'SchemaServiceGrpcTransport', - 'SchemaServiceGrpcAsyncIOTransport', - 'SchemaServiceRestTransport', - 'SchemaServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/base.py deleted file mode 100644 index eeb36e9fef51..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/base.py +++ /dev/null @@ -1,231 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.discoveryengine_v1beta import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.discoveryengine_v1beta.types import schema -from google.cloud.discoveryengine_v1beta.types import schema_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class SchemaServiceTransport(abc.ABC): - """Abstract transport class for SchemaService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'discoveryengine.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.get_schema: gapic_v1.method.wrap_method( - self.get_schema, - default_timeout=None, - client_info=client_info, - ), - self.list_schemas: gapic_v1.method.wrap_method( - self.list_schemas, - default_timeout=None, - client_info=client_info, - ), - self.create_schema: gapic_v1.method.wrap_method( - self.create_schema, - default_timeout=None, - client_info=client_info, - ), - self.update_schema: gapic_v1.method.wrap_method( - self.update_schema, - default_timeout=None, - client_info=client_info, - ), - self.delete_schema: gapic_v1.method.wrap_method( - self.delete_schema, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def get_schema(self) -> Callable[ - [schema_service.GetSchemaRequest], - Union[ - schema.Schema, - Awaitable[schema.Schema] - ]]: - raise NotImplementedError() - - @property - def list_schemas(self) -> Callable[ - [schema_service.ListSchemasRequest], - Union[ - schema_service.ListSchemasResponse, - Awaitable[schema_service.ListSchemasResponse] - ]]: - raise NotImplementedError() - - @property - def create_schema(self) -> Callable[ - [schema_service.CreateSchemaRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_schema(self) -> Callable[ - [schema_service.UpdateSchemaRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_schema(self) -> Callable[ - [schema_service.DeleteSchemaRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'SchemaServiceTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/grpc.py deleted file mode 100644 index 59d88fb350c8..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/grpc.py +++ /dev/null @@ -1,427 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.discoveryengine_v1beta.types import schema -from google.cloud.discoveryengine_v1beta.types import schema_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import SchemaServiceTransport, DEFAULT_CLIENT_INFO - - -class SchemaServiceGrpcTransport(SchemaServiceTransport): - """gRPC backend transport for SchemaService. - - Service for managing - [Schema][google.cloud.discoveryengine.v1beta.Schema]s. - - 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def get_schema(self) -> Callable[ - [schema_service.GetSchemaRequest], - schema.Schema]: - r"""Return a callable for the get schema method over gRPC. - - Gets a [Schema][google.cloud.discoveryengine.v1beta.Schema]. - - Returns: - Callable[[~.GetSchemaRequest], - ~.Schema]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_schema' not in self._stubs: - self._stubs['get_schema'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.SchemaService/GetSchema', - request_serializer=schema_service.GetSchemaRequest.serialize, - response_deserializer=schema.Schema.deserialize, - ) - return self._stubs['get_schema'] - - @property - def list_schemas(self) -> Callable[ - [schema_service.ListSchemasRequest], - schema_service.ListSchemasResponse]: - r"""Return a callable for the list schemas method over gRPC. - - Gets a list of - [Schema][google.cloud.discoveryengine.v1beta.Schema]s. - - Returns: - Callable[[~.ListSchemasRequest], - ~.ListSchemasResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_schemas' not in self._stubs: - self._stubs['list_schemas'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.SchemaService/ListSchemas', - request_serializer=schema_service.ListSchemasRequest.serialize, - response_deserializer=schema_service.ListSchemasResponse.deserialize, - ) - return self._stubs['list_schemas'] - - @property - def create_schema(self) -> Callable[ - [schema_service.CreateSchemaRequest], - operations_pb2.Operation]: - r"""Return a callable for the create schema method over gRPC. - - Creates a [Schema][google.cloud.discoveryengine.v1beta.Schema]. - - Returns: - Callable[[~.CreateSchemaRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_schema' not in self._stubs: - self._stubs['create_schema'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.SchemaService/CreateSchema', - request_serializer=schema_service.CreateSchemaRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_schema'] - - @property - def update_schema(self) -> Callable[ - [schema_service.UpdateSchemaRequest], - operations_pb2.Operation]: - r"""Return a callable for the update schema method over gRPC. - - Updates a [Schema][google.cloud.discoveryengine.v1beta.Schema]. - - Returns: - Callable[[~.UpdateSchemaRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_schema' not in self._stubs: - self._stubs['update_schema'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.SchemaService/UpdateSchema', - request_serializer=schema_service.UpdateSchemaRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_schema'] - - @property - def delete_schema(self) -> Callable[ - [schema_service.DeleteSchemaRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete schema method over gRPC. - - Deletes a [Schema][google.cloud.discoveryengine.v1beta.Schema]. - - Returns: - Callable[[~.DeleteSchemaRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_schema' not in self._stubs: - self._stubs['delete_schema'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.SchemaService/DeleteSchema', - request_serializer=schema_service.DeleteSchemaRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_schema'] - - def close(self): - self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'SchemaServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/grpc_asyncio.py deleted file mode 100644 index c3fac15e2ad3..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,426 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.discoveryengine_v1beta.types import schema -from google.cloud.discoveryengine_v1beta.types import schema_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import SchemaServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import SchemaServiceGrpcTransport - - -class SchemaServiceGrpcAsyncIOTransport(SchemaServiceTransport): - """gRPC AsyncIO backend transport for SchemaService. - - Service for managing - [Schema][google.cloud.discoveryengine.v1beta.Schema]s. - - 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def get_schema(self) -> Callable[ - [schema_service.GetSchemaRequest], - Awaitable[schema.Schema]]: - r"""Return a callable for the get schema method over gRPC. - - Gets a [Schema][google.cloud.discoveryengine.v1beta.Schema]. - - Returns: - Callable[[~.GetSchemaRequest], - Awaitable[~.Schema]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_schema' not in self._stubs: - self._stubs['get_schema'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.SchemaService/GetSchema', - request_serializer=schema_service.GetSchemaRequest.serialize, - response_deserializer=schema.Schema.deserialize, - ) - return self._stubs['get_schema'] - - @property - def list_schemas(self) -> Callable[ - [schema_service.ListSchemasRequest], - Awaitable[schema_service.ListSchemasResponse]]: - r"""Return a callable for the list schemas method over gRPC. - - Gets a list of - [Schema][google.cloud.discoveryengine.v1beta.Schema]s. - - Returns: - Callable[[~.ListSchemasRequest], - Awaitable[~.ListSchemasResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_schemas' not in self._stubs: - self._stubs['list_schemas'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.SchemaService/ListSchemas', - request_serializer=schema_service.ListSchemasRequest.serialize, - response_deserializer=schema_service.ListSchemasResponse.deserialize, - ) - return self._stubs['list_schemas'] - - @property - def create_schema(self) -> Callable[ - [schema_service.CreateSchemaRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create schema method over gRPC. - - Creates a [Schema][google.cloud.discoveryengine.v1beta.Schema]. - - Returns: - Callable[[~.CreateSchemaRequest], - 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_schema' not in self._stubs: - self._stubs['create_schema'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.SchemaService/CreateSchema', - request_serializer=schema_service.CreateSchemaRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_schema'] - - @property - def update_schema(self) -> Callable[ - [schema_service.UpdateSchemaRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update schema method over gRPC. - - Updates a [Schema][google.cloud.discoveryengine.v1beta.Schema]. - - Returns: - Callable[[~.UpdateSchemaRequest], - 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_schema' not in self._stubs: - self._stubs['update_schema'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.SchemaService/UpdateSchema', - request_serializer=schema_service.UpdateSchemaRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_schema'] - - @property - def delete_schema(self) -> Callable[ - [schema_service.DeleteSchemaRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete schema method over gRPC. - - Deletes a [Schema][google.cloud.discoveryengine.v1beta.Schema]. - - Returns: - Callable[[~.DeleteSchemaRequest], - 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_schema' not in self._stubs: - self._stubs['delete_schema'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.SchemaService/DeleteSchema', - request_serializer=schema_service.DeleteSchemaRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_schema'] - - def close(self): - return self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - -__all__ = ( - 'SchemaServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/rest.py deleted file mode 100644 index 018217eaa473..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/schema_service/transports/rest.py +++ /dev/null @@ -1,1192 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.cloud.location import locations_pb2 # type: ignore -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.discoveryengine_v1beta.types import schema -from google.cloud.discoveryengine_v1beta.types import schema_service -from google.longrunning import operations_pb2 # type: ignore - -from .base import SchemaServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class SchemaServiceRestInterceptor: - """Interceptor for SchemaService. - - 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 SchemaServiceRestTransport. - - .. code-block:: python - class MyCustomSchemaServiceInterceptor(SchemaServiceRestInterceptor): - def pre_create_schema(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_schema(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_schema(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_schema(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_schema(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_schema(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_schemas(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_schemas(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_schema(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_schema(self, response): - logging.log(f"Received response: {response}") - return response - - transport = SchemaServiceRestTransport(interceptor=MyCustomSchemaServiceInterceptor()) - client = SchemaServiceClient(transport=transport) - - - """ - def pre_create_schema(self, request: schema_service.CreateSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[schema_service.CreateSchemaRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_schema - - Override in a subclass to manipulate the request or metadata - before they are sent to the SchemaService server. - """ - return request, metadata - - def post_create_schema(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_schema - - Override in a subclass to manipulate the response - after it is returned by the SchemaService server but before - it is returned to user code. - """ - return response - def pre_delete_schema(self, request: schema_service.DeleteSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[schema_service.DeleteSchemaRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_schema - - Override in a subclass to manipulate the request or metadata - before they are sent to the SchemaService server. - """ - return request, metadata - - def post_delete_schema(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_schema - - Override in a subclass to manipulate the response - after it is returned by the SchemaService server but before - it is returned to user code. - """ - return response - def pre_get_schema(self, request: schema_service.GetSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[schema_service.GetSchemaRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_schema - - Override in a subclass to manipulate the request or metadata - before they are sent to the SchemaService server. - """ - return request, metadata - - def post_get_schema(self, response: schema.Schema) -> schema.Schema: - """Post-rpc interceptor for get_schema - - Override in a subclass to manipulate the response - after it is returned by the SchemaService server but before - it is returned to user code. - """ - return response - def pre_list_schemas(self, request: schema_service.ListSchemasRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[schema_service.ListSchemasRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_schemas - - Override in a subclass to manipulate the request or metadata - before they are sent to the SchemaService server. - """ - return request, metadata - - def post_list_schemas(self, response: schema_service.ListSchemasResponse) -> schema_service.ListSchemasResponse: - """Post-rpc interceptor for list_schemas - - Override in a subclass to manipulate the response - after it is returned by the SchemaService server but before - it is returned to user code. - """ - return response - def pre_update_schema(self, request: schema_service.UpdateSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[schema_service.UpdateSchemaRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_schema - - Override in a subclass to manipulate the request or metadata - before they are sent to the SchemaService server. - """ - return request, metadata - - def post_update_schema(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_schema - - Override in a subclass to manipulate the response - after it is returned by the SchemaService server but before - it is returned to user code. - """ - return response - - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the SchemaService 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 SchemaService server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the SchemaService 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 SchemaService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class SchemaServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: SchemaServiceRestInterceptor - - -class SchemaServiceRestTransport(SchemaServiceTransport): - """REST backend transport for SchemaService. - - Service for managing - [Schema][google.cloud.discoveryengine.v1beta.Schema]s. - - 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 = 'discoveryengine.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[SchemaServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or SchemaServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*}/operations', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1beta") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _CreateSchema(SchemaServiceRestStub): - def __hash__(self): - return hash("CreateSchema") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "schemaId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: schema_service.CreateSchemaRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create schema method over HTTP. - - Args: - request (~.schema_service.CreateSchemaRequest): - The request object. Request message for - [SchemaService.CreateSchema][google.cloud.discoveryengine.v1beta.SchemaService.CreateSchema] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta/{parent=projects/*/locations/*/dataStores/*}/schemas', - 'body': 'schema', - }, -{ - 'method': 'post', - 'uri': '/v1beta/{parent=projects/*/locations/*/collections/*/dataStores/*}/schemas', - 'body': 'schema', - }, - ] - request, metadata = self._interceptor.pre_create_schema(request, metadata) - pb_request = schema_service.CreateSchemaRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_schema(resp) - return resp - - class _DeleteSchema(SchemaServiceRestStub): - def __hash__(self): - return hash("DeleteSchema") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: schema_service.DeleteSchemaRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete schema method over HTTP. - - Args: - request (~.schema_service.DeleteSchemaRequest): - The request object. Request message for - [SchemaService.DeleteSchema][google.cloud.discoveryengine.v1beta.SchemaService.DeleteSchema] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/schemas/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_schema(request, metadata) - pb_request = schema_service.DeleteSchemaRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_schema(resp) - return resp - - class _GetSchema(SchemaServiceRestStub): - def __hash__(self): - return hash("GetSchema") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: schema_service.GetSchemaRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> schema.Schema: - r"""Call the get schema method over HTTP. - - Args: - request (~.schema_service.GetSchemaRequest): - The request object. Request message for - [SchemaService.GetSchema][google.cloud.discoveryengine.v1beta.SchemaService.GetSchema] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.schema.Schema: - Defines the structure and layout of a - type of document data. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/schemas/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}', - }, - ] - request, metadata = self._interceptor.pre_get_schema(request, metadata) - pb_request = schema_service.GetSchemaRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = schema.Schema() - pb_resp = schema.Schema.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_schema(resp) - return resp - - class _ListSchemas(SchemaServiceRestStub): - def __hash__(self): - return hash("ListSchemas") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: schema_service.ListSchemasRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> schema_service.ListSchemasResponse: - r"""Call the list schemas method over HTTP. - - Args: - request (~.schema_service.ListSchemasRequest): - The request object. Request message for - [SchemaService.ListSchemas][google.cloud.discoveryengine.v1beta.SchemaService.ListSchemas] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.schema_service.ListSchemasResponse: - Response message for - [SchemaService.ListSchemas][google.cloud.discoveryengine.v1beta.SchemaService.ListSchemas] - method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{parent=projects/*/locations/*/dataStores/*}/schemas', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{parent=projects/*/locations/*/collections/*/dataStores/*}/schemas', - }, - ] - request, metadata = self._interceptor.pre_list_schemas(request, metadata) - pb_request = schema_service.ListSchemasRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = schema_service.ListSchemasResponse() - pb_resp = schema_service.ListSchemasResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_schemas(resp) - return resp - - class _UpdateSchema(SchemaServiceRestStub): - def __hash__(self): - return hash("UpdateSchema") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: schema_service.UpdateSchemaRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update schema method over HTTP. - - Args: - request (~.schema_service.UpdateSchemaRequest): - The request object. Request message for - [SchemaService.UpdateSchema][google.cloud.discoveryengine.v1beta.SchemaService.UpdateSchema] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1beta/{schema.name=projects/*/locations/*/dataStores/*/schemas/*}', - 'body': 'schema', - }, -{ - 'method': 'patch', - 'uri': '/v1beta/{schema.name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}', - 'body': 'schema', - }, - ] - request, metadata = self._interceptor.pre_update_schema(request, metadata) - pb_request = schema_service.UpdateSchemaRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_schema(resp) - return resp - - @property - def create_schema(self) -> Callable[ - [schema_service.CreateSchemaRequest], - 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._CreateSchema(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_schema(self) -> Callable[ - [schema_service.DeleteSchemaRequest], - 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._DeleteSchema(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_schema(self) -> Callable[ - [schema_service.GetSchemaRequest], - schema.Schema]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetSchema(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_schemas(self) -> Callable[ - [schema_service.ListSchemasRequest], - schema_service.ListSchemasResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListSchemas(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_schema(self) -> Callable[ - [schema_service.UpdateSchemaRequest], - 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._UpdateSchema(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(SchemaServiceRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(SchemaServiceRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'SchemaServiceRestTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/__init__.py deleted file mode 100644 index 0355170e3569..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import SearchServiceClient -from .async_client import SearchServiceAsyncClient - -__all__ = ( - 'SearchServiceClient', - 'SearchServiceAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/async_client.py deleted file mode 100644 index 015496bf3c02..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/async_client.py +++ /dev/null @@ -1,402 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.discoveryengine_v1beta import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.discoveryengine_v1beta.services.search_service import pagers -from google.cloud.discoveryengine_v1beta.types import search_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport -from .client import SearchServiceClient - - -class SearchServiceAsyncClient: - """Service for search.""" - - _client: SearchServiceClient - - DEFAULT_ENDPOINT = SearchServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SearchServiceClient.DEFAULT_MTLS_ENDPOINT - - branch_path = staticmethod(SearchServiceClient.branch_path) - parse_branch_path = staticmethod(SearchServiceClient.parse_branch_path) - document_path = staticmethod(SearchServiceClient.document_path) - parse_document_path = staticmethod(SearchServiceClient.parse_document_path) - serving_config_path = staticmethod(SearchServiceClient.serving_config_path) - parse_serving_config_path = staticmethod(SearchServiceClient.parse_serving_config_path) - common_billing_account_path = staticmethod(SearchServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(SearchServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(SearchServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(SearchServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(SearchServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(SearchServiceClient.parse_common_organization_path) - common_project_path = staticmethod(SearchServiceClient.common_project_path) - parse_common_project_path = staticmethod(SearchServiceClient.parse_common_project_path) - common_location_path = staticmethod(SearchServiceClient.common_location_path) - parse_common_location_path = staticmethod(SearchServiceClient.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: - SearchServiceAsyncClient: The constructed client. - """ - return SearchServiceClient.from_service_account_info.__func__(SearchServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceAsyncClient: The constructed client. - """ - return SearchServiceClient.from_service_account_file.__func__(SearchServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return SearchServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> SearchServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SearchServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(SearchServiceClient).get_transport_class, type(SearchServiceClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, SearchServiceTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the search 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 (Union[str, ~.SearchServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = SearchServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def search(self, - request: Optional[Union[search_service.SearchRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchAsyncPager: - r"""Performs a search. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - async def sample_search(): - # Create a client - client = discoveryengine_v1beta.SearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.SearchRequest( - serving_config="serving_config_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1beta.types.SearchRequest, dict]]): - The request object. Request message for - [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1beta.services.search_service.pagers.SearchAsyncPager: - Response message for - [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - request = search_service.SearchRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.search, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config", request.serving_config), - )), - ) - - # 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.SearchAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "SearchServiceAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "SearchServiceAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/client.py deleted file mode 100644 index a4bc64a88839..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/client.py +++ /dev/null @@ -1,628 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.discoveryengine_v1beta import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.cloud.discoveryengine_v1beta.services.search_service import pagers -from google.cloud.discoveryengine_v1beta.types import search_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .transports.base import SearchServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import SearchServiceGrpcTransport -from .transports.grpc_asyncio import SearchServiceGrpcAsyncIOTransport -from .transports.rest import SearchServiceRestTransport - - -class SearchServiceClientMeta(type): - """Metaclass for the SearchService 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[SearchServiceTransport]] - _transport_registry["grpc"] = SearchServiceGrpcTransport - _transport_registry["grpc_asyncio"] = SearchServiceGrpcAsyncIOTransport - _transport_registry["rest"] = SearchServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[SearchServiceTransport]: - """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 SearchServiceClient(metaclass=SearchServiceClientMeta): - """Service for search.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - SearchServiceClient: 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: - SearchServiceClient: 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) -> SearchServiceTransport: - """Returns the transport used by the client instance. - - Returns: - SearchServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def branch_path(project: str,location: str,data_store: str,branch: str,) -> str: - """Returns a fully-qualified branch string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}".format(project=project, location=location, data_store=data_store, branch=branch, ) - - @staticmethod - def parse_branch_path(path: str) -> Dict[str,str]: - """Parses a branch path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def document_path(project: str,location: str,data_store: str,branch: str,document: str,) -> str: - """Returns a fully-qualified document string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) - - @staticmethod - def parse_document_path(path: str) -> Dict[str,str]: - """Parses a document path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)/documents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def serving_config_path(project: str,location: str,data_store: str,serving_config: str,) -> str: - """Returns a fully-qualified serving_config string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}/servingConfigs/{serving_config}".format(project=project, location=location, data_store=data_store, serving_config=serving_config, ) - - @staticmethod - def parse_serving_config_path(path: str) -> Dict[str,str]: - """Parses a serving_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/servingConfigs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, SearchServiceTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the search 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 (Union[str, SearchServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, SearchServiceTransport): - # transport is a SearchServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def search(self, - request: Optional[Union[search_service.SearchRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchPager: - r"""Performs a search. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - def sample_search(): - # Create a client - client = discoveryengine_v1beta.SearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.SearchRequest( - serving_config="serving_config_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1beta.types.SearchRequest, dict]): - The request object. Request message for - [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1beta.services.search_service.pagers.SearchPager: - Response message for - [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] - method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a search_service.SearchRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, search_service.SearchRequest): - request = search_service.SearchRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.search] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("serving_config", request.serving_config), - )), - ) - - # 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.SearchPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "SearchServiceClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - - - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "SearchServiceClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/pagers.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/pagers.py deleted file mode 100644 index cb898bf1e1a2..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.discoveryengine_v1beta.types import search_service - - -class SearchPager: - """A pager for iterating through ``search`` requests. - - This class thinly wraps an initial - :class:`google.cloud.discoveryengine_v1beta.types.SearchResponse` object, and - provides an ``__iter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``Search`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.discoveryengine_v1beta.types.SearchResponse` - 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[..., search_service.SearchResponse], - request: search_service.SearchRequest, - response: search_service.SearchResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.discoveryengine_v1beta.types.SearchRequest): - The initial request object. - response (google.cloud.discoveryengine_v1beta.types.SearchResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = search_service.SearchRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[search_service.SearchResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[search_service.SearchResponse.SearchResult]: - for page in self.pages: - yield from page.results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class SearchAsyncPager: - """A pager for iterating through ``search`` requests. - - This class thinly wraps an initial - :class:`google.cloud.discoveryengine_v1beta.types.SearchResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``Search`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.discoveryengine_v1beta.types.SearchResponse` - 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[search_service.SearchResponse]], - request: search_service.SearchRequest, - response: search_service.SearchResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.discoveryengine_v1beta.types.SearchRequest): - The initial request object. - response (google.cloud.discoveryengine_v1beta.types.SearchResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = search_service.SearchRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[search_service.SearchResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[search_service.SearchResponse.SearchResult]: - async def async_generator(): - async for page in self.pages: - for response in page.results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/__init__.py deleted file mode 100644 index 4282aef080e3..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import SearchServiceTransport -from .grpc import SearchServiceGrpcTransport -from .grpc_asyncio import SearchServiceGrpcAsyncIOTransport -from .rest import SearchServiceRestTransport -from .rest import SearchServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SearchServiceTransport]] -_transport_registry['grpc'] = SearchServiceGrpcTransport -_transport_registry['grpc_asyncio'] = SearchServiceGrpcAsyncIOTransport -_transport_registry['rest'] = SearchServiceRestTransport - -__all__ = ( - 'SearchServiceTransport', - 'SearchServiceGrpcTransport', - 'SearchServiceGrpcAsyncIOTransport', - 'SearchServiceRestTransport', - 'SearchServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/base.py deleted file mode 100644 index 0017b8de30e8..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/base.py +++ /dev/null @@ -1,168 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.discoveryengine_v1beta import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.discoveryengine_v1beta.types import search_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class SearchServiceTransport(abc.ABC): - """Abstract transport class for SearchService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'discoveryengine.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.search: gapic_v1.method.wrap_method( - self.search, - 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 search(self) -> Callable[ - [search_service.SearchRequest], - Union[ - search_service.SearchResponse, - Awaitable[search_service.SearchResponse] - ]]: - 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 kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'SearchServiceTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/grpc.py deleted file mode 100644 index 575f254d79c3..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/grpc.py +++ /dev/null @@ -1,302 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.discoveryengine_v1beta.types import search_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO - - -class SearchServiceGrpcTransport(SearchServiceTransport): - """gRPC backend transport for SearchService. - - Service for search. - - 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def search(self) -> Callable[ - [search_service.SearchRequest], - search_service.SearchResponse]: - r"""Return a callable for the search method over gRPC. - - Performs a search. - - Returns: - Callable[[~.SearchRequest], - ~.SearchResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search' not in self._stubs: - self._stubs['search'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.SearchService/Search', - request_serializer=search_service.SearchRequest.serialize, - response_deserializer=search_service.SearchResponse.deserialize, - ) - return self._stubs['search'] - - def close(self): - self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'SearchServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/grpc_asyncio.py deleted file mode 100644 index 3222cb6c4323..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,301 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.discoveryengine_v1beta.types import search_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import SearchServiceGrpcTransport - - -class SearchServiceGrpcAsyncIOTransport(SearchServiceTransport): - """gRPC AsyncIO backend transport for SearchService. - - Service for search. - - 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def search(self) -> Callable[ - [search_service.SearchRequest], - Awaitable[search_service.SearchResponse]]: - r"""Return a callable for the search method over gRPC. - - Performs a search. - - Returns: - Callable[[~.SearchRequest], - Awaitable[~.SearchResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'search' not in self._stubs: - self._stubs['search'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.SearchService/Search', - request_serializer=search_service.SearchRequest.serialize, - response_deserializer=search_service.SearchResponse.deserialize, - ) - return self._stubs['search'] - - def close(self): - return self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - -__all__ = ( - 'SearchServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/rest.py deleted file mode 100644 index 1fd752a5c08c..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/search_service/transports/rest.py +++ /dev/null @@ -1,576 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.cloud.location import locations_pb2 # type: ignore -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.discoveryengine_v1beta.types import search_service -from google.longrunning import operations_pb2 # type: ignore - -from .base import SearchServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class SearchServiceRestInterceptor: - """Interceptor for SearchService. - - 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 SearchServiceRestTransport. - - .. code-block:: python - class MyCustomSearchServiceInterceptor(SearchServiceRestInterceptor): - def pre_search(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_search(self, response): - logging.log(f"Received response: {response}") - return response - - transport = SearchServiceRestTransport(interceptor=MyCustomSearchServiceInterceptor()) - client = SearchServiceClient(transport=transport) - - - """ - def pre_search(self, request: search_service.SearchRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[search_service.SearchRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for search - - Override in a subclass to manipulate the request or metadata - before they are sent to the SearchService server. - """ - return request, metadata - - def post_search(self, response: search_service.SearchResponse) -> search_service.SearchResponse: - """Post-rpc interceptor for search - - Override in a subclass to manipulate the response - after it is returned by the SearchService server but before - it is returned to user code. - """ - return response - - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the SearchService 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 SearchService server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the SearchService 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 SearchService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class SearchServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: SearchServiceRestInterceptor - - -class SearchServiceRestTransport(SearchServiceTransport): - """REST backend transport for SearchService. - - Service for search. - - 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 = 'discoveryengine.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[SearchServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or SearchServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _Search(SearchServiceRestStub): - def __hash__(self): - return hash("Search") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: search_service.SearchRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> search_service.SearchResponse: - r"""Call the search method over HTTP. - - Args: - request (~.search_service.SearchRequest): - The request object. Request message for - [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.search_service.SearchResponse: - Response message for - [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] - method. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta/{serving_config=projects/*/locations/*/dataStores/*/servingConfigs/*}:search', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1beta/{serving_config=projects/*/locations/*/collections/*/dataStores/*/servingConfigs/*}:search', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_search(request, metadata) - pb_request = search_service.SearchRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = search_service.SearchResponse() - pb_resp = search_service.SearchResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_search(resp) - return resp - - @property - def search(self) -> Callable[ - [search_service.SearchRequest], - search_service.SearchResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._Search(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(SearchServiceRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(SearchServiceRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'SearchServiceRestTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/__init__.py deleted file mode 100644 index 387c002d1701..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import UserEventServiceClient -from .async_client import UserEventServiceAsyncClient - -__all__ = ( - 'UserEventServiceClient', - 'UserEventServiceAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/async_client.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/async_client.py deleted file mode 100644 index 03cc92de4659..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/async_client.py +++ /dev/null @@ -1,644 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.discoveryengine_v1beta import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.discoveryengine_v1beta.types import common -from google.cloud.discoveryengine_v1beta.types import import_config -from google.cloud.discoveryengine_v1beta.types import user_event -from google.cloud.discoveryengine_v1beta.types import user_event_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport -from .client import UserEventServiceClient - - -class UserEventServiceAsyncClient: - """Service for ingesting end user actions on a website to - Discovery Engine API. - """ - - _client: UserEventServiceClient - - DEFAULT_ENDPOINT = UserEventServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = UserEventServiceClient.DEFAULT_MTLS_ENDPOINT - - data_store_path = staticmethod(UserEventServiceClient.data_store_path) - parse_data_store_path = staticmethod(UserEventServiceClient.parse_data_store_path) - document_path = staticmethod(UserEventServiceClient.document_path) - parse_document_path = staticmethod(UserEventServiceClient.parse_document_path) - common_billing_account_path = staticmethod(UserEventServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(UserEventServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(UserEventServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(UserEventServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(UserEventServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(UserEventServiceClient.parse_common_organization_path) - common_project_path = staticmethod(UserEventServiceClient.common_project_path) - parse_common_project_path = staticmethod(UserEventServiceClient.parse_common_project_path) - common_location_path = staticmethod(UserEventServiceClient.common_location_path) - parse_common_location_path = staticmethod(UserEventServiceClient.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: - UserEventServiceAsyncClient: The constructed client. - """ - return UserEventServiceClient.from_service_account_info.__func__(UserEventServiceAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceAsyncClient: The constructed client. - """ - return UserEventServiceClient.from_service_account_file.__func__(UserEventServiceAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return UserEventServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> UserEventServiceTransport: - """Returns the transport used by the client instance. - - Returns: - UserEventServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(UserEventServiceClient).get_transport_class, type(UserEventServiceClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, UserEventServiceTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the user event 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 (Union[str, ~.UserEventServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = UserEventServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def write_user_event(self, - request: Optional[Union[user_event_service.WriteUserEventRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> user_event.UserEvent: - r"""Writes a single user event. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - async def sample_write_user_event(): - # Create a client - client = discoveryengine_v1beta.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.WriteUserEventRequest( - parent="parent_value", - ) - - # Make the request - response = await client.write_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1beta.types.WriteUserEventRequest, dict]]): - The request object. Request message for WriteUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1beta.types.UserEvent: - UserEvent captures all metadata - information Discovery Engine API needs - to know about how end users interact - with customers' website. - - """ - # Create or coerce a protobuf request object. - request = user_event_service.WriteUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.write_user_event, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def collect_user_event(self, - request: Optional[Union[user_event_service.CollectUserEventRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> httpbody_pb2.HttpBody: - r"""Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a third-party domain. - - This method is used only by the Discovery Engine API - JavaScript pixel and Google Tag Manager. Users should - not call this method directly. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - async def sample_collect_user_event(): - # Create a client - client = discoveryengine_v1beta.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = await client.collect_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1beta.types.CollectUserEventRequest, dict]]): - The request object. Request message for CollectUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It should only be used for - payload formats that can't be represented as JSON, - such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as - the response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request - fields and also want access to the raw HTTP body. - - Example: - - message GetResourceRequest { - // A unique request id. string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) - returns (google.api.HttpBody); - - rpc UpdateResource(google.api.HttpBody) - returns (google.protobuf.Empty); - - } - - Example with streaming methods: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - # Create or coerce a protobuf request object. - request = user_event_service.CollectUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.collect_user_event, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def import_user_events(self, - request: Optional[Union[import_config.ImportUserEventsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - async def sample_import_user_events(): - # Create a client - client = discoveryengine_v1beta.UserEventServiceAsyncClient() - - # Initialize request argument(s) - inline_source = discoveryengine_v1beta.InlineSource() - inline_source.user_events.event_type = "event_type_value" - inline_source.user_events.user_pseudo_id = "user_pseudo_id_value" - - request = discoveryengine_v1beta.ImportUserEventsRequest( - inline_source=inline_source, - parent="parent_value", - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.discoveryengine_v1beta.types.ImportUserEventsRequest, dict]]): - The request object. Request message for the - ImportUserEvents request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.discoveryengine_v1beta.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is - returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - request = import_config.ImportUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.import_user_events, - default_retry=retries.Retry( -initial=1.0,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=300.0, - ), - default_timeout=300.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - import_config.ImportUserEventsResponse, - metadata_type=import_config.ImportUserEventsMetadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "UserEventServiceAsyncClient": - return self - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "UserEventServiceAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/client.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/client.py deleted file mode 100644 index 298dd873dc24..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/client.py +++ /dev/null @@ -1,857 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.discoveryengine_v1beta import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.discoveryengine_v1beta.types import common -from google.cloud.discoveryengine_v1beta.types import import_config -from google.cloud.discoveryengine_v1beta.types import user_event -from google.cloud.discoveryengine_v1beta.types import user_event_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import UserEventServiceGrpcTransport -from .transports.grpc_asyncio import UserEventServiceGrpcAsyncIOTransport -from .transports.rest import UserEventServiceRestTransport - - -class UserEventServiceClientMeta(type): - """Metaclass for the UserEventService 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[UserEventServiceTransport]] - _transport_registry["grpc"] = UserEventServiceGrpcTransport - _transport_registry["grpc_asyncio"] = UserEventServiceGrpcAsyncIOTransport - _transport_registry["rest"] = UserEventServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[UserEventServiceTransport]: - """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 UserEventServiceClient(metaclass=UserEventServiceClientMeta): - """Service for ingesting end user actions on a website to - Discovery Engine API. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - UserEventServiceClient: 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: - UserEventServiceClient: 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) -> UserEventServiceTransport: - """Returns the transport used by the client instance. - - Returns: - UserEventServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def data_store_path(project: str,location: str,data_store: str,) -> str: - """Returns a fully-qualified data_store string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) - - @staticmethod - def parse_data_store_path(path: str) -> Dict[str,str]: - """Parses a data_store path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def document_path(project: str,location: str,data_store: str,branch: str,document: str,) -> str: - """Returns a fully-qualified document string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) - - @staticmethod - def parse_document_path(path: str) -> Dict[str,str]: - """Parses a document path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)/documents/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, UserEventServiceTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the user event 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 (Union[str, UserEventServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, UserEventServiceTransport): - # transport is a UserEventServiceTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def write_user_event(self, - request: Optional[Union[user_event_service.WriteUserEventRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> user_event.UserEvent: - r"""Writes a single user event. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - def sample_write_user_event(): - # Create a client - client = discoveryengine_v1beta.UserEventServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.WriteUserEventRequest( - parent="parent_value", - ) - - # Make the request - response = client.write_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1beta.types.WriteUserEventRequest, dict]): - The request object. Request message for WriteUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.discoveryengine_v1beta.types.UserEvent: - UserEvent captures all metadata - information Discovery Engine API needs - to know about how end users interact - with customers' website. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a user_event_service.WriteUserEventRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, user_event_service.WriteUserEventRequest): - request = user_event_service.WriteUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.write_user_event] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def collect_user_event(self, - request: Optional[Union[user_event_service.CollectUserEventRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> httpbody_pb2.HttpBody: - r"""Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a third-party domain. - - This method is used only by the Discovery Engine API - JavaScript pixel and Google Tag Manager. Users should - not call this method directly. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - def sample_collect_user_event(): - # Create a client - client = discoveryengine_v1beta.UserEventServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = client.collect_user_event(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1beta.types.CollectUserEventRequest, dict]): - The request object. Request message for CollectUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It should only be used for - payload formats that can't be represented as JSON, - such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as - the response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request - fields and also want access to the raw HTTP body. - - Example: - - message GetResourceRequest { - // A unique request id. string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) - returns (google.api.HttpBody); - - rpc UpdateResource(google.api.HttpBody) - returns (google.protobuf.Empty); - - } - - Example with streaming methods: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a user_event_service.CollectUserEventRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, user_event_service.CollectUserEventRequest): - request = user_event_service.CollectUserEventRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.collect_user_event] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def import_user_events(self, - request: Optional[Union[import_config.ImportUserEventsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import discoveryengine_v1beta - - def sample_import_user_events(): - # Create a client - client = discoveryengine_v1beta.UserEventServiceClient() - - # Initialize request argument(s) - inline_source = discoveryengine_v1beta.InlineSource() - inline_source.user_events.event_type = "event_type_value" - inline_source.user_events.user_pseudo_id = "user_pseudo_id_value" - - request = discoveryengine_v1beta.ImportUserEventsRequest( - inline_source=inline_source, - parent="parent_value", - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.discoveryengine_v1beta.types.ImportUserEventsRequest, dict]): - The request object. Request message for the - ImportUserEvents request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.discoveryengine_v1beta.types.ImportUserEventsResponse` Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is - returned by the - google.longrunning.Operations.response field if the - operation was successful. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a import_config.ImportUserEventsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, import_config.ImportUserEventsRequest): - request = import_config.ImportUserEventsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_user_events] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - import_config.ImportUserEventsResponse, - metadata_type=import_config.ImportUserEventsMetadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "UserEventServiceClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - - - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "UserEventServiceClient", -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/__init__.py deleted file mode 100644 index bea95d5a9d94..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import UserEventServiceTransport -from .grpc import UserEventServiceGrpcTransport -from .grpc_asyncio import UserEventServiceGrpcAsyncIOTransport -from .rest import UserEventServiceRestTransport -from .rest import UserEventServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[UserEventServiceTransport]] -_transport_registry['grpc'] = UserEventServiceGrpcTransport -_transport_registry['grpc_asyncio'] = UserEventServiceGrpcAsyncIOTransport -_transport_registry['rest'] = UserEventServiceRestTransport - -__all__ = ( - 'UserEventServiceTransport', - 'UserEventServiceGrpcTransport', - 'UserEventServiceGrpcAsyncIOTransport', - 'UserEventServiceRestTransport', - 'UserEventServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/base.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/base.py deleted file mode 100644 index 98e38316fc61..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/base.py +++ /dev/null @@ -1,211 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.discoveryengine_v1beta import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.discoveryengine_v1beta.types import import_config -from google.cloud.discoveryengine_v1beta.types import user_event -from google.cloud.discoveryengine_v1beta.types import user_event_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class UserEventServiceTransport(abc.ABC): - """Abstract transport class for UserEventService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'discoveryengine.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.write_user_event: gapic_v1.method.wrap_method( - self.write_user_event, - default_timeout=None, - client_info=client_info, - ), - self.collect_user_event: gapic_v1.method.wrap_method( - self.collect_user_event, - default_timeout=None, - client_info=client_info, - ), - self.import_user_events: gapic_v1.method.wrap_method( - self.import_user_events, - default_retry=retries.Retry( -initial=1.0,maximum=30.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=300.0, - ), - default_timeout=300.0, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - Union[ - user_event.UserEvent, - Awaitable[user_event.UserEvent] - ]]: - raise NotImplementedError() - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - Union[ - httpbody_pb2.HttpBody, - Awaitable[httpbody_pb2.HttpBody] - ]]: - raise NotImplementedError() - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'UserEventServiceTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/grpc.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/grpc.py deleted file mode 100644 index 92ec5065ce00..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/grpc.py +++ /dev/null @@ -1,389 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.discoveryengine_v1beta.types import import_config -from google.cloud.discoveryengine_v1beta.types import user_event -from google.cloud.discoveryengine_v1beta.types import user_event_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO - - -class UserEventServiceGrpcTransport(UserEventServiceTransport): - """gRPC backend transport for UserEventService. - - Service for ingesting end user actions on a website to - Discovery Engine 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 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - user_event.UserEvent]: - r"""Return a callable for the write user event method over gRPC. - - Writes a single user event. - - Returns: - Callable[[~.WriteUserEventRequest], - ~.UserEvent]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'write_user_event' not in self._stubs: - self._stubs['write_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.UserEventService/WriteUserEvent', - request_serializer=user_event_service.WriteUserEventRequest.serialize, - response_deserializer=user_event.UserEvent.deserialize, - ) - return self._stubs['write_user_event'] - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - httpbody_pb2.HttpBody]: - r"""Return a callable for the collect user event method over gRPC. - - Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a third-party domain. - - This method is used only by the Discovery Engine API - JavaScript pixel and Google Tag Manager. Users should - not call this method directly. - - Returns: - Callable[[~.CollectUserEventRequest], - ~.HttpBody]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'collect_user_event' not in self._stubs: - self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.UserEventService/CollectUserEvent', - request_serializer=user_event_service.CollectUserEventRequest.serialize, - response_deserializer=httpbody_pb2.HttpBody.FromString, - ) - return self._stubs['collect_user_event'] - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - operations_pb2.Operation]: - r"""Return a callable for the import user events method over gRPC. - - Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - Returns: - Callable[[~.ImportUserEventsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_user_events' not in self._stubs: - self._stubs['import_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.UserEventService/ImportUserEvents', - request_serializer=import_config.ImportUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_user_events'] - - def close(self): - self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'UserEventServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/grpc_asyncio.py deleted file mode 100644 index d3d622275528..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,388 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.discoveryengine_v1beta.types import import_config -from google.cloud.discoveryengine_v1beta.types import user_event -from google.cloud.discoveryengine_v1beta.types import user_event_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import UserEventServiceGrpcTransport - - -class UserEventServiceGrpcAsyncIOTransport(UserEventServiceTransport): - """gRPC AsyncIO backend transport for UserEventService. - - Service for ingesting end user actions on a website to - Discovery Engine 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 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - Awaitable[user_event.UserEvent]]: - r"""Return a callable for the write user event method over gRPC. - - Writes a single user event. - - Returns: - Callable[[~.WriteUserEventRequest], - Awaitable[~.UserEvent]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'write_user_event' not in self._stubs: - self._stubs['write_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.UserEventService/WriteUserEvent', - request_serializer=user_event_service.WriteUserEventRequest.serialize, - response_deserializer=user_event.UserEvent.deserialize, - ) - return self._stubs['write_user_event'] - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - Awaitable[httpbody_pb2.HttpBody]]: - r"""Return a callable for the collect user event method over gRPC. - - Writes a single user event from the browser. This - uses a GET request to due to browser restriction of - POST-ing to a third-party domain. - - This method is used only by the Discovery Engine API - JavaScript pixel and Google Tag Manager. Users should - not call this method directly. - - Returns: - Callable[[~.CollectUserEventRequest], - Awaitable[~.HttpBody]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'collect_user_event' not in self._stubs: - self._stubs['collect_user_event'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.UserEventService/CollectUserEvent', - request_serializer=user_event_service.CollectUserEventRequest.serialize, - response_deserializer=httpbody_pb2.HttpBody.FromString, - ) - return self._stubs['collect_user_event'] - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the import user events method over gRPC. - - Bulk import of User events. Request processing might - be synchronous. Events that already exist are skipped. - Use this method for backfilling historical user events. - - Operation.response is of type ImportResponse. Note that - it is possible for a subset of the items to be - successfully inserted. Operation.metadata is of type - ImportMetadata. - - Returns: - Callable[[~.ImportUserEventsRequest], - 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 'import_user_events' not in self._stubs: - self._stubs['import_user_events'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1beta.UserEventService/ImportUserEvents', - request_serializer=import_config.ImportUserEventsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['import_user_events'] - - def close(self): - return self.grpc_channel.close() - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - -__all__ = ( - 'UserEventServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/rest.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/rest.py deleted file mode 100644 index 4f42389166b8..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/services/user_event_service/transports/rest.py +++ /dev/null @@ -1,1005 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.cloud.location import locations_pb2 # type: ignore -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.discoveryengine_v1beta.types import import_config -from google.cloud.discoveryengine_v1beta.types import user_event -from google.cloud.discoveryengine_v1beta.types import user_event_service -from google.longrunning import operations_pb2 # type: ignore - -from .base import UserEventServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class UserEventServiceRestInterceptor: - """Interceptor for UserEventService. - - 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 UserEventServiceRestTransport. - - .. code-block:: python - class MyCustomUserEventServiceInterceptor(UserEventServiceRestInterceptor): - def pre_collect_user_event(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_collect_user_event(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_import_user_events(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_import_user_events(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_write_user_event(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_write_user_event(self, response): - logging.log(f"Received response: {response}") - return response - - transport = UserEventServiceRestTransport(interceptor=MyCustomUserEventServiceInterceptor()) - client = UserEventServiceClient(transport=transport) - - - """ - def pre_collect_user_event(self, request: user_event_service.CollectUserEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[user_event_service.CollectUserEventRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for collect_user_event - - Override in a subclass to manipulate the request or metadata - before they are sent to the UserEventService server. - """ - return request, metadata - - def post_collect_user_event(self, response: httpbody_pb2.HttpBody) -> httpbody_pb2.HttpBody: - """Post-rpc interceptor for collect_user_event - - Override in a subclass to manipulate the response - after it is returned by the UserEventService server but before - it is returned to user code. - """ - return response - def pre_import_user_events(self, request: import_config.ImportUserEventsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[import_config.ImportUserEventsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for import_user_events - - Override in a subclass to manipulate the request or metadata - before they are sent to the UserEventService server. - """ - return request, metadata - - def post_import_user_events(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for import_user_events - - Override in a subclass to manipulate the response - after it is returned by the UserEventService server but before - it is returned to user code. - """ - return response - def pre_write_user_event(self, request: user_event_service.WriteUserEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[user_event_service.WriteUserEventRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for write_user_event - - Override in a subclass to manipulate the request or metadata - before they are sent to the UserEventService server. - """ - return request, metadata - - def post_write_user_event(self, response: user_event.UserEvent) -> user_event.UserEvent: - """Post-rpc interceptor for write_user_event - - Override in a subclass to manipulate the response - after it is returned by the UserEventService server but before - it is returned to user code. - """ - return response - - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the UserEventService 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 UserEventService server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the UserEventService 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 UserEventService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class UserEventServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: UserEventServiceRestInterceptor - - -class UserEventServiceRestTransport(UserEventServiceTransport): - """REST backend transport for UserEventService. - - Service for ingesting end user actions on a website to - Discovery Engine 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 = 'discoveryengine.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[UserEventServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or UserEventServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*}/operations', - }, - { - 'method': 'get', - 'uri': '/v1beta/{name=projects/*}/operations', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1beta") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _CollectUserEvent(UserEventServiceRestStub): - def __hash__(self): - return hash("CollectUserEvent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "userEvent" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: user_event_service.CollectUserEventRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> httpbody_pb2.HttpBody: - r"""Call the collect user event method over HTTP. - - Args: - request (~.user_event_service.CollectUserEventRequest): - The request object. Request message for CollectUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It - should only be used for payload formats that can't be - represented as JSON, such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as the - response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request fields - and also want access to the raw HTTP body. - - Example: - - :: - - message GetResourceRequest { - // A unique request id. - string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) - returns (google.api.HttpBody); - rpc UpdateResource(google.api.HttpBody) - returns (google.protobuf.Empty); - - } - - Example with streaming methods: - - :: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{parent=projects/*/locations/*/dataStores/*}/userEvents:collect', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{parent=projects/*/locations/*/collections/*/dataStores/*}/userEvents:collect', - }, - ] - request, metadata = self._interceptor.pre_collect_user_event(request, metadata) - pb_request = user_event_service.CollectUserEventRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = httpbody_pb2.HttpBody() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_collect_user_event(resp) - return resp - - class _ImportUserEvents(UserEventServiceRestStub): - def __hash__(self): - return hash("ImportUserEvents") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: import_config.ImportUserEventsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the import user events method over HTTP. - - Args: - request (~.import_config.ImportUserEventsRequest): - The request object. Request message for the - ImportUserEvents request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta/{parent=projects/*/locations/*/dataStores/*}/userEvents:import', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1beta/{parent=projects/*/locations/*/collections/*/dataStores/*}/userEvents:import', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_import_user_events(request, metadata) - pb_request = import_config.ImportUserEventsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_import_user_events(resp) - return resp - - class _WriteUserEvent(UserEventServiceRestStub): - def __hash__(self): - return hash("WriteUserEvent") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: user_event_service.WriteUserEventRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> user_event.UserEvent: - r"""Call the write user event method over HTTP. - - Args: - request (~.user_event_service.WriteUserEventRequest): - The request object. Request message for WriteUserEvent - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.user_event.UserEvent: - UserEvent captures all metadata - information Discovery Engine API needs - to know about how end users interact - with customers' website. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1beta/{parent=projects/*/locations/*/dataStores/*}/userEvents:write', - 'body': 'user_event', - }, -{ - 'method': 'post', - 'uri': '/v1beta/{parent=projects/*/locations/*/collections/*/dataStores/*}/userEvents:write', - 'body': 'user_event', - }, - ] - request, metadata = self._interceptor.pre_write_user_event(request, metadata) - pb_request = user_event_service.WriteUserEventRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = user_event.UserEvent() - pb_resp = user_event.UserEvent.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_write_user_event(resp) - return resp - - @property - def collect_user_event(self) -> Callable[ - [user_event_service.CollectUserEventRequest], - httpbody_pb2.HttpBody]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CollectUserEvent(self._session, self._host, self._interceptor) # type: ignore - - @property - def import_user_events(self) -> Callable[ - [import_config.ImportUserEventsRequest], - 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._ImportUserEvents(self._session, self._host, self._interceptor) # type: ignore - - @property - def write_user_event(self) -> Callable[ - [user_event_service.WriteUserEventRequest], - user_event.UserEvent]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._WriteUserEvent(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(UserEventServiceRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(UserEventServiceRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*/engines/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/collections/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*/locations/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1beta/{name=projects/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'UserEventServiceRestTransport', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/__init__.py deleted file mode 100644 index 8b5d1aef0fda..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/__init__.py +++ /dev/null @@ -1,170 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .common import ( - CustomAttribute, - DoubleList, - Interval, - UserInfo, -) -from .completion_service import ( - CompleteQueryRequest, - CompleteQueryResponse, -) -from .conversation import ( - Conversation, - ConversationContext, - ConversationMessage, - Reply, - TextInput, -) -from .conversational_search_service import ( - ConverseConversationRequest, - ConverseConversationResponse, - CreateConversationRequest, - DeleteConversationRequest, - GetConversationRequest, - ListConversationsRequest, - ListConversationsResponse, - UpdateConversationRequest, -) -from .document import ( - Document, -) -from .document_service import ( - CreateDocumentRequest, - DeleteDocumentRequest, - GetDocumentRequest, - ListDocumentsRequest, - ListDocumentsResponse, - UpdateDocumentRequest, -) -from .import_config import ( - BigQuerySource, - GcsSource, - ImportDocumentsMetadata, - ImportDocumentsRequest, - ImportDocumentsResponse, - ImportErrorConfig, - ImportUserEventsMetadata, - ImportUserEventsRequest, - ImportUserEventsResponse, -) -from .purge_config import ( - PurgeDocumentsMetadata, - PurgeDocumentsRequest, - PurgeDocumentsResponse, -) -from .recommendation_service import ( - RecommendRequest, - RecommendResponse, -) -from .schema import ( - Schema, -) -from .schema_service import ( - CreateSchemaMetadata, - CreateSchemaRequest, - DeleteSchemaMetadata, - DeleteSchemaRequest, - GetSchemaRequest, - ListSchemasRequest, - ListSchemasResponse, - UpdateSchemaMetadata, - UpdateSchemaRequest, -) -from .search_service import ( - SearchRequest, - SearchResponse, -) -from .user_event import ( - CompletionInfo, - DocumentInfo, - MediaInfo, - PageInfo, - PanelInfo, - SearchInfo, - TransactionInfo, - UserEvent, -) -from .user_event_service import ( - CollectUserEventRequest, - WriteUserEventRequest, -) - -__all__ = ( - 'CustomAttribute', - 'DoubleList', - 'Interval', - 'UserInfo', - 'CompleteQueryRequest', - 'CompleteQueryResponse', - 'Conversation', - 'ConversationContext', - 'ConversationMessage', - 'Reply', - 'TextInput', - 'ConverseConversationRequest', - 'ConverseConversationResponse', - 'CreateConversationRequest', - 'DeleteConversationRequest', - 'GetConversationRequest', - 'ListConversationsRequest', - 'ListConversationsResponse', - 'UpdateConversationRequest', - 'Document', - 'CreateDocumentRequest', - 'DeleteDocumentRequest', - 'GetDocumentRequest', - 'ListDocumentsRequest', - 'ListDocumentsResponse', - 'UpdateDocumentRequest', - 'BigQuerySource', - 'GcsSource', - 'ImportDocumentsMetadata', - 'ImportDocumentsRequest', - 'ImportDocumentsResponse', - 'ImportErrorConfig', - 'ImportUserEventsMetadata', - 'ImportUserEventsRequest', - 'ImportUserEventsResponse', - 'PurgeDocumentsMetadata', - 'PurgeDocumentsRequest', - 'PurgeDocumentsResponse', - 'RecommendRequest', - 'RecommendResponse', - 'Schema', - 'CreateSchemaMetadata', - 'CreateSchemaRequest', - 'DeleteSchemaMetadata', - 'DeleteSchemaRequest', - 'GetSchemaRequest', - 'ListSchemasRequest', - 'ListSchemasResponse', - 'UpdateSchemaMetadata', - 'UpdateSchemaRequest', - 'SearchRequest', - 'SearchResponse', - 'CompletionInfo', - 'DocumentInfo', - 'MediaInfo', - 'PageInfo', - 'PanelInfo', - 'SearchInfo', - 'TransactionInfo', - 'UserEvent', - 'CollectUserEventRequest', - 'WriteUserEventRequest', -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/common.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/common.py deleted file mode 100644 index a677438ff182..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/common.py +++ /dev/null @@ -1,182 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1beta', - manifest={ - 'Interval', - 'CustomAttribute', - 'UserInfo', - 'DoubleList', - }, -) - - -class Interval(proto.Message): - r"""A floating point interval. - - 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: - minimum (float): - Inclusive lower bound. - - This field is a member of `oneof`_ ``min``. - exclusive_minimum (float): - Exclusive lower bound. - - This field is a member of `oneof`_ ``min``. - maximum (float): - Inclusive upper bound. - - This field is a member of `oneof`_ ``max``. - exclusive_maximum (float): - Exclusive upper bound. - - This field is a member of `oneof`_ ``max``. - """ - - minimum: float = proto.Field( - proto.DOUBLE, - number=1, - oneof='min', - ) - exclusive_minimum: float = proto.Field( - proto.DOUBLE, - number=2, - oneof='min', - ) - maximum: float = proto.Field( - proto.DOUBLE, - number=3, - oneof='max', - ) - exclusive_maximum: float = proto.Field( - proto.DOUBLE, - number=4, - oneof='max', - ) - - -class CustomAttribute(proto.Message): - r"""A custom attribute that is not explicitly modeled in a resource, - e.g. [UserEvent][google.cloud.discoveryengine.v1beta.UserEvent]. - - Attributes: - text (MutableSequence[str]): - The textual values of this custom attribute. For example, - ``["yellow", "green"]`` when the key is "color". - - Empty string is not allowed. Otherwise, an - ``INVALID_ARGUMENT`` error is returned. - - Exactly one of - [CustomAttribute.text][google.cloud.discoveryengine.v1beta.CustomAttribute.text] - or - [CustomAttribute.numbers][google.cloud.discoveryengine.v1beta.CustomAttribute.numbers] - should be set. Otherwise, an ``INVALID_ARGUMENT`` error is - returned. - numbers (MutableSequence[float]): - The numerical values of this custom attribute. For example, - ``[2.3, 15.4]`` when the key is "lengths_cm". - - Exactly one of - [CustomAttribute.text][google.cloud.discoveryengine.v1beta.CustomAttribute.text] - or - [CustomAttribute.numbers][google.cloud.discoveryengine.v1beta.CustomAttribute.numbers] - should be set. Otherwise, an ``INVALID_ARGUMENT`` error is - returned. - """ - - text: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - numbers: MutableSequence[float] = proto.RepeatedField( - proto.DOUBLE, - number=2, - ) - - -class UserInfo(proto.Message): - r"""Information of an end user. - - Attributes: - user_id (str): - Highly recommended for logged-in users. Unique identifier - for logged-in user, such as a user name. Don't set for - anonymous users. - - Always use a hashed value for this ID. - - Don't set the field to the same fixed ID for different - users. This mixes the event history of those users together, - which results in degraded model quality. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an ``INVALID_ARGUMENT`` error - is returned. - user_agent (str): - User agent as included in the HTTP header. - - The field must be a UTF-8 encoded string with a length limit - of 1,000 characters. Otherwise, an ``INVALID_ARGUMENT`` - error is returned. - - This should not be set when using the client side event - reporting with GTM or JavaScript tag in - [UserEventService.CollectUserEvent][google.cloud.discoveryengine.v1beta.UserEventService.CollectUserEvent] - or if - [UserEvent.direct_user_request][google.cloud.discoveryengine.v1beta.UserEvent.direct_user_request] - is set. - """ - - user_id: str = proto.Field( - proto.STRING, - number=1, - ) - user_agent: str = proto.Field( - proto.STRING, - number=2, - ) - - -class DoubleList(proto.Message): - r"""Double list. - - Attributes: - values (MutableSequence[float]): - Double values. - """ - - values: MutableSequence[float] = proto.RepeatedField( - proto.DOUBLE, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/completion_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/completion_service.py deleted file mode 100644 index 78d40101d69b..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/completion_service.py +++ /dev/null @@ -1,158 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1beta', - manifest={ - 'CompleteQueryRequest', - 'CompleteQueryResponse', - }, -) - - -class CompleteQueryRequest(proto.Message): - r"""Request message for - [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1beta.CompletionService.CompleteQuery] - method. - - Attributes: - data_store (str): - Required. The parent data store resource name for which the - completion is performed, such as - ``projects/*/locations/global/collections/default_collection/dataStores/default_data_store``. - query (str): - Required. The typeahead input used to fetch - suggestions. Maximum length is 128 characters. - query_model (str): - Selects data model of query suggestions for serving. - Currently supported values: - - - ``document`` - Using suggestions generated from - user-imported documents. - - ``search-history`` - Using suggestions generated from the - past history of - [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] - API calls. Do not use it when there is no traffic for - Search API. - - ``user-event`` - Using suggestions generated from - user-imported search events. - - ``document-completable`` - Using suggestions taken - directly from user-imported document fields marked as - completable. - - Default values: - - - ``document`` is the default model for regular dataStores. - - ``search-history`` is the default model for - [IndustryVertical.SITE_SEARCH][] dataStores. - user_pseudo_id (str): - A unique identifier for tracking visitors. For example, this - could be implemented with an HTTP cookie, which should be - able to uniquely identify a visitor on a single device. This - unique identifier should not change if the visitor logs in - or out of the website. - - This field should NOT have a fixed value such as - ``unknown_visitor``. - - This should be the same identifier as - [UserEvent.user_pseudo_id][google.cloud.discoveryengine.v1beta.UserEvent.user_pseudo_id] - and - [SearchRequest.user_pseudo_id][google.cloud.discoveryengine.v1beta.SearchRequest.user_pseudo_id]. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an ``INVALID_ARGUMENT`` error - is returned. - include_tail_suggestions (bool): - Indicates if tail suggestions should be - returned if there are no suggestions that match - the full query. Even if set to true, if there - are suggestions that match the full query, those - are returned and no tail suggestions are - returned. - """ - - data_store: str = proto.Field( - proto.STRING, - number=1, - ) - query: str = proto.Field( - proto.STRING, - number=2, - ) - query_model: str = proto.Field( - proto.STRING, - number=3, - ) - user_pseudo_id: str = proto.Field( - proto.STRING, - number=4, - ) - include_tail_suggestions: bool = proto.Field( - proto.BOOL, - number=5, - ) - - -class CompleteQueryResponse(proto.Message): - r"""Response message for - [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1beta.CompletionService.CompleteQuery] - method. - - Attributes: - query_suggestions (MutableSequence[google.cloud.discoveryengine_v1beta.types.CompleteQueryResponse.QuerySuggestion]): - Results of the matched query suggestions. The - result list is ordered and the first result is a - top suggestion. - tail_match_triggered (bool): - True if the returned suggestions are all tail suggestions. - - For tail matching to be triggered, include_tail_suggestions - in the request must be true and there must be no suggestions - that match the full query. - """ - - class QuerySuggestion(proto.Message): - r"""Suggestions as search queries. - - Attributes: - suggestion (str): - The suggestion for the query. - """ - - suggestion: str = proto.Field( - proto.STRING, - number=1, - ) - - query_suggestions: MutableSequence[QuerySuggestion] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=QuerySuggestion, - ) - tail_match_triggered: bool = proto.Field( - proto.BOOL, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/conversation.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/conversation.py deleted file mode 100644 index d82afb7df677..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/conversation.py +++ /dev/null @@ -1,248 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.discoveryengine_v1beta.types import search_service -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1beta', - manifest={ - 'Conversation', - 'Reply', - 'ConversationContext', - 'TextInput', - 'ConversationMessage', - }, -) - - -class Conversation(proto.Message): - r"""External conversation proto definition. - - Attributes: - name (str): - Immutable. Fully qualified name - ``project/*/locations/global/collections/{collection}/dataStore/*/conversations/*`` - state (google.cloud.discoveryengine_v1beta.types.Conversation.State): - The state of the Conversation. - user_pseudo_id (str): - A unique identifier for tracking users. - messages (MutableSequence[google.cloud.discoveryengine_v1beta.types.ConversationMessage]): - Conversation messages. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time the conversation - started. - end_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time the conversation - finished. - """ - class State(proto.Enum): - r"""Enumeration of the state of the conversation. - - Values: - STATE_UNSPECIFIED (0): - Unknown. - IN_PROGRESS (1): - Conversation is currently open. - COMPLETED (2): - Conversation has been completed. - """ - STATE_UNSPECIFIED = 0 - IN_PROGRESS = 1 - COMPLETED = 2 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - state: State = proto.Field( - proto.ENUM, - number=2, - enum=State, - ) - user_pseudo_id: str = proto.Field( - proto.STRING, - number=3, - ) - messages: MutableSequence['ConversationMessage'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='ConversationMessage', - ) - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - - -class Reply(proto.Message): - r"""Defines a reply message to user. - - Attributes: - reply (str): - DEPRECATED: use ``summary`` instead. Text reply. - references (MutableSequence[google.cloud.discoveryengine_v1beta.types.Reply.Reference]): - References in the reply. - summary (google.cloud.discoveryengine_v1beta.types.SearchResponse.Summary): - Summary based on search results. - """ - - class Reference(proto.Message): - r"""Defines reference in reply. - - Attributes: - uri (str): - URI link reference. - anchor_text (str): - Anchor text. - start (int): - Anchor text start index. - end (int): - Anchor text end index. - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - ) - anchor_text: str = proto.Field( - proto.STRING, - number=2, - ) - start: int = proto.Field( - proto.INT32, - number=3, - ) - end: int = proto.Field( - proto.INT32, - number=4, - ) - - reply: str = proto.Field( - proto.STRING, - number=1, - ) - references: MutableSequence[Reference] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=Reference, - ) - summary: search_service.SearchResponse.Summary = proto.Field( - proto.MESSAGE, - number=3, - message=search_service.SearchResponse.Summary, - ) - - -class ConversationContext(proto.Message): - r"""Defines context of the conversation - - Attributes: - context_documents (MutableSequence[str]): - The current list of documents the user is - seeing. It contains the document resource - references. - active_document (str): - The current active document the user opened. - It contains the document resource reference. - """ - - context_documents: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - active_document: str = proto.Field( - proto.STRING, - number=2, - ) - - -class TextInput(proto.Message): - r"""Defines text input. - - Attributes: - input (str): - Text input. - context (google.cloud.discoveryengine_v1beta.types.ConversationContext): - Conversation context of the input. - """ - - input: str = proto.Field( - proto.STRING, - number=1, - ) - context: 'ConversationContext' = proto.Field( - proto.MESSAGE, - number=2, - message='ConversationContext', - ) - - -class ConversationMessage(proto.Message): - r"""Defines a conversation 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: - user_input (google.cloud.discoveryengine_v1beta.types.TextInput): - User text input. - - This field is a member of `oneof`_ ``message``. - reply (google.cloud.discoveryengine_v1beta.types.Reply): - Search reply. - - This field is a member of `oneof`_ ``message``. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Message creation timestamp. - """ - - user_input: 'TextInput' = proto.Field( - proto.MESSAGE, - number=1, - oneof='message', - message='TextInput', - ) - reply: 'Reply' = proto.Field( - proto.MESSAGE, - number=2, - oneof='message', - message='Reply', - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/conversational_search_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/conversational_search_service.py deleted file mode 100644 index 8cd4858004e9..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/conversational_search_service.py +++ /dev/null @@ -1,328 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.discoveryengine_v1beta.types import conversation as gcd_conversation -from google.cloud.discoveryengine_v1beta.types import search_service -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1beta', - manifest={ - 'ConverseConversationRequest', - 'ConverseConversationResponse', - 'CreateConversationRequest', - 'UpdateConversationRequest', - 'DeleteConversationRequest', - 'GetConversationRequest', - 'ListConversationsRequest', - 'ListConversationsResponse', - }, -) - - -class ConverseConversationRequest(proto.Message): - r"""Request message for - [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1beta.ConversationalSearchService.ConverseConversation] - method. - - Attributes: - name (str): - Required. The resource name of the Conversation to get. - Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}``. - Use - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/-`` - to activate auto session mode, which automatically creates a - new conversation inside a ConverseConversation session. - query (google.cloud.discoveryengine_v1beta.types.TextInput): - Required. Current user input. - serving_config (str): - The resource name of the Serving Config to use. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/servingConfigs/{serving_config_id}`` - If this is not set, the default serving config will be used. - conversation (google.cloud.discoveryengine_v1beta.types.Conversation): - The conversation to be used by auto session - only. The name field will be ignored as we - automatically assign new name for the - conversation in auto session. - safe_search (bool): - Whether to turn on safe search. - user_labels (MutableMapping[str, str]): - The user labels applied to a resource must meet the - following requirements: - - - Each resource can have multiple labels, up to a maximum - of 64. - - Each label must be a key-value pair. - - Keys have a minimum length of 1 character and a maximum - length of 63 characters and cannot be empty. Values can - be empty and have a maximum length of 63 characters. - - Keys and values can contain only lowercase letters, - numeric characters, underscores, and dashes. All - characters must use UTF-8 encoding, and international - characters are allowed. - - The key portion of a label must be unique. However, you - can use the same key with multiple resources. - - Keys must start with a lowercase letter or international - character. - - See `Google Cloud - Document `__ - for more details. - summary_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.ContentSearchSpec.SummarySpec): - A specification for configuring the summary - returned in the response. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - query: gcd_conversation.TextInput = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_conversation.TextInput, - ) - serving_config: str = proto.Field( - proto.STRING, - number=3, - ) - conversation: gcd_conversation.Conversation = proto.Field( - proto.MESSAGE, - number=5, - message=gcd_conversation.Conversation, - ) - safe_search: bool = proto.Field( - proto.BOOL, - number=6, - ) - user_labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=7, - ) - summary_spec: search_service.SearchRequest.ContentSearchSpec.SummarySpec = proto.Field( - proto.MESSAGE, - number=8, - message=search_service.SearchRequest.ContentSearchSpec.SummarySpec, - ) - - -class ConverseConversationResponse(proto.Message): - r"""Response message for - [ConversationalSearchService.ConverseConversation][google.cloud.discoveryengine.v1beta.ConversationalSearchService.ConverseConversation] - method. - - Attributes: - reply (google.cloud.discoveryengine_v1beta.types.Reply): - Answer to the current query. - conversation (google.cloud.discoveryengine_v1beta.types.Conversation): - Updated conversation including the answer. - related_questions (MutableSequence[str]): - Suggested related questions. - search_results (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchResponse.SearchResult]): - Search Results. - """ - - reply: gcd_conversation.Reply = proto.Field( - proto.MESSAGE, - number=1, - message=gcd_conversation.Reply, - ) - conversation: gcd_conversation.Conversation = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_conversation.Conversation, - ) - related_questions: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=6, - ) - search_results: MutableSequence[search_service.SearchResponse.SearchResult] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=search_service.SearchResponse.SearchResult, - ) - - -class CreateConversationRequest(proto.Message): - r"""Request for CreateConversation method. - - Attributes: - parent (str): - Required. Full resource name of parent data store. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` - conversation (google.cloud.discoveryengine_v1beta.types.Conversation): - Required. The conversation to create. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - conversation: gcd_conversation.Conversation = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_conversation.Conversation, - ) - - -class UpdateConversationRequest(proto.Message): - r"""Request for UpdateConversation method. - - Attributes: - conversation (google.cloud.discoveryengine_v1beta.types.Conversation): - Required. The Conversation to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Indicates which fields in the provided - [Conversation][google.cloud.discoveryengine.v1beta.Conversation] - to update. The following are NOT supported: - - - [conversation.name][] - - If not set or empty, all supported fields are updated. - """ - - conversation: gcd_conversation.Conversation = proto.Field( - proto.MESSAGE, - number=1, - message=gcd_conversation.Conversation, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteConversationRequest(proto.Message): - r"""Request for DeleteConversation method. - - Attributes: - name (str): - Required. The resource name of the Conversation to delete. - Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetConversationRequest(proto.Message): - r"""Request for GetConversation method. - - Attributes: - name (str): - Required. The resource name of the Conversation to get. - Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}/conversations/{conversation_id}`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListConversationsRequest(proto.Message): - r"""Request for ListConversations method. - - Attributes: - parent (str): - Required. The data store resource name. Format: - ``projects/{project_number}/locations/{location_id}/collections/{collection}/dataStores/{data_store_id}`` - page_size (int): - Maximum number of results to return. If - unspecified, defaults to 50. Max allowed value - is 1000. - page_token (str): - A page token, received from a previous ``ListConversations`` - call. Provide this to retrieve the subsequent page. - filter (str): - A filter to apply on the list results. The supported - features are: user_pseudo_id, state. - - Example: "user_pseudo_id = some_id". - order_by (str): - A comma-separated list of fields to order by, sorted in - ascending order. Use "desc" after a field name for - descending. Supported fields: - - - ``update_time`` - - ``create_time`` - - ``conversation_name`` - - Example: "update_time desc" "create_time". - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - order_by: str = proto.Field( - proto.STRING, - number=5, - ) - - -class ListConversationsResponse(proto.Message): - r"""Response for ListConversations method. - - Attributes: - conversations (MutableSequence[google.cloud.discoveryengine_v1beta.types.Conversation]): - All the Conversations for a given data store. - next_page_token (str): - Pagination token, if not returned indicates - the last page. - """ - - @property - def raw_page(self): - return self - - conversations: MutableSequence[gcd_conversation.Conversation] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcd_conversation.Conversation, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/document.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/document.py deleted file mode 100644 index 98e34b090864..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/document.py +++ /dev/null @@ -1,189 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1beta', - manifest={ - 'Document', - }, -) - - -class Document(proto.Message): - r"""Document captures all raw metadata information of items to be - recommended or searched. - - 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: - struct_data (google.protobuf.struct_pb2.Struct): - The structured JSON data for the document. It should conform - to the registered - [Schema][google.cloud.discoveryengine.v1beta.Schema] or an - ``INVALID_ARGUMENT`` error is thrown. - - This field is a member of `oneof`_ ``data``. - json_data (str): - The JSON string representation of the document. It should - conform to the registered - [Schema][google.cloud.discoveryengine.v1beta.Schema] or an - ``INVALID_ARGUMENT`` error is thrown. - - This field is a member of `oneof`_ ``data``. - name (str): - Immutable. The full resource name of the document. Format: - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document_id}``. - - This field must be a UTF-8 encoded string with a length - limit of 1024 characters. - id (str): - Immutable. The identifier of the document. - - Id should conform to - `RFC-1034 `__ standard - with a length limit of 63 characters. - schema_id (str): - The identifier of the schema located in the - same data store. - content (google.cloud.discoveryengine_v1beta.types.Document.Content): - The unstructured data linked to this document. Content must - be set if this document is under a ``CONTENT_REQUIRED`` data - store. - parent_document_id (str): - The identifier of the parent document. Currently supports at - most two level document hierarchy. - - Id should conform to - `RFC-1034 `__ standard - with a length limit of 63 characters. - derived_struct_data (google.protobuf.struct_pb2.Struct): - Output only. This field is OUTPUT_ONLY. It contains derived - data that are not in the original input document. - """ - - class Content(proto.Message): - r"""Unstructured data linked to this document. - - 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: - raw_bytes (bytes): - The content represented as a stream of bytes. The maximum - length is 1,000,000 bytes (1 MB / ~0.95 MiB). - - Note: As with all ``bytes`` fields, this field is - represented as pure binary in Protocol Buffers and - base64-encoded string in JSON. For example, - ``abc123!?$*&()'-=@~`` should be represented as - ``YWJjMTIzIT8kKiYoKSctPUB+`` in JSON. See - https://developers.google.com/protocol-buffers/docs/proto3#json. - - This field is a member of `oneof`_ ``content``. - uri (str): - The URI of the content. Only Cloud Storage URIs (e.g. - ``gs://bucket-name/path/to/file``) are supported. The - maximum file size is 100 MB. - - This field is a member of `oneof`_ ``content``. - mime_type (str): - The MIME type of the content. Supported types: - - - ``application/pdf`` (PDF, only native PDFs are supported - for now) - - ``text/html`` (HTML) - - ``application/vnd.openxmlformats-officedocument.wordprocessingml.document`` - (DOCX) - - ``application/vnd.openxmlformats-officedocument.presentationml.presentation`` - (PPTX) - - ``text/plain`` (TXT) - - See - https://www.iana.org/assignments/media-types/media-types.xhtml. - """ - - raw_bytes: bytes = proto.Field( - proto.BYTES, - number=2, - oneof='content', - ) - uri: str = proto.Field( - proto.STRING, - number=3, - oneof='content', - ) - mime_type: str = proto.Field( - proto.STRING, - number=1, - ) - - struct_data: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=4, - oneof='data', - message=struct_pb2.Struct, - ) - json_data: str = proto.Field( - proto.STRING, - number=5, - oneof='data', - ) - name: str = proto.Field( - proto.STRING, - number=1, - ) - id: str = proto.Field( - proto.STRING, - number=2, - ) - schema_id: str = proto.Field( - proto.STRING, - number=3, - ) - content: Content = proto.Field( - proto.MESSAGE, - number=10, - message=Content, - ) - parent_document_id: str = proto.Field( - proto.STRING, - number=7, - ) - derived_struct_data: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=6, - message=struct_pb2.Struct, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/document_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/document_service.py deleted file mode 100644 index 8ff69b0d5e86..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/document_service.py +++ /dev/null @@ -1,265 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.discoveryengine_v1beta.types import document as gcd_document - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1beta', - manifest={ - 'GetDocumentRequest', - 'ListDocumentsRequest', - 'ListDocumentsResponse', - 'CreateDocumentRequest', - 'UpdateDocumentRequest', - 'DeleteDocumentRequest', - }, -) - - -class GetDocumentRequest(proto.Message): - r"""Request message for - [DocumentService.GetDocument][google.cloud.discoveryengine.v1beta.DocumentService.GetDocument] - method. - - Attributes: - name (str): - Required. Full resource name of - [Document][google.cloud.discoveryengine.v1beta.Document], - such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. - - If the caller does not have permission to access the - [Document][google.cloud.discoveryengine.v1beta.Document], - regardless of whether or not it exists, a - ``PERMISSION_DENIED`` error is returned. - - If the requested - [Document][google.cloud.discoveryengine.v1beta.Document] - does not exist, a ``NOT_FOUND`` error is returned. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListDocumentsRequest(proto.Message): - r"""Request message for - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1beta.DocumentService.ListDocuments] - method. - - Attributes: - parent (str): - Required. The parent branch resource name, such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. - Use ``default_branch`` as the branch ID, to list documents - under the default branch. - - If the caller does not have permission to list - [Document][google.cloud.discoveryengine.v1beta.Document]s - under this branch, regardless of whether or not this branch - exists, a ``PERMISSION_DENIED`` error is returned. - page_size (int): - Maximum number of - [Document][google.cloud.discoveryengine.v1beta.Document]s to - return. If unspecified, defaults to 100. The maximum allowed - value is 1000. Values above 1000 will be coerced to 1000. - - If this field is negative, an ``INVALID_ARGUMENT`` error is - returned. - page_token (str): - A page token - [ListDocumentsResponse.next_page_token][google.cloud.discoveryengine.v1beta.ListDocumentsResponse.next_page_token], - received from a previous - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1beta.DocumentService.ListDocuments] - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1beta.DocumentService.ListDocuments] - must match the call that provided the page token. Otherwise, - an ``INVALID_ARGUMENT`` error is returned. - """ - - 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 ListDocumentsResponse(proto.Message): - r"""Response message for - [DocumentService.ListDocuments][google.cloud.discoveryengine.v1beta.DocumentService.ListDocuments] - method. - - Attributes: - documents (MutableSequence[google.cloud.discoveryengine_v1beta.types.Document]): - The - [Document][google.cloud.discoveryengine.v1beta.Document]s. - next_page_token (str): - A token that can be sent as - [ListDocumentsRequest.page_token][google.cloud.discoveryengine.v1beta.ListDocumentsRequest.page_token] - to retrieve the next page. If this field is omitted, there - are no subsequent pages. - """ - - @property - def raw_page(self): - return self - - documents: MutableSequence[gcd_document.Document] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcd_document.Document, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class CreateDocumentRequest(proto.Message): - r"""Request message for - [DocumentService.CreateDocument][google.cloud.discoveryengine.v1beta.DocumentService.CreateDocument] - method. - - Attributes: - parent (str): - Required. The parent resource name, such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. - document (google.cloud.discoveryengine_v1beta.types.Document): - Required. The - [Document][google.cloud.discoveryengine.v1beta.Document] to - create. - document_id (str): - Required. The ID to use for the - [Document][google.cloud.discoveryengine.v1beta.Document], - which will become the final component of the - [Document.name][google.cloud.discoveryengine.v1beta.Document.name]. - - If the caller does not have permission to create the - [Document][google.cloud.discoveryengine.v1beta.Document], - regardless of whether or not it exists, a - ``PERMISSION_DENIED`` error is returned. - - This field must be unique among all - [Document][google.cloud.discoveryengine.v1beta.Document]s - with the same - [parent][google.cloud.discoveryengine.v1beta.CreateDocumentRequest.parent]. - Otherwise, an ``ALREADY_EXISTS`` error is returned. - - This field must conform to - `RFC-1034 `__ standard - with a length limit of 63 characters. Otherwise, an - ``INVALID_ARGUMENT`` error is returned. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - document: gcd_document.Document = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_document.Document, - ) - document_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class UpdateDocumentRequest(proto.Message): - r"""Request message for - [DocumentService.UpdateDocument][google.cloud.discoveryengine.v1beta.DocumentService.UpdateDocument] - method. - - Attributes: - document (google.cloud.discoveryengine_v1beta.types.Document): - Required. The document to update/create. - - If the caller does not have permission to update the - [Document][google.cloud.discoveryengine.v1beta.Document], - regardless of whether or not it exists, a - ``PERMISSION_DENIED`` error is returned. - - If the - [Document][google.cloud.discoveryengine.v1beta.Document] to - update does not exist and - [allow_missing][google.cloud.discoveryengine.v1beta.UpdateDocumentRequest.allow_missing] - is not set, a ``NOT_FOUND`` error is returned. - allow_missing (bool): - If set to true, and the - [Document][google.cloud.discoveryengine.v1beta.Document] is - not found, a new - [Document][google.cloud.discoveryengine.v1beta.Document] - will be created. - """ - - document: gcd_document.Document = proto.Field( - proto.MESSAGE, - number=1, - message=gcd_document.Document, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=2, - ) - - -class DeleteDocumentRequest(proto.Message): - r"""Request message for - [DocumentService.DeleteDocument][google.cloud.discoveryengine.v1beta.DocumentService.DeleteDocument] - method. - - Attributes: - name (str): - Required. Full resource name of - [Document][google.cloud.discoveryengine.v1beta.Document], - such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}``. - - If the caller does not have permission to delete the - [Document][google.cloud.discoveryengine.v1beta.Document], - regardless of whether or not it exists, a - ``PERMISSION_DENIED`` error is returned. - - If the - [Document][google.cloud.discoveryengine.v1beta.Document] to - delete does not exist, a ``NOT_FOUND`` error is returned. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/import_config.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/import_config.py deleted file mode 100644 index 5ba838cc43f8..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/import_config.py +++ /dev/null @@ -1,607 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.discoveryengine_v1beta.types import document -from google.cloud.discoveryengine_v1beta.types import user_event -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from google.type import date_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1beta', - manifest={ - 'GcsSource', - 'BigQuerySource', - 'ImportErrorConfig', - 'ImportUserEventsRequest', - 'ImportUserEventsResponse', - 'ImportUserEventsMetadata', - 'ImportDocumentsMetadata', - 'ImportDocumentsRequest', - 'ImportDocumentsResponse', - }, -) - - -class GcsSource(proto.Message): - r"""Cloud Storage location for input content. - - Attributes: - input_uris (MutableSequence[str]): - Required. Cloud Storage URIs to input files. URI can be up - to 2000 characters long. URIs can match the full object path - (for example, ``gs://bucket/directory/object.json``) or a - pattern matching one or more files, such as - ``gs://bucket/directory/*.json``. - - A request can contain at most 100 files (or 100,000 files if - ``data_schema`` is ``content``). Each file can be up to 2 GB - (or 100 MB if ``data_schema`` is ``content``). - data_schema (str): - The schema to use when parsing the data from the source. - - Supported values for document imports: - - - ``document`` (default): One JSON - [Document][google.cloud.discoveryengine.v1beta.Document] - per line. Each document must have a valid - [Document.id][google.cloud.discoveryengine.v1beta.Document.id]. - - ``content``: Unstructured data (e.g. PDF, HTML). Each - file matched by ``input_uris`` becomes a document, with - the ID set to the first 128 bits of SHA256(URI) encoded - as a hex string. - - ``custom``: One custom data JSON per row in arbitrary - format that conforms to the defined - [Schema][google.cloud.discoveryengine.v1beta.Schema] of - the data store. This can only be used by Gen App Builder. - - ``csv``: A CSV file with header conforming to the defined - [Schema][google.cloud.discoveryengine.v1beta.Schema] of - the data store. Each entry after the header is imported - as a Document. This can only be used by Gen App Builder. - - Supported values for user even imports: - - - ``user_event`` (default): One JSON - [UserEvent][google.cloud.discoveryengine.v1beta.UserEvent] - per line. - """ - - input_uris: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - data_schema: str = proto.Field( - proto.STRING, - number=2, - ) - - -class BigQuerySource(proto.Message): - r"""BigQuery source import data from. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - partition_date (google.type.date_pb2.Date): - BigQuery time partitioned table's \_PARTITIONDATE in - YYYY-MM-DD format. - - This field is a member of `oneof`_ ``partition``. - project_id (str): - The project ID (can be project # or ID) that - the BigQuery source is in with a length limit of - 128 characters. If not specified, inherits the - project ID from the parent request. - dataset_id (str): - Required. The BigQuery data set to copy the - data from with a length limit of 1,024 - characters. - table_id (str): - Required. The BigQuery table to copy the data - from with a length limit of 1,024 characters. - gcs_staging_dir (str): - Intermediate Cloud Storage directory used for - the import with a length limit of 2,000 - characters. Can be specified if one wants to - have the BigQuery export to a specific Cloud - Storage directory. - data_schema (str): - The schema to use when parsing the data from the source. - - Supported values for user event imports: - - - ``user_event`` (default): One - [UserEvent][google.cloud.discoveryengine.v1beta.UserEvent] - per row. - - Supported values for document imports: - - - ``document`` (default): One - [Document][google.cloud.discoveryengine.v1beta.Document] - format per row. Each document must have a valid - [Document.id][google.cloud.discoveryengine.v1beta.Document.id] - and one of - [Document.json_data][google.cloud.discoveryengine.v1beta.Document.json_data] - or - [Document.struct_data][google.cloud.discoveryengine.v1beta.Document.struct_data]. - - ``custom``: One custom data per row in arbitrary format - that conforms to the defined - [Schema][google.cloud.discoveryengine.v1beta.Schema] of - the data store. This can only be used by Gen App Builder. - """ - - partition_date: date_pb2.Date = proto.Field( - proto.MESSAGE, - number=5, - oneof='partition', - message=date_pb2.Date, - ) - project_id: str = proto.Field( - proto.STRING, - number=1, - ) - dataset_id: str = proto.Field( - proto.STRING, - number=2, - ) - table_id: str = proto.Field( - proto.STRING, - number=3, - ) - gcs_staging_dir: str = proto.Field( - proto.STRING, - number=4, - ) - data_schema: str = proto.Field( - proto.STRING, - number=6, - ) - - -class ImportErrorConfig(proto.Message): - r"""Configuration of destination for Import related errors. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_prefix (str): - Cloud Storage prefix for import errors. This must be an - empty, existing Cloud Storage directory. Import errors are - written to sharded files in this directory, one per line, as - a JSON-encoded ``google.rpc.Status`` message. - - This field is a member of `oneof`_ ``destination``. - """ - - gcs_prefix: str = proto.Field( - proto.STRING, - number=1, - oneof='destination', - ) - - -class ImportUserEventsRequest(proto.Message): - r"""Request message for the ImportUserEvents request. - - 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: - inline_source (google.cloud.discoveryengine_v1beta.types.ImportUserEventsRequest.InlineSource): - The Inline source for the input content for - UserEvents. - - This field is a member of `oneof`_ ``source``. - gcs_source (google.cloud.discoveryengine_v1beta.types.GcsSource): - Cloud Storage location for the input content. - - This field is a member of `oneof`_ ``source``. - bigquery_source (google.cloud.discoveryengine_v1beta.types.BigQuerySource): - BigQuery input source. - - This field is a member of `oneof`_ ``source``. - parent (str): - Required. Parent DataStore resource name, of the form - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}`` - error_config (google.cloud.discoveryengine_v1beta.types.ImportErrorConfig): - The desired location of errors incurred - during the Import. Cannot be set for inline user - event imports. - """ - - class InlineSource(proto.Message): - r"""The inline source for the input config for ImportUserEvents - method. - - Attributes: - user_events (MutableSequence[google.cloud.discoveryengine_v1beta.types.UserEvent]): - Required. A list of user events to import. - Recommended max of 10k items. - """ - - user_events: MutableSequence[user_event.UserEvent] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=user_event.UserEvent, - ) - - inline_source: InlineSource = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message=InlineSource, - ) - gcs_source: 'GcsSource' = proto.Field( - proto.MESSAGE, - number=3, - oneof='source', - message='GcsSource', - ) - bigquery_source: 'BigQuerySource' = proto.Field( - proto.MESSAGE, - number=4, - oneof='source', - message='BigQuerySource', - ) - parent: str = proto.Field( - proto.STRING, - number=1, - ) - error_config: 'ImportErrorConfig' = proto.Field( - proto.MESSAGE, - number=5, - message='ImportErrorConfig', - ) - - -class ImportUserEventsResponse(proto.Message): - r"""Response of the ImportUserEventsRequest. If the long running - operation was successful, then this message is returned by the - google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (MutableSequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - error_config (google.cloud.discoveryengine_v1beta.types.ImportErrorConfig): - Echoes the destination for the complete - errors if this field was set in the request. - joined_events_count (int): - Count of user events imported with complete - existing Documents. - unjoined_events_count (int): - Count of user events imported, but with - Document information not found in the existing - Branch. - """ - - error_samples: MutableSequence[status_pb2.Status] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - error_config: 'ImportErrorConfig' = proto.Field( - proto.MESSAGE, - number=2, - message='ImportErrorConfig', - ) - joined_events_count: int = proto.Field( - proto.INT64, - number=3, - ) - unjoined_events_count: int = proto.Field( - proto.INT64, - number=4, - ) - - -class ImportUserEventsMetadata(proto.Message): - r"""Metadata related to the progress of the Import operation. - This is returned by the google.longrunning.Operation.metadata - field. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - success_count (int): - Count of entries that were processed - successfully. - failure_count (int): - Count of entries that encountered errors - while processing. - """ - - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - success_count: int = proto.Field( - proto.INT64, - number=3, - ) - failure_count: int = proto.Field( - proto.INT64, - number=4, - ) - - -class ImportDocumentsMetadata(proto.Message): - r"""Metadata related to the progress of the ImportDocuments - operation. This is returned by the - google.longrunning.Operation.metadata field. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - success_count (int): - Count of entries that were processed - successfully. - failure_count (int): - Count of entries that encountered errors - while processing. - """ - - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - success_count: int = proto.Field( - proto.INT64, - number=3, - ) - failure_count: int = proto.Field( - proto.INT64, - number=4, - ) - - -class ImportDocumentsRequest(proto.Message): - r"""Request message for Import methods. - - 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: - inline_source (google.cloud.discoveryengine_v1beta.types.ImportDocumentsRequest.InlineSource): - The Inline source for the input content for - documents. - - This field is a member of `oneof`_ ``source``. - gcs_source (google.cloud.discoveryengine_v1beta.types.GcsSource): - Cloud Storage location for the input content. - - This field is a member of `oneof`_ ``source``. - bigquery_source (google.cloud.discoveryengine_v1beta.types.BigQuerySource): - BigQuery input source. - - This field is a member of `oneof`_ ``source``. - parent (str): - Required. The parent branch resource name, such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. - Requires create/update permission. - error_config (google.cloud.discoveryengine_v1beta.types.ImportErrorConfig): - The desired location of errors incurred - during the Import. - reconciliation_mode (google.cloud.discoveryengine_v1beta.types.ImportDocumentsRequest.ReconciliationMode): - The mode of reconciliation between existing documents and - the documents to be imported. Defaults to - [ReconciliationMode.INCREMENTAL][google.cloud.discoveryengine.v1beta.ImportDocumentsRequest.ReconciliationMode.INCREMENTAL]. - auto_generate_ids (bool): - Whether to automatically generate IDs for the documents if - absent. - - If set to ``true``, - [Document.id][google.cloud.discoveryengine.v1beta.Document.id]s - are automatically generated based on the hash of the - payload, where IDs may not be consistent during multiple - imports. In which case - [ReconciliationMode.FULL][google.cloud.discoveryengine.v1beta.ImportDocumentsRequest.ReconciliationMode.FULL] - is highly recommended to avoid duplicate contents. If unset - or set to ``false``, - [Document.id][google.cloud.discoveryengine.v1beta.Document.id]s - have to be specified using - [id_field][google.cloud.discoveryengine.v1beta.ImportDocumentsRequest.id_field], - otherwise, documents without IDs fail to be imported. - - Only set this field when using - [GcsSource][google.cloud.discoveryengine.v1beta.GcsSource] - or - [BigQuerySource][google.cloud.discoveryengine.v1beta.BigQuerySource], - and when - [GcsSource.data_schema][google.cloud.discoveryengine.v1beta.GcsSource.data_schema] - or - [BigQuerySource.data_schema][google.cloud.discoveryengine.v1beta.BigQuerySource.data_schema] - is ``custom`` or ``csv``. Otherwise, an INVALID_ARGUMENT - error is thrown. - id_field (str): - The field in the Cloud Storage and BigQuery sources that - indicates the unique IDs of the documents. - - For - [GcsSource][google.cloud.discoveryengine.v1beta.GcsSource] - it is the key of the JSON field. For instance, ``my_id`` for - JSON ``{"my_id": "some_uuid"}``. For - [BigQuerySource][google.cloud.discoveryengine.v1beta.BigQuerySource] - it is the column name of the BigQuery table where the unique - ids are stored. - - The values of the JSON field or the BigQuery column are used - as the - [Document.id][google.cloud.discoveryengine.v1beta.Document.id]s. - The JSON field or the BigQuery column must be of string - type, and the values must be set as valid strings conform to - `RFC-1034 `__ with 1-63 - characters. Otherwise, documents without valid IDs fail to - be imported. - - Only set this field when using - [GcsSource][google.cloud.discoveryengine.v1beta.GcsSource] - or - [BigQuerySource][google.cloud.discoveryengine.v1beta.BigQuerySource], - and when - [GcsSource.data_schema][google.cloud.discoveryengine.v1beta.GcsSource.data_schema] - or - [BigQuerySource.data_schema][google.cloud.discoveryengine.v1beta.BigQuerySource.data_schema] - is ``custom``. And only set this field when - [auto_generate_ids][google.cloud.discoveryengine.v1beta.ImportDocumentsRequest.auto_generate_ids] - is unset or set as ``false``. Otherwise, an INVALID_ARGUMENT - error is thrown. - - If it is unset, a default value ``_id`` is used when - importing from the allowed data sources. - """ - class ReconciliationMode(proto.Enum): - r"""Indicates how imported documents are reconciled with the - existing documents created or imported before. - - Values: - RECONCILIATION_MODE_UNSPECIFIED (0): - Defaults to ``INCREMENTAL``. - INCREMENTAL (1): - Inserts new documents or updates existing - documents. - FULL (2): - Calculates diff and replaces the entire - document dataset. Existing documents may be - deleted if they are not present in the source - location. - """ - RECONCILIATION_MODE_UNSPECIFIED = 0 - INCREMENTAL = 1 - FULL = 2 - - class InlineSource(proto.Message): - r"""The inline source for the input config for ImportDocuments - method. - - Attributes: - documents (MutableSequence[google.cloud.discoveryengine_v1beta.types.Document]): - Required. A list of documents to update/create. Each - document must have a valid - [Document.id][google.cloud.discoveryengine.v1beta.Document.id]. - Recommended max of 100 items. - """ - - documents: MutableSequence[document.Document] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=document.Document, - ) - - inline_source: InlineSource = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message=InlineSource, - ) - gcs_source: 'GcsSource' = proto.Field( - proto.MESSAGE, - number=3, - oneof='source', - message='GcsSource', - ) - bigquery_source: 'BigQuerySource' = proto.Field( - proto.MESSAGE, - number=4, - oneof='source', - message='BigQuerySource', - ) - parent: str = proto.Field( - proto.STRING, - number=1, - ) - error_config: 'ImportErrorConfig' = proto.Field( - proto.MESSAGE, - number=5, - message='ImportErrorConfig', - ) - reconciliation_mode: ReconciliationMode = proto.Field( - proto.ENUM, - number=6, - enum=ReconciliationMode, - ) - auto_generate_ids: bool = proto.Field( - proto.BOOL, - number=8, - ) - id_field: str = proto.Field( - proto.STRING, - number=9, - ) - - -class ImportDocumentsResponse(proto.Message): - r"""Response of the - [ImportDocumentsRequest][google.cloud.discoveryengine.v1beta.ImportDocumentsRequest]. - If the long running operation is done, then this message is returned - by the google.longrunning.Operations.response field if the operation - was successful. - - Attributes: - error_samples (MutableSequence[google.rpc.status_pb2.Status]): - A sample of errors encountered while - processing the request. - error_config (google.cloud.discoveryengine_v1beta.types.ImportErrorConfig): - Echoes the destination for the complete - errors in the request if set. - """ - - error_samples: MutableSequence[status_pb2.Status] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=status_pb2.Status, - ) - error_config: 'ImportErrorConfig' = proto.Field( - proto.MESSAGE, - number=2, - message='ImportErrorConfig', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/purge_config.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/purge_config.py deleted file mode 100644 index 14d7d3c87642..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/purge_config.py +++ /dev/null @@ -1,133 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1beta', - manifest={ - 'PurgeDocumentsRequest', - 'PurgeDocumentsResponse', - 'PurgeDocumentsMetadata', - }, -) - - -class PurgeDocumentsRequest(proto.Message): - r"""Request message for - [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1beta.DocumentService.PurgeDocuments] - method. - - Attributes: - parent (str): - Required. The parent resource name, such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}``. - filter (str): - Required. Filter matching documents to purge. Only currently - supported value is ``*`` (all items). - force (bool): - Actually performs the purge. If ``force`` is set to false, - return the expected purge count without deleting any - documents. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=2, - ) - force: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class PurgeDocumentsResponse(proto.Message): - r"""Response message for - [DocumentService.PurgeDocuments][google.cloud.discoveryengine.v1beta.DocumentService.PurgeDocuments] - method. If the long running operation is successfully done, then - this message is returned by the - google.longrunning.Operations.response field. - - Attributes: - purge_count (int): - The total count of documents purged as a - result of the operation. - purge_sample (MutableSequence[str]): - A sample of document names that will be deleted. Only - populated if ``force`` is set to false. A max of 100 names - will be returned and the names are chosen at random. - """ - - purge_count: int = proto.Field( - proto.INT64, - number=1, - ) - purge_sample: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class PurgeDocumentsMetadata(proto.Message): - r"""Metadata related to the progress of the PurgeDocuments - operation. This will be returned by the - google.longrunning.Operation.metadata field. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - success_count (int): - Count of entries that were deleted - successfully. - failure_count (int): - Count of entries that encountered errors - while processing. - """ - - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - success_count: int = proto.Field( - proto.INT64, - number=3, - ) - failure_count: int = proto.Field( - proto.INT64, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/recommendation_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/recommendation_service.py deleted file mode 100644 index d367306d2b22..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/recommendation_service.py +++ /dev/null @@ -1,264 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.discoveryengine_v1beta.types import document as gcd_document -from google.cloud.discoveryengine_v1beta.types import user_event as gcd_user_event -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1beta', - manifest={ - 'RecommendRequest', - 'RecommendResponse', - }, -) - - -class RecommendRequest(proto.Message): - r"""Request message for Recommend method. - - Attributes: - serving_config (str): - Required. Full resource name of the format: - ``projects/*/locations/global/collections/*/dataStores/*/servingConfigs/*`` - - Before you can request recommendations from your model, you - must create at least one serving config for it. - user_event (google.cloud.discoveryengine_v1beta.types.UserEvent): - Required. Context about the user, what they are looking at - and what action they took to trigger the Recommend request. - Note that this user event detail won't be ingested to - userEvent logs. Thus, a separate userEvent write request is - required for event logging. - - Don't set - [UserEvent.user_pseudo_id][google.cloud.discoveryengine.v1beta.UserEvent.user_pseudo_id] - or - [UserEvent.user_info.user_id][google.cloud.discoveryengine.v1beta.UserInfo.user_id] - to the same fixed ID for different users. If you are trying - to receive non-personalized recommendations (not - recommended; this can negatively impact model performance), - instead set - [UserEvent.user_pseudo_id][google.cloud.discoveryengine.v1beta.UserEvent.user_pseudo_id] - to a random unique ID and leave - [UserEvent.user_info.user_id][google.cloud.discoveryengine.v1beta.UserInfo.user_id] - unset. - page_size (int): - Maximum number of results to return. Set this - property to the number of recommendation results - needed. If zero, the service will choose a - reasonable default. The maximum allowed value is - 100. Values above 100 will be coerced to 100. - filter (str): - Filter for restricting recommendation results with a length - limit of 5,000 characters. Currently, only filter - expressions on the ``filter_tags`` attribute is supported. - - Examples: - - - ``(filter_tags: ANY("Red", "Blue") OR filter_tags: ANY("Hot", "Cold"))`` - - ``(filter_tags: ANY("Red", "Blue")) AND NOT (filter_tags: ANY("Green"))`` - - If your filter blocks all results, the API will return - generic (unfiltered) popular Documents. If you only want - results strictly matching the filters, set - ``strictFiltering`` to True in - [RecommendRequest.params][google.cloud.discoveryengine.v1beta.RecommendRequest.params] - to receive empty results instead. - - Note that the API will never return - [Document][google.cloud.discoveryengine.v1beta.Document]s - with ``storageStatus`` of ``EXPIRED`` or ``DELETED`` - regardless of filter choices. - validate_only (bool): - Use validate only mode for this - recommendation query. If set to true, a fake - model will be used that returns arbitrary - Document IDs. Note that the validate only mode - should only be used for testing the API, or if - the model is not ready. - params (MutableMapping[str, google.protobuf.struct_pb2.Value]): - Additional domain specific parameters for the - recommendations. - - Allowed values: - - - ``returnDocument``: Boolean. If set to true, the - associated Document object will be returned in - [RecommendResponse.RecommendationResult.document][google.cloud.discoveryengine.v1beta.RecommendResponse.RecommendationResult.document]. - - ``returnScore``: Boolean. If set to true, the - recommendation 'score' corresponding to each returned - Document will be set in - [RecommendResponse.RecommendationResult.metadata][google.cloud.discoveryengine.v1beta.RecommendResponse.RecommendationResult.metadata]. - The given 'score' indicates the probability of a Document - conversion given the user's context and history. - - ``strictFiltering``: Boolean. True by default. If set to - false, the service will return generic (unfiltered) - popular Documents instead of empty if your filter blocks - all recommendation results. - - ``diversityLevel``: String. Default empty. If set to be - non-empty, then it needs to be one of: - - - ``no-diversity`` - - ``low-diversity`` - - ``medium-diversity`` - - ``high-diversity`` - - ``auto-diversity`` This gives request-level control - and adjusts recommendation results based on Document - category. - user_labels (MutableMapping[str, str]): - The user labels applied to a resource must meet the - following requirements: - - - Each resource can have multiple labels, up to a maximum - of 64. - - Each label must be a key-value pair. - - Keys have a minimum length of 1 character and a maximum - length of 63 characters and cannot be empty. Values can - be empty and have a maximum length of 63 characters. - - Keys and values can contain only lowercase letters, - numeric characters, underscores, and dashes. All - characters must use UTF-8 encoding, and international - characters are allowed. - - The key portion of a label must be unique. However, you - can use the same key with multiple resources. - - Keys must start with a lowercase letter or international - character. - - See `Requirements for - labels `__ - for more details. - """ - - serving_config: str = proto.Field( - proto.STRING, - number=1, - ) - user_event: gcd_user_event.UserEvent = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_user_event.UserEvent, - ) - page_size: int = proto.Field( - proto.INT32, - number=3, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=5, - ) - params: MutableMapping[str, struct_pb2.Value] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=6, - message=struct_pb2.Value, - ) - user_labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=8, - ) - - -class RecommendResponse(proto.Message): - r"""Response message for Recommend method. - - Attributes: - results (MutableSequence[google.cloud.discoveryengine_v1beta.types.RecommendResponse.RecommendationResult]): - A list of recommended Documents. The order - represents the ranking (from the most relevant - Document to the least). - attribution_token (str): - A unique attribution token. This should be included in the - [UserEvent][google.cloud.discoveryengine.v1beta.UserEvent] - logs resulting from this recommendation, which enables - accurate attribution of recommendation model performance. - missing_ids (MutableSequence[str]): - IDs of documents in the request that were - missing from the default Branch associated with - the requested ServingConfig. - validate_only (bool): - True if - [RecommendRequest.validate_only][google.cloud.discoveryengine.v1beta.RecommendRequest.validate_only] - was set. - """ - - class RecommendationResult(proto.Message): - r"""RecommendationResult represents a generic recommendation - result with associated metadata. - - Attributes: - id (str): - Resource ID of the recommended Document. - document (google.cloud.discoveryengine_v1beta.types.Document): - Set if ``returnDocument`` is set to true in - [RecommendRequest.params][google.cloud.discoveryengine.v1beta.RecommendRequest.params]. - metadata (MutableMapping[str, google.protobuf.struct_pb2.Value]): - Additional Document metadata / annotations. - - Possible values: - - - ``score``: Recommendation score in double value. Is set - if ``returnScore`` is set to true in - [RecommendRequest.params][google.cloud.discoveryengine.v1beta.RecommendRequest.params]. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - document: gcd_document.Document = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_document.Document, - ) - metadata: MutableMapping[str, struct_pb2.Value] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=3, - message=struct_pb2.Value, - ) - - results: MutableSequence[RecommendationResult] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=RecommendationResult, - ) - attribution_token: str = proto.Field( - proto.STRING, - number=2, - ) - missing_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/schema.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/schema.py deleted file mode 100644 index 0a7bd7de897b..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/schema.py +++ /dev/null @@ -1,78 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1beta', - manifest={ - 'Schema', - }, -) - - -class Schema(proto.Message): - r"""Defines the structure and layout of a type of document data. - - 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: - struct_schema (google.protobuf.struct_pb2.Struct): - The structured representation of the schema. - - This field is a member of `oneof`_ ``schema``. - json_schema (str): - The JSON representation of the schema. - - This field is a member of `oneof`_ ``schema``. - name (str): - Immutable. The full resource name of the schema, in the - format of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. - - This field must be a UTF-8 encoded string with a length - limit of 1024 characters. - """ - - struct_schema: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=2, - oneof='schema', - message=struct_pb2.Struct, - ) - json_schema: str = proto.Field( - proto.STRING, - number=3, - oneof='schema', - ) - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/schema_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/schema_service.py deleted file mode 100644 index cf3d210dfce7..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/schema_service.py +++ /dev/null @@ -1,291 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.discoveryengine_v1beta.types import schema as gcd_schema -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1beta', - manifest={ - 'GetSchemaRequest', - 'ListSchemasRequest', - 'ListSchemasResponse', - 'CreateSchemaRequest', - 'UpdateSchemaRequest', - 'DeleteSchemaRequest', - 'CreateSchemaMetadata', - 'UpdateSchemaMetadata', - 'DeleteSchemaMetadata', - }, -) - - -class GetSchemaRequest(proto.Message): - r"""Request message for - [SchemaService.GetSchema][google.cloud.discoveryengine.v1beta.SchemaService.GetSchema] - method. - - Attributes: - name (str): - Required. The full resource name of the schema, in the - format of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListSchemasRequest(proto.Message): - r"""Request message for - [SchemaService.ListSchemas][google.cloud.discoveryengine.v1beta.SchemaService.ListSchemas] - method. - - Attributes: - parent (str): - Required. The parent data store resource name, in the format - of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. - page_size (int): - The maximum number of - [Schema][google.cloud.discoveryengine.v1beta.Schema]s to - return. The service may return fewer than this value. - - If unspecified, at most 100 - [Schema][google.cloud.discoveryengine.v1beta.Schema]s will - be returned. - - The maximum value is 1000; values above 1000 will be coerced - to 1000. - page_token (str): - A page token, received from a previous - [SchemaService.ListSchemas][google.cloud.discoveryengine.v1beta.SchemaService.ListSchemas] - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - [SchemaService.ListSchemas][google.cloud.discoveryengine.v1beta.SchemaService.ListSchemas] - 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 ListSchemasResponse(proto.Message): - r"""Response message for - [SchemaService.ListSchemas][google.cloud.discoveryengine.v1beta.SchemaService.ListSchemas] - method. - - Attributes: - schemas (MutableSequence[google.cloud.discoveryengine_v1beta.types.Schema]): - The [Schema][google.cloud.discoveryengine.v1beta.Schema]s. - next_page_token (str): - A token that can be sent as - [ListSchemasRequest.page_token][google.cloud.discoveryengine.v1beta.ListSchemasRequest.page_token] - to retrieve the next page. If this field is omitted, there - are no subsequent pages. - """ - - @property - def raw_page(self): - return self - - schemas: MutableSequence[gcd_schema.Schema] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gcd_schema.Schema, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class CreateSchemaRequest(proto.Message): - r"""Request message for - [SchemaService.CreateSchema][google.cloud.discoveryengine.v1beta.SchemaService.CreateSchema] - method. - - Attributes: - parent (str): - Required. The parent data store resource name, in the format - of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. - schema (google.cloud.discoveryengine_v1beta.types.Schema): - Required. The - [Schema][google.cloud.discoveryengine.v1beta.Schema] to - create. - schema_id (str): - Required. The ID to use for the - [Schema][google.cloud.discoveryengine.v1beta.Schema], which - will become the final component of the - [Schema.name][google.cloud.discoveryengine.v1beta.Schema.name]. - - This field should conform to - `RFC-1034 `__ standard - with a length limit of 63 characters. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - schema: gcd_schema.Schema = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_schema.Schema, - ) - schema_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class UpdateSchemaRequest(proto.Message): - r"""Request message for - [SchemaService.UpdateSchema][google.cloud.discoveryengine.v1beta.SchemaService.UpdateSchema] - method. - - Attributes: - schema (google.cloud.discoveryengine_v1beta.types.Schema): - Required. The - [Schema][google.cloud.discoveryengine.v1beta.Schema] to - update. - allow_missing (bool): - If set to true, and the - [Schema][google.cloud.discoveryengine.v1beta.Schema] is not - found, a new - [Schema][google.cloud.discoveryengine.v1beta.Schema] will be - created. In this situation, ``update_mask`` is ignored. - """ - - schema: gcd_schema.Schema = proto.Field( - proto.MESSAGE, - number=1, - message=gcd_schema.Schema, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class DeleteSchemaRequest(proto.Message): - r"""Request message for - [SchemaService.DeleteSchema][google.cloud.discoveryengine.v1beta.SchemaService.DeleteSchema] - method. - - Attributes: - name (str): - Required. The full resource name of the schema, in the - format of - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/schemas/{schema}``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateSchemaMetadata(proto.Message): - r"""Metadata for Create Schema LRO. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - """ - - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - -class UpdateSchemaMetadata(proto.Message): - r"""Metadata for UpdateSchema LRO. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - """ - - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - -class DeleteSchemaMetadata(proto.Message): - r"""Metadata for DeleteSchema LRO. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Operation create time. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Operation last update time. If the operation - is done, this is also the finish time. - """ - - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/search_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/search_service.py deleted file mode 100644 index daaae5214b66..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/search_service.py +++ /dev/null @@ -1,1312 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.discoveryengine_v1beta.types import common -from google.cloud.discoveryengine_v1beta.types import document as gcd_document -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1beta', - manifest={ - 'SearchRequest', - 'SearchResponse', - }, -) - - -class SearchRequest(proto.Message): - r"""Request message for - [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] - method. - - Attributes: - serving_config (str): - Required. The resource name of the Search serving config, - such as - ``projects/*/locations/global/collections/default_collection/dataStores/default_data_store/servingConfigs/default_serving_config``. - This field is used to identify the serving configuration - name, set of models used to make the search. - branch (str): - The branch resource name, such as - ``projects/*/locations/global/collections/default_collection/dataStores/default_data_store/branches/0``. - - Use ``default_branch`` as the branch ID or leave this field - empty, to search documents under the default branch. - query (str): - Raw search query. - image_query (google.cloud.discoveryengine_v1beta.types.SearchRequest.ImageQuery): - Raw image query. - page_size (int): - Maximum number of - [Document][google.cloud.discoveryengine.v1beta.Document]s to - return. If unspecified, defaults to a reasonable value. The - maximum allowed value is 100. Values above 100 are coerced - to 100. - - If this field is negative, an ``INVALID_ARGUMENT`` is - returned. - page_token (str): - A page token received from a previous - [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] - must match the call that provided the page token. Otherwise, - an ``INVALID_ARGUMENT`` error is returned. - offset (int): - A 0-indexed integer that specifies the current offset (that - is, starting result location, amongst the - [Document][google.cloud.discoveryengine.v1beta.Document]s - deemed by the API as relevant) in search results. This field - is only considered if - [page_token][google.cloud.discoveryengine.v1beta.SearchRequest.page_token] - is unset. - - If this field is negative, an ``INVALID_ARGUMENT`` is - returned. - filter (str): - The filter syntax consists of an expression language for - constructing a predicate from one or more fields of the - documents being filtered. Filter expression is - case-sensitive. - - If this field is unrecognizable, an ``INVALID_ARGUMENT`` is - returned. - order_by (str): - The order in which documents are returned. Documents can be - ordered by a field in an - [Document][google.cloud.discoveryengine.v1beta.Document] - object. Leave it unset if ordered by relevance. ``order_by`` - expression is case-sensitive. - - If this field is unrecognizable, an ``INVALID_ARGUMENT`` is - returned. - user_info (google.cloud.discoveryengine_v1beta.types.UserInfo): - Information about the end user. Highly recommended for - analytics. - [UserInfo.user_agent][google.cloud.discoveryengine.v1beta.UserInfo.user_agent] - is used to deduce ``device_type`` for analytics. - facet_specs (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchRequest.FacetSpec]): - Facet specifications for faceted search. If empty, no facets - are returned. - - A maximum of 100 values are allowed. Otherwise, an - ``INVALID_ARGUMENT`` error is returned. - boost_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.BoostSpec): - Boost specification to boost certain - documents. - params (MutableMapping[str, google.protobuf.struct_pb2.Value]): - Additional search parameters. - - For public website search only, supported values are: - - - ``user_country_code``: string. Default empty. If set to - non-empty, results are restricted or boosted based on the - location provided. - - ``search_type``: double. Default empty. Enables - non-webpage searching depending on the value. The only - valid non-default value is 1, which enables image - searching. - query_expansion_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.QueryExpansionSpec): - The query expansion specification that - specifies the conditions under which query - expansion occurs. - spell_correction_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.SpellCorrectionSpec): - The spell correction specification that - specifies the mode under which spell correction - takes effect. - user_pseudo_id (str): - A unique identifier for tracking visitors. For example, this - could be implemented with an HTTP cookie, which should be - able to uniquely identify a visitor on a single device. This - unique identifier should not change if the visitor logs in - or out of the website. - - This field should NOT have a fixed value such as - ``unknown_visitor``. - - This should be the same identifier as - [UserEvent.user_pseudo_id][google.cloud.discoveryengine.v1beta.UserEvent.user_pseudo_id] - and - [CompleteQueryRequest.user_pseudo_id][google.cloud.discoveryengine.v1beta.CompleteQueryRequest.user_pseudo_id] - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an ``INVALID_ARGUMENT`` error - is returned. - content_search_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.ContentSearchSpec): - A specification for configuring the behavior - of content search. - embedding_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.EmbeddingSpec): - Uses the provided embedding to do additional semantic - document retrieval. The retrieval is based on the dot - product of - [SearchRequest.embedding_spec.embedding_vectors.vector][] - and the document embedding that is provided in - [SearchRequest.embedding_spec.embedding_vectors.field_path][]. - - If - [SearchRequest.embedding_spec.embedding_vectors.field_path][] - is not provided, it will use - [ServingConfig.embedding_config.field_paths][]. - ranking_expression (str): - The ranking expression controls the customized ranking on - retrieval documents. This overrides - [ServingConfig.ranking_expression][]. The ranking expression - is a single function or multiple functions that are joint by - "+". - - - ranking_expression = function, { " + ", function }; - Supported functions: - - double \* relevance_score - - double \* dotProduct(embedding_field_path) Function - variables: ``relevance_score``: pre-defined keywords, - used for measure relevance between query and document. - ``embedding_field_path``: the document embedding field - used with query embedding vector. ``dotProduct``: - embedding function between embedding_field_path and query - embedding vector. - - Example ranking expression: If document has an embedding - field doc_embedding, the ranking expression could be - ``0.5 * relevance_score + 0.3 * dotProduct(doc_embedding)``. - safe_search (bool): - Whether to turn on safe search. This is only - supported for website search. - user_labels (MutableMapping[str, str]): - The user labels applied to a resource must meet the - following requirements: - - - Each resource can have multiple labels, up to a maximum - of 64. - - Each label must be a key-value pair. - - Keys have a minimum length of 1 character and a maximum - length of 63 characters and cannot be empty. Values can - be empty and have a maximum length of 63 characters. - - Keys and values can contain only lowercase letters, - numeric characters, underscores, and dashes. All - characters must use UTF-8 encoding, and international - characters are allowed. - - The key portion of a label must be unique. However, you - can use the same key with multiple resources. - - Keys must start with a lowercase letter or international - character. - - See `Google Cloud - Document `__ - for more details. - """ - - class ImageQuery(proto.Message): - r"""Specifies the image query input. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - image_bytes (str): - Base64 encoded image bytes. Supported image - formats: JPEG, PNG, and BMP. - - This field is a member of `oneof`_ ``image``. - """ - - image_bytes: str = proto.Field( - proto.STRING, - number=1, - oneof='image', - ) - - class FacetSpec(proto.Message): - r"""A facet specification to perform faceted search. - - Attributes: - facet_key (google.cloud.discoveryengine_v1beta.types.SearchRequest.FacetSpec.FacetKey): - Required. The facet key specification. - limit (int): - Maximum of facet values that should be returned for this - facet. If unspecified, defaults to 20. The maximum allowed - value is 300. Values above 300 are coerced to 300. - - If this field is negative, an ``INVALID_ARGUMENT`` is - returned. - excluded_filter_keys (MutableSequence[str]): - List of keys to exclude when faceting. - - By default, - [FacetKey.key][google.cloud.discoveryengine.v1beta.SearchRequest.FacetSpec.FacetKey.key] - is not excluded from the filter unless it is listed in this - field. - - Listing a facet key in this field allows its values to - appear as facet results, even when they are filtered out of - search results. Using this field does not affect what search - results are returned. - - For example, suppose there are 100 documents with the color - facet "Red" and 200 documents with the color facet "Blue". A - query containing the filter "color:ANY("Red")" and having - "color" as - [FacetKey.key][google.cloud.discoveryengine.v1beta.SearchRequest.FacetSpec.FacetKey.key] - would by default return only "Red" documents in the search - results, and also return "Red" with count 100 as the only - color facet. Although there are also blue documents - available, "Blue" would not be shown as an available facet - value. - - If "color" is listed in "excludedFilterKeys", then the query - returns the facet values "Red" with count 100 and "Blue" - with count 200, because the "color" key is now excluded from - the filter. Because this field doesn't affect search - results, the search results are still correctly filtered to - return only "Red" documents. - - A maximum of 100 values are allowed. Otherwise, an - ``INVALID_ARGUMENT`` error is returned. - enable_dynamic_position (bool): - Enables dynamic position for this facet. If set to true, the - position of this facet among all facets in the response is - determined automatically. If dynamic facets are enabled, it - is ordered together. If set to false, the position of this - facet in the response is the same as in the request, and it - is ranked before the facets with dynamic position enable and - all dynamic facets. - - For example, you may always want to have rating facet - returned in the response, but it's not necessarily to always - display the rating facet at the top. In that case, you can - set enable_dynamic_position to true so that the position of - rating facet in response is determined automatically. - - Another example, assuming you have the following facets in - the request: - - - "rating", enable_dynamic_position = true - - - "price", enable_dynamic_position = false - - - "brands", enable_dynamic_position = false - - And also you have a dynamic facets enabled, which generates - a facet ``gender``. Then the final order of the facets in - the response can be ("price", "brands", "rating", "gender") - or ("price", "brands", "gender", "rating") depends on how - API orders "gender" and "rating" facets. However, notice - that "price" and "brands" are always ranked at first and - second position because their enable_dynamic_position is - false. - """ - - class FacetKey(proto.Message): - r"""Specifies how a facet is computed. - - Attributes: - key (str): - Required. Supported textual and numerical facet keys in - [Document][google.cloud.discoveryengine.v1beta.Document] - object, over which the facet values are computed. Facet key - is case-sensitive. - intervals (MutableSequence[google.cloud.discoveryengine_v1beta.types.Interval]): - Set only if values should be bucketed into - intervals. Must be set for facets with numerical - values. Must not be set for facet with text - values. Maximum number of intervals is 30. - restricted_values (MutableSequence[str]): - Only get facet for the given restricted values. Only - supported on textual fields. For example, suppose "category" - has three values "Action > 2022", "Action > 2021" and - "Sci-Fi > 2022". If set "restricted_values" to "Action > - 2022", the "category" facet only contains "Action > 2022". - Only supported on textual fields. Maximum is 10. - prefixes (MutableSequence[str]): - Only get facet values that start with the - given string prefix. For example, suppose - "category" has three values "Action > 2022", - "Action > 2021" and "Sci-Fi > 2022". If set - "prefixes" to "Action", the "category" facet - only contains "Action > 2022" and "Action > - 2021". Only supported on textual fields. Maximum - is 10. - contains (MutableSequence[str]): - Only get facet values that contains the given - strings. For example, suppose "category" has - three values "Action > 2022", "Action > 2021" - and "Sci-Fi > 2022". If set "contains" to - "2022", the "category" facet only contains - "Action > 2022" and "Sci-Fi > 2022". Only - supported on textual fields. Maximum is 10. - case_insensitive (bool): - True to make facet keys case insensitive when - getting faceting values with prefixes or - contains; false otherwise. - order_by (str): - The order in which documents are returned. - - Allowed values are: - - - "count desc", which means order by - [SearchResponse.Facet.values.count][google.cloud.discoveryengine.v1beta.SearchResponse.Facet.FacetValue.count] - descending. - - - "value desc", which means order by - [SearchResponse.Facet.values.value][google.cloud.discoveryengine.v1beta.SearchResponse.Facet.FacetValue.value] - descending. Only applies to textual facets. - - If not set, textual values are sorted in `natural - order `__; - numerical intervals are sorted in the order given by - [FacetSpec.FacetKey.intervals][google.cloud.discoveryengine.v1beta.SearchRequest.FacetSpec.FacetKey.intervals]. - """ - - key: str = proto.Field( - proto.STRING, - number=1, - ) - intervals: MutableSequence[common.Interval] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=common.Interval, - ) - restricted_values: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - prefixes: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - contains: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - case_insensitive: bool = proto.Field( - proto.BOOL, - number=6, - ) - order_by: str = proto.Field( - proto.STRING, - number=7, - ) - - facet_key: 'SearchRequest.FacetSpec.FacetKey' = proto.Field( - proto.MESSAGE, - number=1, - message='SearchRequest.FacetSpec.FacetKey', - ) - limit: int = proto.Field( - proto.INT32, - number=2, - ) - excluded_filter_keys: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - enable_dynamic_position: bool = proto.Field( - proto.BOOL, - number=4, - ) - - class BoostSpec(proto.Message): - r"""Boost specification to boost certain documents. - - Attributes: - condition_boost_specs (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchRequest.BoostSpec.ConditionBoostSpec]): - Condition boost specifications. If a document - matches multiple conditions in the - specifictions, boost scores from these - specifications are all applied and combined in a - non-linear way. Maximum number of specifications - is 20. - """ - - class ConditionBoostSpec(proto.Message): - r"""Boost applies to documents which match a condition. - - Attributes: - condition (str): - An expression which specifies a boost condition. The syntax - and supported fields are the same as a filter expression. - See - [SearchRequest.filter][google.cloud.discoveryengine.v1beta.SearchRequest.filter] - for detail syntax and limitations. - - Examples: - - - To boost documents with document ID "doc_1" or "doc_2", - and color "Red" or "Blue": - - - (id: ANY("doc_1", "doc_2")) AND (color: - ANY("Red","Blue")) - boost (float): - Strength of the condition boost, which should be in [-1, 1]. - Negative boost means demotion. Default is 0.0. - - Setting to 1.0 gives the document a big promotion. However, - it does not necessarily mean that the boosted document will - be the top result at all times, nor that other documents - will be excluded. Results could still be shown even when - none of them matches the condition. And results that are - significantly more relevant to the search query can still - trump your heavily favored but irrelevant documents. - - Setting to -1.0 gives the document a big demotion. However, - results that are deeply relevant might still be shown. The - document will have an upstream battle to get a fairly high - ranking, but it is not blocked out completely. - - Setting to 0.0 means no boost applied. The boosting - condition is ignored. - """ - - condition: str = proto.Field( - proto.STRING, - number=1, - ) - boost: float = proto.Field( - proto.FLOAT, - number=2, - ) - - condition_boost_specs: MutableSequence['SearchRequest.BoostSpec.ConditionBoostSpec'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SearchRequest.BoostSpec.ConditionBoostSpec', - ) - - class QueryExpansionSpec(proto.Message): - r"""Specification to determine under which conditions query - expansion should occur. - - Attributes: - condition (google.cloud.discoveryengine_v1beta.types.SearchRequest.QueryExpansionSpec.Condition): - The condition under which query expansion should occur. - Default to - [Condition.DISABLED][google.cloud.discoveryengine.v1beta.SearchRequest.QueryExpansionSpec.Condition.DISABLED]. - pin_unexpanded_results (bool): - Whether to pin unexpanded results. If this - field is set to true, unexpanded products are - always at the top of the search results, - followed by the expanded results. - """ - class Condition(proto.Enum): - r"""Enum describing under which condition query expansion should - occur. - - Values: - CONDITION_UNSPECIFIED (0): - Unspecified query expansion condition. In this case, server - behavior defaults to - [Condition.DISABLED][google.cloud.discoveryengine.v1beta.SearchRequest.QueryExpansionSpec.Condition.DISABLED]. - DISABLED (1): - Disabled query expansion. Only the exact search query is - used, even if - [SearchResponse.total_size][google.cloud.discoveryengine.v1beta.SearchResponse.total_size] - is zero. - AUTO (2): - Automatic query expansion built by the Search - API. - """ - CONDITION_UNSPECIFIED = 0 - DISABLED = 1 - AUTO = 2 - - condition: 'SearchRequest.QueryExpansionSpec.Condition' = proto.Field( - proto.ENUM, - number=1, - enum='SearchRequest.QueryExpansionSpec.Condition', - ) - pin_unexpanded_results: bool = proto.Field( - proto.BOOL, - number=2, - ) - - class SpellCorrectionSpec(proto.Message): - r"""The specification for query spell correction. - - Attributes: - mode (google.cloud.discoveryengine_v1beta.types.SearchRequest.SpellCorrectionSpec.Mode): - The mode under which spell correction should take effect to - replace the original search query. Default to - [Mode.AUTO][google.cloud.discoveryengine.v1beta.SearchRequest.SpellCorrectionSpec.Mode.AUTO]. - """ - class Mode(proto.Enum): - r"""Enum describing under which mode spell correction should - occur. - - Values: - MODE_UNSPECIFIED (0): - Unspecified spell correction mode. In this case, server - behavior defaults to - [Mode.AUTO][google.cloud.discoveryengine.v1beta.SearchRequest.SpellCorrectionSpec.Mode.AUTO]. - SUGGESTION_ONLY (1): - Search API will try to find a spell suggestion if there is - any and put in the - [SearchResponse.corrected_query][google.cloud.discoveryengine.v1beta.SearchResponse.corrected_query]. - The spell suggestion will not be used as the search query. - AUTO (2): - Automatic spell correction built by the - Search API. Search will be based on the - corrected query if found. - """ - MODE_UNSPECIFIED = 0 - SUGGESTION_ONLY = 1 - AUTO = 2 - - mode: 'SearchRequest.SpellCorrectionSpec.Mode' = proto.Field( - proto.ENUM, - number=1, - enum='SearchRequest.SpellCorrectionSpec.Mode', - ) - - class ContentSearchSpec(proto.Message): - r"""A specification for configuring the behavior of content - search. - - Attributes: - snippet_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.ContentSearchSpec.SnippetSpec): - If ``snippetSpec`` is not specified, snippets are not - included in the search response. - summary_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.ContentSearchSpec.SummarySpec): - If ``summarySpec`` is not specified, summaries are not - included in the search response. - extractive_content_spec (google.cloud.discoveryengine_v1beta.types.SearchRequest.ContentSearchSpec.ExtractiveContentSpec): - If there is no extractive_content_spec provided, there will - be no extractive answer in the search response. - """ - - class SnippetSpec(proto.Message): - r"""A specification for configuring snippets in a search - response. - - Attributes: - max_snippet_count (int): - [DEPRECATED] This field is deprecated. To control snippet - return, use ``return_snippet`` field. For backwards - compatibility, we will return snippet if max_snippet_count > - 0. - reference_only (bool): - [DEPRECATED] This field is deprecated and will have no - affect on the snippet. - return_snippet (bool): - If ``true``, then return snippet. If no snippet can be - generated, we return "No snippet is available for this - page." A ``snippet_status`` with ``SUCCESS`` or - ``NO_SNIPPET_AVAILABLE`` will also be returned. - """ - - max_snippet_count: int = proto.Field( - proto.INT32, - number=1, - ) - reference_only: bool = proto.Field( - proto.BOOL, - number=2, - ) - return_snippet: bool = proto.Field( - proto.BOOL, - number=3, - ) - - class SummarySpec(proto.Message): - r"""A specification for configuring a summary returned in a - search response. - - Attributes: - summary_result_count (int): - The number of top results to generate the summary from. If - the number of results returned is less than - ``summaryResultCount``, the summary is generated from all of - the results. - - At most five results can be used to generate a summary. - include_citations (bool): - Specifies whether to include citations in the summary. The - default value is ``false``. - - When this field is set to ``true``, summaries include - in-line citation numbers. - - Example summary including citations: - - BigQuery is Google Cloud's fully managed and completely - serverless enterprise data warehouse [1]. BigQuery supports - all data types, works across clouds, and has built-in - machine learning and business intelligence, all within a - unified platform [2, 3]. - - The citation numbers refer to the returned search results - and are 1-indexed. For example, [1] means that the sentence - is attributed to the first search result. [2, 3] means that - the sentence is attributed to both the second and third - search results. - ignore_adversarial_query (bool): - Specifies whether to filter out adversarial queries. The - default value is ``false``. - - Google employs search-query classification to detect - adversarial queries. No summary is returned if the search - query is classified as an adversarial query. For example, a - user might ask a question regarding negative comments about - the company or submit a query designed to generate unsafe, - policy-violating output. If this field is set to ``true``, - we skip generating summaries for adversarial queries and - return fallback messages instead. - ignore_non_summary_seeking_query (bool): - Specifies whether to filter out queries that are not - summary-seeking. The default value is ``false``. - - Google employs search-query classification to detect - summary-seeking queries. No summary is returned if the - search query is classified as a non-summary seeking query. - For example, ``why is the sky blue`` and - ``Who is the best soccer player in the world?`` are - summary-seeking queries, but ``SFO airport`` and - ``world cup 2026`` are not. They are most likely - navigational queries. If this field is set to ``true``, we - skip generating summaries for non-summary seeking queries - and return fallback messages instead. - language_code (str): - Language code for Summary. Use language tags defined by - [BCP47][https://www.rfc-editor.org/rfc/bcp/bcp47.txt]. - """ - - summary_result_count: int = proto.Field( - proto.INT32, - number=1, - ) - include_citations: bool = proto.Field( - proto.BOOL, - number=2, - ) - ignore_adversarial_query: bool = proto.Field( - proto.BOOL, - number=3, - ) - ignore_non_summary_seeking_query: bool = proto.Field( - proto.BOOL, - number=4, - ) - language_code: str = proto.Field( - proto.STRING, - number=6, - ) - - class ExtractiveContentSpec(proto.Message): - r"""A specification for configuring the extractive content in a - search response. - - Attributes: - max_extractive_answer_count (int): - The maximum number of extractive answers returned in each - search result. - - An extractive answer is a verbatim answer extracted from the - original document, which provides a precise and contextually - relevant answer to the search query. - - If the number of matching answers is less than the - ``max_extractive_answer_count``, return all of the answers. - Otherwise, return the ``max_extractive_answer_count``. - - At most one answer is returned for each - [SearchResult][google.cloud.discoveryengine.v1beta.SearchResponse.SearchResult]. - max_extractive_segment_count (int): - The max number of extractive segments returned in each - search result. Only applied if the - [DataStore][google.cloud.discoveryengine.v1beta.DataStore] - is set to - [DataStore.ContentConfig.CONTENT_REQUIRED][google.cloud.discoveryengine.v1beta.DataStore.ContentConfig.CONTENT_REQUIRED] - or - [DataStore.solution_types][google.cloud.discoveryengine.v1beta.DataStore.solution_types] - is - [SOLUTION_TYPE_CHAT][google.cloud.discoveryengine.v1beta.SolutionType.SOLUTION_TYPE_CHAT]. - - An extractive segment is a text segment extracted from the - original document that is relevant to the search query, and, - in general, more verbose than an extractive answer. The - segment could then be used as input for LLMs to generate - summaries and answers. - - If the number of matching segments is less than - ``max_extractive_segment_count``, return all of the - segments. Otherwise, return the - ``max_extractive_segment_count``. - return_extractive_segment_score (bool): - Specifies whether to return the confidence score from the - extractive segments in each search result. The default value - is ``false``. - num_previous_segments (int): - Specifies whether to also include the adjacent from each - selected segments. Return at most ``num_previous_segments`` - segments before each selected segments. - num_next_segments (int): - Return at most ``num_next_segments`` segments after each - selected segments. - """ - - max_extractive_answer_count: int = proto.Field( - proto.INT32, - number=1, - ) - max_extractive_segment_count: int = proto.Field( - proto.INT32, - number=2, - ) - return_extractive_segment_score: bool = proto.Field( - proto.BOOL, - number=3, - ) - num_previous_segments: int = proto.Field( - proto.INT32, - number=4, - ) - num_next_segments: int = proto.Field( - proto.INT32, - number=5, - ) - - snippet_spec: 'SearchRequest.ContentSearchSpec.SnippetSpec' = proto.Field( - proto.MESSAGE, - number=1, - message='SearchRequest.ContentSearchSpec.SnippetSpec', - ) - summary_spec: 'SearchRequest.ContentSearchSpec.SummarySpec' = proto.Field( - proto.MESSAGE, - number=2, - message='SearchRequest.ContentSearchSpec.SummarySpec', - ) - extractive_content_spec: 'SearchRequest.ContentSearchSpec.ExtractiveContentSpec' = proto.Field( - proto.MESSAGE, - number=3, - message='SearchRequest.ContentSearchSpec.ExtractiveContentSpec', - ) - - class EmbeddingSpec(proto.Message): - r"""The specification that uses customized query embedding vector - to do semantic document retrieval. - - Attributes: - embedding_vectors (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchRequest.EmbeddingSpec.EmbeddingVector]): - The embedding vector used for retrieval. - Limit to 1. - """ - - class EmbeddingVector(proto.Message): - r"""Embedding vector. - - Attributes: - field_path (str): - Embedding field path in schema. - vector (MutableSequence[float]): - Query embedding vector. - """ - - field_path: str = proto.Field( - proto.STRING, - number=1, - ) - vector: MutableSequence[float] = proto.RepeatedField( - proto.FLOAT, - number=2, - ) - - embedding_vectors: MutableSequence['SearchRequest.EmbeddingSpec.EmbeddingVector'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SearchRequest.EmbeddingSpec.EmbeddingVector', - ) - - serving_config: str = proto.Field( - proto.STRING, - number=1, - ) - branch: str = proto.Field( - proto.STRING, - number=2, - ) - query: str = proto.Field( - proto.STRING, - number=3, - ) - image_query: ImageQuery = proto.Field( - proto.MESSAGE, - number=19, - message=ImageQuery, - ) - page_size: int = proto.Field( - proto.INT32, - number=4, - ) - page_token: str = proto.Field( - proto.STRING, - number=5, - ) - offset: int = proto.Field( - proto.INT32, - number=6, - ) - filter: str = proto.Field( - proto.STRING, - number=7, - ) - order_by: str = proto.Field( - proto.STRING, - number=8, - ) - user_info: common.UserInfo = proto.Field( - proto.MESSAGE, - number=21, - message=common.UserInfo, - ) - facet_specs: MutableSequence[FacetSpec] = proto.RepeatedField( - proto.MESSAGE, - number=9, - message=FacetSpec, - ) - boost_spec: BoostSpec = proto.Field( - proto.MESSAGE, - number=10, - message=BoostSpec, - ) - params: MutableMapping[str, struct_pb2.Value] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=11, - message=struct_pb2.Value, - ) - query_expansion_spec: QueryExpansionSpec = proto.Field( - proto.MESSAGE, - number=13, - message=QueryExpansionSpec, - ) - spell_correction_spec: SpellCorrectionSpec = proto.Field( - proto.MESSAGE, - number=14, - message=SpellCorrectionSpec, - ) - user_pseudo_id: str = proto.Field( - proto.STRING, - number=15, - ) - content_search_spec: ContentSearchSpec = proto.Field( - proto.MESSAGE, - number=24, - message=ContentSearchSpec, - ) - embedding_spec: EmbeddingSpec = proto.Field( - proto.MESSAGE, - number=23, - message=EmbeddingSpec, - ) - ranking_expression: str = proto.Field( - proto.STRING, - number=26, - ) - safe_search: bool = proto.Field( - proto.BOOL, - number=20, - ) - user_labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=22, - ) - - -class SearchResponse(proto.Message): - r"""Response message for - [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] - method. - - Attributes: - results (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchResponse.SearchResult]): - A list of matched documents. The order - represents the ranking. - facets (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchResponse.Facet]): - Results of facets requested by user. - guided_search_result (google.cloud.discoveryengine_v1beta.types.SearchResponse.GuidedSearchResult): - Guided search result. - total_size (int): - The estimated total count of matched items irrespective of - pagination. The count of - [results][google.cloud.discoveryengine.v1beta.SearchResponse.results] - returned by pagination may be less than the - [total_size][google.cloud.discoveryengine.v1beta.SearchResponse.total_size] - that matches. - attribution_token (str): - A unique search token. This should be included in the - [UserEvent][google.cloud.discoveryengine.v1beta.UserEvent] - logs resulting from this search, which enables accurate - attribution of search model performance. - redirect_uri (str): - The URI of a customer-defined redirect page. If redirect - action is triggered, no search is performed, and only - [redirect_uri][google.cloud.discoveryengine.v1beta.SearchResponse.redirect_uri] - and - [attribution_token][google.cloud.discoveryengine.v1beta.SearchResponse.attribution_token] - are set in the response. - next_page_token (str): - A token that can be sent as - [SearchRequest.page_token][google.cloud.discoveryengine.v1beta.SearchRequest.page_token] - to retrieve the next page. If this field is omitted, there - are no subsequent pages. - corrected_query (str): - Contains the spell corrected query, if found. If the spell - correction type is AUTOMATIC, then the search results are - based on corrected_query. Otherwise the original query is - used for search. - summary (google.cloud.discoveryengine_v1beta.types.SearchResponse.Summary): - A summary as part of the search results. This field is only - returned if - [SearchRequest.ContentSearchSpec.summary_spec][google.cloud.discoveryengine.v1beta.SearchRequest.ContentSearchSpec.summary_spec] - is set. - applied_controls (MutableSequence[str]): - Controls applied as part of the Control - service. - query_expansion_info (google.cloud.discoveryengine_v1beta.types.SearchResponse.QueryExpansionInfo): - Query expansion information for the returned - results. - """ - - class SearchResult(proto.Message): - r"""Represents the search results. - - Attributes: - id (str): - [Document.id][google.cloud.discoveryengine.v1beta.Document.id] - of the searched - [Document][google.cloud.discoveryengine.v1beta.Document]. - document (google.cloud.discoveryengine_v1beta.types.Document): - The document data snippet in the search - response. Only fields that are marked as - retrievable are populated. - model_scores (MutableMapping[str, google.cloud.discoveryengine_v1beta.types.DoubleList]): - Google provided available scores. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - document: gcd_document.Document = proto.Field( - proto.MESSAGE, - number=2, - message=gcd_document.Document, - ) - model_scores: MutableMapping[str, common.DoubleList] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=4, - message=common.DoubleList, - ) - - class Facet(proto.Message): - r"""A facet result. - - Attributes: - key (str): - The key for this facet. E.g., "colors" or "price". It - matches - [SearchRequest.FacetSpec.FacetKey.key][google.cloud.discoveryengine.v1beta.SearchRequest.FacetSpec.FacetKey.key]. - values (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchResponse.Facet.FacetValue]): - The facet values for this field. - dynamic_facet (bool): - Whether the facet is dynamically generated. - """ - - class FacetValue(proto.Message): - r"""A facet value which contains value names and their count. - - 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: - value (str): - Text value of a facet, such as "Black" for - facet "colors". - - This field is a member of `oneof`_ ``facet_value``. - interval (google.cloud.discoveryengine_v1beta.types.Interval): - Interval value for a facet, such as [10, 20) for facet - "price". It matches - [SearchRequest.FacetSpec.FacetKey.intervals][google.cloud.discoveryengine.v1beta.SearchRequest.FacetSpec.FacetKey.intervals]. - - This field is a member of `oneof`_ ``facet_value``. - count (int): - Number of items that have this facet value. - """ - - value: str = proto.Field( - proto.STRING, - number=1, - oneof='facet_value', - ) - interval: common.Interval = proto.Field( - proto.MESSAGE, - number=2, - oneof='facet_value', - message=common.Interval, - ) - count: int = proto.Field( - proto.INT64, - number=3, - ) - - key: str = proto.Field( - proto.STRING, - number=1, - ) - values: MutableSequence['SearchResponse.Facet.FacetValue'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='SearchResponse.Facet.FacetValue', - ) - dynamic_facet: bool = proto.Field( - proto.BOOL, - number=3, - ) - - class GuidedSearchResult(proto.Message): - r"""Guided search result. The guided search helps user to refine - the search results and narrow down to the real needs from a - broaded search results. - - Attributes: - refinement_attributes (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchResponse.GuidedSearchResult.RefinementAttribute]): - A list of ranked refinement attributes. - follow_up_questions (MutableSequence[str]): - Suggested follow-up questions. - """ - - class RefinementAttribute(proto.Message): - r"""Useful attribute for search result refinements. - - Attributes: - attribute_key (str): - Attribute key used to refine the results e.g. 'movie_type'. - attribute_value (str): - Attribute value used to refine the results - e.g. 'drama'. - """ - - attribute_key: str = proto.Field( - proto.STRING, - number=1, - ) - attribute_value: str = proto.Field( - proto.STRING, - number=2, - ) - - refinement_attributes: MutableSequence['SearchResponse.GuidedSearchResult.RefinementAttribute'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SearchResponse.GuidedSearchResult.RefinementAttribute', - ) - follow_up_questions: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - class Summary(proto.Message): - r"""Summary of the top N search result specified by the summary - spec. - - Attributes: - summary_text (str): - The summary content. - summary_skipped_reasons (MutableSequence[google.cloud.discoveryengine_v1beta.types.SearchResponse.Summary.SummarySkippedReason]): - Additional summary-skipped reasons. This - provides the reason for ignored cases. If - nothing is skipped, this field is not set. - safety_attributes (google.cloud.discoveryengine_v1beta.types.SearchResponse.Summary.SafetyAttributes): - A collection of Safety Attribute categories - and their associated confidence scores. - """ - class SummarySkippedReason(proto.Enum): - r"""An Enum for summary-skipped reasons. - - Values: - SUMMARY_SKIPPED_REASON_UNSPECIFIED (0): - Default value. The summary skipped reason is - not specified. - ADVERSARIAL_QUERY_IGNORED (1): - The adversarial query ignored case. - - Only populated when - [SummarySpec.ignore_adversarial_query][google.cloud.discoveryengine.v1beta.SearchRequest.ContentSearchSpec.SummarySpec.ignore_adversarial_query] - is set to ``true``. - NON_SUMMARY_SEEKING_QUERY_IGNORED (2): - The non-summary seeking query ignored case. - - Only populated when - [SummarySpec.ignore_non_summary_seeking_query][google.cloud.discoveryengine.v1beta.SearchRequest.ContentSearchSpec.SummarySpec.ignore_non_summary_seeking_query] - is set to ``true``. - OUT_OF_DOMAIN_QUERY_IGNORED (3): - The out-of-domain query ignored case. - - Google skips the summary if there are no - high-relevance search results. For example, the - data store contains facts about company A but - the user query is asking questions about company - B. - POTENTIAL_POLICY_VIOLATION (4): - The potential policy violation case. - - Google skips the summary if there is a potential - policy violation detected. This includes content - that may be violent or toxic. - LLM_ADDON_NOT_ENABLED (5): - The LLM addon not enabled case. - - Google skips the summary if the LLM addon is not - enabled. - """ - SUMMARY_SKIPPED_REASON_UNSPECIFIED = 0 - ADVERSARIAL_QUERY_IGNORED = 1 - NON_SUMMARY_SEEKING_QUERY_IGNORED = 2 - OUT_OF_DOMAIN_QUERY_IGNORED = 3 - POTENTIAL_POLICY_VIOLATION = 4 - LLM_ADDON_NOT_ENABLED = 5 - - class SafetyAttributes(proto.Message): - r"""Safety Attribute categories and their associated confidence - scores. - - Attributes: - categories (MutableSequence[str]): - The display names of Safety Attribute - categories associated with the generated - content. Order matches the Scores. - scores (MutableSequence[float]): - The confidence scores of the each category, - higher value means higher confidence. Order - matches the Categories. - """ - - categories: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - scores: MutableSequence[float] = proto.RepeatedField( - proto.FLOAT, - number=2, - ) - - summary_text: str = proto.Field( - proto.STRING, - number=1, - ) - summary_skipped_reasons: MutableSequence['SearchResponse.Summary.SummarySkippedReason'] = proto.RepeatedField( - proto.ENUM, - number=2, - enum='SearchResponse.Summary.SummarySkippedReason', - ) - safety_attributes: 'SearchResponse.Summary.SafetyAttributes' = proto.Field( - proto.MESSAGE, - number=3, - message='SearchResponse.Summary.SafetyAttributes', - ) - - class QueryExpansionInfo(proto.Message): - r"""Information describing query expansion including whether - expansion has occurred. - - Attributes: - expanded_query (bool): - Bool describing whether query expansion has - occurred. - pinned_result_count (int): - Number of pinned results. This field will only be set when - expansion happens and - [SearchRequest.QueryExpansionSpec.pin_unexpanded_results][google.cloud.discoveryengine.v1beta.SearchRequest.QueryExpansionSpec.pin_unexpanded_results] - is set to true. - """ - - expanded_query: bool = proto.Field( - proto.BOOL, - number=1, - ) - pinned_result_count: int = proto.Field( - proto.INT64, - number=2, - ) - - @property - def raw_page(self): - return self - - results: MutableSequence[SearchResult] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=SearchResult, - ) - facets: MutableSequence[Facet] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=Facet, - ) - guided_search_result: GuidedSearchResult = proto.Field( - proto.MESSAGE, - number=8, - message=GuidedSearchResult, - ) - total_size: int = proto.Field( - proto.INT32, - number=3, - ) - attribution_token: str = proto.Field( - proto.STRING, - number=4, - ) - redirect_uri: str = proto.Field( - proto.STRING, - number=12, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=5, - ) - corrected_query: str = proto.Field( - proto.STRING, - number=7, - ) - summary: Summary = proto.Field( - proto.MESSAGE, - number=9, - message=Summary, - ) - applied_controls: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=10, - ) - query_expansion_info: QueryExpansionInfo = proto.Field( - proto.MESSAGE, - number=14, - message=QueryExpansionInfo, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/user_event.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/user_event.py deleted file mode 100644 index 26f29fcf13c5..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/user_event.py +++ /dev/null @@ -1,758 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.discoveryengine_v1beta.types import common -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1beta', - manifest={ - 'UserEvent', - 'PageInfo', - 'SearchInfo', - 'CompletionInfo', - 'TransactionInfo', - 'DocumentInfo', - 'PanelInfo', - 'MediaInfo', - }, -) - - -class UserEvent(proto.Message): - r"""UserEvent captures all metadata information Discovery Engine - API needs to know about how end users interact with customers' - website. - - Attributes: - event_type (str): - Required. User event type. Allowed values are: - - Generic values: - - - ``search``: Search for Documents. - - ``view-item``: Detailed page view of a Document. - - ``view-item-list``: View of a panel or ordered list of - Documents. - - ``view-home-page``: View of the home page. - - ``view-category-page``: View of a category page, e.g. - Home > Men > Jeans - - Retail-related values: - - - ``add-to-cart``: Add an item(s) to cart, e.g. in Retail - online shopping - - ``purchase``: Purchase an item(s) - - Media-related values: - - - ``media-play``: Start/resume watching a video, playing a - song, etc. - - ``media-complete``: Finished or stopped midway through a - video, song, etc. - user_pseudo_id (str): - Required. A unique identifier for tracking visitors. - - For example, this could be implemented with an HTTP cookie, - which should be able to uniquely identify a visitor on a - single device. This unique identifier should not change if - the visitor log in/out of the website. - - Do not set the field to the same fixed ID for different - users. This mixes the event history of those users together, - which results in degraded model quality. - - The field must be a UTF-8 encoded string with a length limit - of 128 characters. Otherwise, an ``INVALID_ARGUMENT`` error - is returned. - - The field should not contain PII or user-data. We recommend - to use Google Analytics `Client - ID `__ - for this field. - event_time (google.protobuf.timestamp_pb2.Timestamp): - Only required for - [UserEventService.ImportUserEvents][google.cloud.discoveryengine.v1beta.UserEventService.ImportUserEvents] - method. Timestamp of when the user event happened. - user_info (google.cloud.discoveryengine_v1beta.types.UserInfo): - Information about the end user. - direct_user_request (bool): - Should set to true if the request is made directly from the - end user, in which case the - [UserEvent.user_info.user_agent][google.cloud.discoveryengine.v1beta.UserInfo.user_agent] - can be populated from the HTTP request. - - This flag should be set only if the API request is made - directly from the end user such as a mobile app (and not if - a gateway or a server is processing and pushing the user - events). - - This should not be set when using the JavaScript tag in - [UserEventService.CollectUserEvent][google.cloud.discoveryengine.v1beta.UserEventService.CollectUserEvent]. - session_id (str): - A unique identifier for tracking a visitor session with a - length limit of 128 bytes. A session is an aggregation of an - end user behavior in a time span. - - A general guideline to populate the session_id: - - 1. If user has no activity for 30 min, a new session_id - should be assigned. - 2. The session_id should be unique across users, suggest use - uuid or add - [UserEvent.user_pseudo_id][google.cloud.discoveryengine.v1beta.UserEvent.user_pseudo_id] - as prefix. - page_info (google.cloud.discoveryengine_v1beta.types.PageInfo): - Page metadata such as categories and other critical - information for certain event types such as - ``view-category-page``. - attribution_token (str): - Token to attribute an API response to user action(s) to - trigger the event. - - Highly recommended for user events that are the result of - [RecommendationService.Recommend][google.cloud.discoveryengine.v1beta.RecommendationService.Recommend]. - This field enables accurate attribution of recommendation - model performance. - - The value must be one of: - - - [RecommendResponse.attribution_token][google.cloud.discoveryengine.v1beta.RecommendResponse.attribution_token] - for events that are the result of - [RecommendationService.Recommend][google.cloud.discoveryengine.v1beta.RecommendationService.Recommend]. - - [SearchResponse.attribution_token][google.cloud.discoveryengine.v1beta.SearchResponse.attribution_token] - for events that are the result of - [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search]. - - This token enables us to accurately attribute page view or - conversion completion back to the event and the particular - predict response containing this clicked/purchased product. - If user clicks on product K in the recommendation results, - pass - [RecommendResponse.attribution_token][google.cloud.discoveryengine.v1beta.RecommendResponse.attribution_token] - as a URL parameter to product K's page. When recording - events on product K's page, log the - [RecommendResponse.attribution_token][google.cloud.discoveryengine.v1beta.RecommendResponse.attribution_token] - to this field. - filter (str): - The filter syntax consists of an expression language for - constructing a predicate from one or more fields of the - documents being filtered. - - One example is for ``search`` events, the associated - [SearchRequest][google.cloud.discoveryengine.v1beta.SearchRequest] - may contain a filter expression in - [SearchRequest.filter][google.cloud.discoveryengine.v1beta.SearchRequest.filter] - conforming to https://google.aip.dev/160#filtering. - - Similarly, for ``view-item-list`` events that are generated - from a [RecommendationService.RecommendRequest][], this - field may be populated directly from - [RecommendationService.RecommendRequest.filter][] conforming - to https://google.aip.dev/160#filtering. - - The value must be a UTF-8 encoded string with a length limit - of 1,000 characters. Otherwise, an ``INVALID_ARGUMENT`` - error is returned. - documents (MutableSequence[google.cloud.discoveryengine_v1beta.types.DocumentInfo]): - List of - [Document][google.cloud.discoveryengine.v1beta.Document]s - associated with this user event. - - This field is optional except for the following event types: - - - ``view-item`` - - ``add-to-cart`` - - ``purchase`` - - ``media-play`` - - ``media-complete`` - - In a ``search`` event, this field represents the documents - returned to the end user on the current page (the end user - may have not finished browsing the whole page yet). When a - new page is returned to the end user, after - pagination/filtering/ordering even for the same query, a new - ``search`` event with different - [UserEvent.documents][google.cloud.discoveryengine.v1beta.UserEvent.documents] - is desired. - panel (google.cloud.discoveryengine_v1beta.types.PanelInfo): - Panel metadata associated with this user - event. - search_info (google.cloud.discoveryengine_v1beta.types.SearchInfo): - [SearchService.Search][google.cloud.discoveryengine.v1beta.SearchService.Search] - details related to the event. - - This field should be set for ``search`` event. - completion_info (google.cloud.discoveryengine_v1beta.types.CompletionInfo): - [CompletionService.CompleteQuery][google.cloud.discoveryengine.v1beta.CompletionService.CompleteQuery] - details related to the event. - - This field should be set for ``search`` event when - autocomplete function is enabled and the user clicks a - suggestion for search. - transaction_info (google.cloud.discoveryengine_v1beta.types.TransactionInfo): - The transaction metadata (if any) associated - with this user event. - tag_ids (MutableSequence[str]): - A list of identifiers for the independent - experiment groups this user event belongs to. - This is used to distinguish between user events - associated with different experiment setups on - the customer end. - promotion_ids (MutableSequence[str]): - The promotion IDs if this is an event - associated with promotions. Currently, this - field is restricted to at most one ID. - attributes (MutableMapping[str, google.cloud.discoveryengine_v1beta.types.CustomAttribute]): - Extra user event features to include in the recommendation - model. These attributes must NOT contain data that needs to - be parsed or processed further, e.g. JSON or other - encodings. - - If you provide custom attributes for ingested user events, - also include them in the user events that you associate with - prediction requests. Custom attribute formatting must be - consistent between imported events and events provided with - prediction requests. This lets the Discovery Engine API use - those custom attributes when training models and serving - predictions, which helps improve recommendation quality. - - This field needs to pass all below criteria, otherwise an - ``INVALID_ARGUMENT`` error is returned: - - - The key must be a UTF-8 encoded string with a length - limit of 5,000 characters. - - For text attributes, at most 400 values are allowed. - Empty values are not allowed. Each value must be a UTF-8 - encoded string with a length limit of 256 characters. - - For number attributes, at most 400 values are allowed. - - For product recommendations, an example of extra user - information is ``traffic_channel``, which is how a user - arrives at the site. Users can arrive at the site by coming - to the site directly, coming through Google search, or in - other ways. - media_info (google.cloud.discoveryengine_v1beta.types.MediaInfo): - Media-specific info. - """ - - event_type: str = proto.Field( - proto.STRING, - number=1, - ) - user_pseudo_id: str = proto.Field( - proto.STRING, - number=2, - ) - event_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - user_info: common.UserInfo = proto.Field( - proto.MESSAGE, - number=4, - message=common.UserInfo, - ) - direct_user_request: bool = proto.Field( - proto.BOOL, - number=5, - ) - session_id: str = proto.Field( - proto.STRING, - number=6, - ) - page_info: 'PageInfo' = proto.Field( - proto.MESSAGE, - number=7, - message='PageInfo', - ) - attribution_token: str = proto.Field( - proto.STRING, - number=8, - ) - filter: str = proto.Field( - proto.STRING, - number=9, - ) - documents: MutableSequence['DocumentInfo'] = proto.RepeatedField( - proto.MESSAGE, - number=10, - message='DocumentInfo', - ) - panel: 'PanelInfo' = proto.Field( - proto.MESSAGE, - number=11, - message='PanelInfo', - ) - search_info: 'SearchInfo' = proto.Field( - proto.MESSAGE, - number=12, - message='SearchInfo', - ) - completion_info: 'CompletionInfo' = proto.Field( - proto.MESSAGE, - number=13, - message='CompletionInfo', - ) - transaction_info: 'TransactionInfo' = proto.Field( - proto.MESSAGE, - number=14, - message='TransactionInfo', - ) - tag_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=15, - ) - promotion_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=16, - ) - attributes: MutableMapping[str, common.CustomAttribute] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=17, - message=common.CustomAttribute, - ) - media_info: 'MediaInfo' = proto.Field( - proto.MESSAGE, - number=18, - message='MediaInfo', - ) - - -class PageInfo(proto.Message): - r"""Detailed page information. - - Attributes: - pageview_id (str): - A unique ID of a web page view. - - This should be kept the same for all user events triggered - from the same pageview. For example, an item detail page - view could trigger multiple events as the user is browsing - the page. The ``pageview_id`` property should be kept the - same for all these events so that they can be grouped - together properly. - - When using the client side event reporting with JavaScript - pixel and Google Tag Manager, this value is filled in - automatically. - page_category (str): - The most specific category associated with a category page. - - To represent full path of category, use '>' sign to separate - different hierarchies. If '>' is part of the category name, - please replace it with other character(s). - - Category pages include special pages such as sales or - promotions. For instance, a special sale page may have the - category hierarchy: - ``"pageCategory" : "Sales > 2017 Black Friday Deals"``. - - Required for ``view-category-page`` events. Other event - types should not set this field. Otherwise, an - ``INVALID_ARGUMENT`` error is returned. - uri (str): - Complete URL (window.location.href) of the - user's current page. - When using the client side event reporting with - JavaScript pixel and Google Tag Manager, this - value is filled in automatically. Maximum length - 5,000 characters. - referrer_uri (str): - The referrer URL of the current page. - - When using the client side event reporting with - JavaScript pixel and Google Tag Manager, this - value is filled in automatically. However, some - browser privacy restrictions may cause this - field to be empty. - """ - - pageview_id: str = proto.Field( - proto.STRING, - number=1, - ) - page_category: str = proto.Field( - proto.STRING, - number=2, - ) - uri: str = proto.Field( - proto.STRING, - number=3, - ) - referrer_uri: str = proto.Field( - proto.STRING, - number=4, - ) - - -class SearchInfo(proto.Message): - r"""Detailed search information. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - search_query (str): - The user's search query. - - See - [SearchRequest.query][google.cloud.discoveryengine.v1beta.SearchRequest.query] - for definition. - - The value must be a UTF-8 encoded string with a length limit - of 5,000 characters. Otherwise, an ``INVALID_ARGUMENT`` - error is returned. - - At least one of - [search_query][google.cloud.discoveryengine.v1beta.SearchInfo.search_query] - or - [PageInfo.page_category][google.cloud.discoveryengine.v1beta.PageInfo.page_category] - is required for ``search`` events. Other event types should - not set this field. Otherwise, an ``INVALID_ARGUMENT`` error - is returned. - order_by (str): - The order in which products are returned, if applicable. - - See - [SearchRequest.order_by][google.cloud.discoveryengine.v1beta.SearchRequest.order_by] - for definition and syntax. - - The value must be a UTF-8 encoded string with a length limit - of 1,000 characters. Otherwise, an ``INVALID_ARGUMENT`` - error is returned. - - This can only be set for ``search`` events. Other event - types should not set this field. Otherwise, an - ``INVALID_ARGUMENT`` error is returned. - offset (int): - An integer that specifies the current offset for pagination - (the 0-indexed starting location, amongst the products - deemed by the API as relevant). - - See - [SearchRequest.offset][google.cloud.discoveryengine.v1beta.SearchRequest.offset] - for definition. - - If this field is negative, an ``INVALID_ARGUMENT`` is - returned. - - This can only be set for ``search`` events. Other event - types should not set this field. Otherwise, an - ``INVALID_ARGUMENT`` error is returned. - - This field is a member of `oneof`_ ``_offset``. - """ - - search_query: str = proto.Field( - proto.STRING, - number=1, - ) - order_by: str = proto.Field( - proto.STRING, - number=2, - ) - offset: int = proto.Field( - proto.INT32, - number=3, - optional=True, - ) - - -class CompletionInfo(proto.Message): - r"""Detailed completion information including completion - attribution token and clicked completion info. - - Attributes: - selected_suggestion (str): - End user selected - [CompleteQueryResponse.QuerySuggestion.suggestion][google.cloud.discoveryengine.v1beta.CompleteQueryResponse.QuerySuggestion.suggestion]. - selected_position (int): - End user selected - [CompleteQueryResponse.QuerySuggestion.suggestion][google.cloud.discoveryengine.v1beta.CompleteQueryResponse.QuerySuggestion.suggestion] - position, starting from 0. - """ - - selected_suggestion: str = proto.Field( - proto.STRING, - number=1, - ) - selected_position: int = proto.Field( - proto.INT32, - number=2, - ) - - -class TransactionInfo(proto.Message): - r"""A transaction represents the entire purchase transaction. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - value (float): - Required. Total non-zero value associated - with the transaction. This value may include - shipping, tax, or other adjustments to the total - value that you want to include. - - This field is a member of `oneof`_ ``_value``. - currency (str): - Required. Currency code. Use three-character - ISO-4217 code. - transaction_id (str): - The transaction ID with a length limit of 128 - characters. - tax (float): - All the taxes associated with the - transaction. - - This field is a member of `oneof`_ ``_tax``. - cost (float): - All the costs associated with the products. These can be - manufacturing costs, shipping expenses not borne by the end - user, or any other costs, such that: - - - Profit = - [value][google.cloud.discoveryengine.v1beta.TransactionInfo.value] - - - [tax][google.cloud.discoveryengine.v1beta.TransactionInfo.tax] - - - [cost][google.cloud.discoveryengine.v1beta.TransactionInfo.cost] - - This field is a member of `oneof`_ ``_cost``. - discount_value (float): - The total discount(s) value applied to this transaction. - This figure should be excluded from - [TransactionInfo.value][google.cloud.discoveryengine.v1beta.TransactionInfo.value] - - For example, if a user paid - [TransactionInfo.value][google.cloud.discoveryengine.v1beta.TransactionInfo.value] - amount, then nominal (pre-discount) value of the transaction - is the sum of - [TransactionInfo.value][google.cloud.discoveryengine.v1beta.TransactionInfo.value] - and - [TransactionInfo.discount_value][google.cloud.discoveryengine.v1beta.TransactionInfo.discount_value] - - This means that profit is calculated the same way, - regardless of the discount value, and that - [TransactionInfo.discount_value][google.cloud.discoveryengine.v1beta.TransactionInfo.discount_value] - can be larger than - [TransactionInfo.value][google.cloud.discoveryengine.v1beta.TransactionInfo.value]: - - - Profit = - [value][google.cloud.discoveryengine.v1beta.TransactionInfo.value] - - - [tax][google.cloud.discoveryengine.v1beta.TransactionInfo.tax] - - - [cost][google.cloud.discoveryengine.v1beta.TransactionInfo.cost] - - This field is a member of `oneof`_ ``_discount_value``. - """ - - value: float = proto.Field( - proto.FLOAT, - number=1, - optional=True, - ) - currency: str = proto.Field( - proto.STRING, - number=2, - ) - transaction_id: str = proto.Field( - proto.STRING, - number=3, - ) - tax: float = proto.Field( - proto.FLOAT, - number=4, - optional=True, - ) - cost: float = proto.Field( - proto.FLOAT, - number=5, - optional=True, - ) - discount_value: float = proto.Field( - proto.FLOAT, - number=6, - optional=True, - ) - - -class DocumentInfo(proto.Message): - r"""Detailed document information associated with a user event. - - 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: - id (str): - The [Document][google.cloud.discoveryengine.v1beta.Document] - resource ID. - - This field is a member of `oneof`_ ``document_descriptor``. - name (str): - The [Document][google.cloud.discoveryengine.v1beta.Document] - resource full name, of the form: - ``projects/{project_id}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}/branches/{branch_id}/documents/{document_id}`` - - This field is a member of `oneof`_ ``document_descriptor``. - uri (str): - The [Document][google.cloud.discoveryengine.v1beta.Document] - URI - only allowed for website data stores. - - This field is a member of `oneof`_ ``document_descriptor``. - quantity (int): - Quantity of the Document associated with the user event. - Defaults to 1. - - For example, this field will be 2 if two quantities of the - same Document are involved in a ``add-to-cart`` event. - - Required for events of the following event types: - - - ``add-to-cart`` - - ``purchase`` - - This field is a member of `oneof`_ ``_quantity``. - promotion_ids (MutableSequence[str]): - The promotion IDs associated with this - Document. Currently, this field is restricted to - at most one ID. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - oneof='document_descriptor', - ) - name: str = proto.Field( - proto.STRING, - number=2, - oneof='document_descriptor', - ) - uri: str = proto.Field( - proto.STRING, - number=6, - oneof='document_descriptor', - ) - quantity: int = proto.Field( - proto.INT32, - number=3, - optional=True, - ) - promotion_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - - -class PanelInfo(proto.Message): - r"""Detailed panel information associated with a user event. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - panel_id (str): - Required. The panel ID. - display_name (str): - The display name of the panel. - panel_position (int): - The ordered position of the panel, if shown to the user with - other panels. If set, then - [total_panels][google.cloud.discoveryengine.v1beta.PanelInfo.total_panels] - must also be set. - - This field is a member of `oneof`_ ``_panel_position``. - total_panels (int): - The total number of panels, including this one, shown to the - user. Must be set if - [panel_position][google.cloud.discoveryengine.v1beta.PanelInfo.panel_position] - is set. - - This field is a member of `oneof`_ ``_total_panels``. - """ - - panel_id: str = proto.Field( - proto.STRING, - number=2, - ) - display_name: str = proto.Field( - proto.STRING, - number=3, - ) - panel_position: int = proto.Field( - proto.INT32, - number=4, - optional=True, - ) - total_panels: int = proto.Field( - proto.INT32, - number=5, - optional=True, - ) - - -class MediaInfo(proto.Message): - r"""Media-specific user event information. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - media_progress_duration (google.protobuf.duration_pb2.Duration): - The media progress time in seconds, if applicable. For - example, if the end user has finished 90 seconds of a - playback video, then - [MediaInfo.media_progress_duration.seconds][google.protobuf.Duration.seconds] - should be set to 90. - media_progress_percentage (float): - Media progress should be computed using only the - [media_progress_duration][google.cloud.discoveryengine.v1beta.MediaInfo.media_progress_duration] - relative to the media total length. - - This value must be between ``[0, 1.0]`` inclusive. - - If this is not a playback or the progress cannot be computed - (e.g. ongoing livestream), this field should be unset. - - This field is a member of `oneof`_ ``_media_progress_percentage``. - """ - - media_progress_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - media_progress_percentage: float = proto.Field( - proto.FLOAT, - number=2, - optional=True, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/user_event_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/user_event_service.py deleted file mode 100644 index ae2bafcd2b09..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/google/cloud/discoveryengine_v1beta/types/user_event_service.py +++ /dev/null @@ -1,110 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.discoveryengine_v1beta.types import user_event as gcd_user_event - - -__protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1beta', - manifest={ - 'WriteUserEventRequest', - 'CollectUserEventRequest', - }, -) - - -class WriteUserEventRequest(proto.Message): - r"""Request message for WriteUserEvent method. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - parent (str): - Required. The parent DataStore resource name, such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. - user_event (google.cloud.discoveryengine_v1beta.types.UserEvent): - Required. User event to write. - - This field is a member of `oneof`_ ``_user_event``. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - user_event: gcd_user_event.UserEvent = proto.Field( - proto.MESSAGE, - number=2, - optional=True, - message=gcd_user_event.UserEvent, - ) - - -class CollectUserEventRequest(proto.Message): - r"""Request message for CollectUserEvent method. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - parent (str): - Required. The parent DataStore resource name, such as - ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}``. - user_event (str): - Required. URL encoded UserEvent proto with a - length limit of 2,000,000 characters. - uri (str): - The URL including cgi-parameters but - excluding the hash fragment with a length limit - of 5,000 characters. This is often more useful - than the referer URL, because many browsers only - send the domain for third-party requests. - - This field is a member of `oneof`_ ``_uri``. - ets (int): - The event timestamp in milliseconds. This - prevents browser caching of otherwise identical - get requests. The name is abbreviated to reduce - the payload bytes. - - This field is a member of `oneof`_ ``_ets``. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - user_event: str = proto.Field( - proto.STRING, - number=2, - ) - uri: str = proto.Field( - proto.STRING, - number=3, - optional=True, - ) - ets: int = proto.Field( - proto.INT64, - number=4, - optional=True, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/mypy.ini b/owl-bot-staging/google-cloud-discoveryengine/v1beta/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/noxfile.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/noxfile.py deleted file mode 100644 index 292cf3ef4497..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/noxfile.py +++ /dev/null @@ -1,184 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.11" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "lint_setup_py", -] - -@nox.session(python=ALL_PYTHON) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/discoveryengine_v1beta/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - 'mypy', - 'types-requests', - 'types-protobuf' - ) - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==7.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_completion_service_complete_query_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_completion_service_complete_query_async.py deleted file mode 100644 index c3292d2432b8..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_completion_service_complete_query_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CompleteQuery -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_CompletionService_CompleteQuery_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -async def sample_complete_query(): - # Create a client - client = discoveryengine_v1beta.CompletionServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.CompleteQueryRequest( - data_store="data_store_value", - query="query_value", - ) - - # Make the request - response = await client.complete_query(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1beta_generated_CompletionService_CompleteQuery_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_completion_service_complete_query_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_completion_service_complete_query_sync.py deleted file mode 100644 index dc9950fc9b3a..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_completion_service_complete_query_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CompleteQuery -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_CompletionService_CompleteQuery_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -def sample_complete_query(): - # Create a client - client = discoveryengine_v1beta.CompletionServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.CompleteQueryRequest( - data_store="data_store_value", - query="query_value", - ) - - # Make the request - response = client.complete_query(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1beta_generated_CompletionService_CompleteQuery_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_converse_conversation_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_converse_conversation_async.py deleted file mode 100644 index f9c364caab7a..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_converse_conversation_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ConverseConversation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_ConversationalSearchService_ConverseConversation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -async def sample_converse_conversation(): - # Create a client - client = discoveryengine_v1beta.ConversationalSearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.ConverseConversationRequest( - name="name_value", - ) - - # Make the request - response = await client.converse_conversation(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1beta_generated_ConversationalSearchService_ConverseConversation_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_converse_conversation_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_converse_conversation_sync.py deleted file mode 100644 index 0ca10055d668..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_converse_conversation_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ConverseConversation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_ConversationalSearchService_ConverseConversation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -def sample_converse_conversation(): - # Create a client - client = discoveryengine_v1beta.ConversationalSearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.ConverseConversationRequest( - name="name_value", - ) - - # Make the request - response = client.converse_conversation(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1beta_generated_ConversationalSearchService_ConverseConversation_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_create_conversation_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_create_conversation_async.py deleted file mode 100644 index 71813f019c97..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_create_conversation_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateConversation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_ConversationalSearchService_CreateConversation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -async def sample_create_conversation(): - # Create a client - client = discoveryengine_v1beta.ConversationalSearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.CreateConversationRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_conversation(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1beta_generated_ConversationalSearchService_CreateConversation_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_create_conversation_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_create_conversation_sync.py deleted file mode 100644 index 1eda69c9ace4..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_create_conversation_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateConversation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_ConversationalSearchService_CreateConversation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -def sample_create_conversation(): - # Create a client - client = discoveryengine_v1beta.ConversationalSearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.CreateConversationRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_conversation(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1beta_generated_ConversationalSearchService_CreateConversation_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_delete_conversation_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_delete_conversation_async.py deleted file mode 100644 index b4a32a25bc03..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_delete_conversation_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteConversation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_ConversationalSearchService_DeleteConversation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -async def sample_delete_conversation(): - # Create a client - client = discoveryengine_v1beta.ConversationalSearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.DeleteConversationRequest( - name="name_value", - ) - - # Make the request - await client.delete_conversation(request=request) - - -# [END discoveryengine_v1beta_generated_ConversationalSearchService_DeleteConversation_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_delete_conversation_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_delete_conversation_sync.py deleted file mode 100644 index 81456ccabed9..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_delete_conversation_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteConversation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_ConversationalSearchService_DeleteConversation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -def sample_delete_conversation(): - # Create a client - client = discoveryengine_v1beta.ConversationalSearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.DeleteConversationRequest( - name="name_value", - ) - - # Make the request - client.delete_conversation(request=request) - - -# [END discoveryengine_v1beta_generated_ConversationalSearchService_DeleteConversation_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_get_conversation_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_get_conversation_async.py deleted file mode 100644 index 584182019e79..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_get_conversation_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetConversation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_ConversationalSearchService_GetConversation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -async def sample_get_conversation(): - # Create a client - client = discoveryengine_v1beta.ConversationalSearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.GetConversationRequest( - name="name_value", - ) - - # Make the request - response = await client.get_conversation(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1beta_generated_ConversationalSearchService_GetConversation_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_get_conversation_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_get_conversation_sync.py deleted file mode 100644 index ba1560fdc73f..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_get_conversation_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetConversation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_ConversationalSearchService_GetConversation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -def sample_get_conversation(): - # Create a client - client = discoveryengine_v1beta.ConversationalSearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.GetConversationRequest( - name="name_value", - ) - - # Make the request - response = client.get_conversation(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1beta_generated_ConversationalSearchService_GetConversation_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_list_conversations_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_list_conversations_async.py deleted file mode 100644 index 8a66f51f457e..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_list_conversations_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListConversations -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_ConversationalSearchService_ListConversations_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -async def sample_list_conversations(): - # Create a client - client = discoveryengine_v1beta.ConversationalSearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.ListConversationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversations(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END discoveryengine_v1beta_generated_ConversationalSearchService_ListConversations_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_list_conversations_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_list_conversations_sync.py deleted file mode 100644 index bd74d5aac498..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_list_conversations_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListConversations -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_ConversationalSearchService_ListConversations_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -def sample_list_conversations(): - # Create a client - client = discoveryengine_v1beta.ConversationalSearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.ListConversationsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_conversations(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END discoveryengine_v1beta_generated_ConversationalSearchService_ListConversations_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_update_conversation_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_update_conversation_async.py deleted file mode 100644 index 6a2315f983e4..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_update_conversation_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for 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-discoveryengine - - -# [START discoveryengine_v1beta_generated_ConversationalSearchService_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 discoveryengine_v1beta - - -async def sample_update_conversation(): - # Create a client - client = discoveryengine_v1beta.ConversationalSearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.UpdateConversationRequest( - ) - - # Make the request - response = await client.update_conversation(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1beta_generated_ConversationalSearchService_UpdateConversation_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_update_conversation_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_update_conversation_sync.py deleted file mode 100644 index 9d7655198a12..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_conversational_search_service_update_conversation_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for 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-discoveryengine - - -# [START discoveryengine_v1beta_generated_ConversationalSearchService_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 discoveryengine_v1beta - - -def sample_update_conversation(): - # Create a client - client = discoveryengine_v1beta.ConversationalSearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.UpdateConversationRequest( - ) - - # Make the request - response = client.update_conversation(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1beta_generated_ConversationalSearchService_UpdateConversation_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_create_document_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_create_document_async.py deleted file mode 100644 index c5ad5307b7dc..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_create_document_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_DocumentService_CreateDocument_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -async def sample_create_document(): - # Create a client - client = discoveryengine_v1beta.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.CreateDocumentRequest( - parent="parent_value", - document_id="document_id_value", - ) - - # Make the request - response = await client.create_document(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1beta_generated_DocumentService_CreateDocument_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_create_document_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_create_document_sync.py deleted file mode 100644 index 581b4de727d3..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_create_document_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_DocumentService_CreateDocument_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -def sample_create_document(): - # Create a client - client = discoveryengine_v1beta.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.CreateDocumentRequest( - parent="parent_value", - document_id="document_id_value", - ) - - # Make the request - response = client.create_document(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1beta_generated_DocumentService_CreateDocument_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_delete_document_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_delete_document_async.py deleted file mode 100644 index 10de40428e12..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_delete_document_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_DocumentService_DeleteDocument_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -async def sample_delete_document(): - # Create a client - client = discoveryengine_v1beta.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.DeleteDocumentRequest( - name="name_value", - ) - - # Make the request - await client.delete_document(request=request) - - -# [END discoveryengine_v1beta_generated_DocumentService_DeleteDocument_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_delete_document_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_delete_document_sync.py deleted file mode 100644 index 3c93fc37d1f0..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_delete_document_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_DocumentService_DeleteDocument_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -def sample_delete_document(): - # Create a client - client = discoveryengine_v1beta.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.DeleteDocumentRequest( - name="name_value", - ) - - # Make the request - client.delete_document(request=request) - - -# [END discoveryengine_v1beta_generated_DocumentService_DeleteDocument_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_get_document_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_get_document_async.py deleted file mode 100644 index 5f4c88f34930..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_get_document_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_DocumentService_GetDocument_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -async def sample_get_document(): - # Create a client - client = discoveryengine_v1beta.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.GetDocumentRequest( - name="name_value", - ) - - # Make the request - response = await client.get_document(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1beta_generated_DocumentService_GetDocument_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_get_document_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_get_document_sync.py deleted file mode 100644 index f86f8f96daaa..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_get_document_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_DocumentService_GetDocument_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -def sample_get_document(): - # Create a client - client = discoveryengine_v1beta.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.GetDocumentRequest( - name="name_value", - ) - - # Make the request - response = client.get_document(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1beta_generated_DocumentService_GetDocument_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_import_documents_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_import_documents_async.py deleted file mode 100644 index 948a10a23148..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_import_documents_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportDocuments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_DocumentService_ImportDocuments_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -async def sample_import_documents(): - # Create a client - client = discoveryengine_v1beta.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.ImportDocumentsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.import_documents(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END discoveryengine_v1beta_generated_DocumentService_ImportDocuments_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_import_documents_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_import_documents_sync.py deleted file mode 100644 index 2637559cffe6..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_import_documents_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportDocuments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_DocumentService_ImportDocuments_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -def sample_import_documents(): - # Create a client - client = discoveryengine_v1beta.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.ImportDocumentsRequest( - parent="parent_value", - ) - - # Make the request - operation = client.import_documents(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END discoveryengine_v1beta_generated_DocumentService_ImportDocuments_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_list_documents_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_list_documents_async.py deleted file mode 100644 index e90d8a1e53f9..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_list_documents_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListDocuments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_DocumentService_ListDocuments_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -async def sample_list_documents(): - # Create a client - client = discoveryengine_v1beta.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.ListDocumentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_documents(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END discoveryengine_v1beta_generated_DocumentService_ListDocuments_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_list_documents_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_list_documents_sync.py deleted file mode 100644 index dca286461a3f..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_list_documents_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListDocuments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_DocumentService_ListDocuments_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -def sample_list_documents(): - # Create a client - client = discoveryengine_v1beta.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.ListDocumentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_documents(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END discoveryengine_v1beta_generated_DocumentService_ListDocuments_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_purge_documents_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_purge_documents_async.py deleted file mode 100644 index 7733ae956e3e..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_purge_documents_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PurgeDocuments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_DocumentService_PurgeDocuments_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -async def sample_purge_documents(): - # Create a client - client = discoveryengine_v1beta.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.PurgeDocumentsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_documents(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END discoveryengine_v1beta_generated_DocumentService_PurgeDocuments_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_purge_documents_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_purge_documents_sync.py deleted file mode 100644 index 2ef4b0163400..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_purge_documents_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for PurgeDocuments -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_DocumentService_PurgeDocuments_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -def sample_purge_documents(): - # Create a client - client = discoveryengine_v1beta.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.PurgeDocumentsRequest( - parent="parent_value", - filter="filter_value", - ) - - # Make the request - operation = client.purge_documents(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END discoveryengine_v1beta_generated_DocumentService_PurgeDocuments_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_update_document_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_update_document_async.py deleted file mode 100644 index 553079df811e..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_update_document_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_DocumentService_UpdateDocument_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -async def sample_update_document(): - # Create a client - client = discoveryengine_v1beta.DocumentServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.UpdateDocumentRequest( - ) - - # Make the request - response = await client.update_document(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1beta_generated_DocumentService_UpdateDocument_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_update_document_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_update_document_sync.py deleted file mode 100644 index 47e00ab8eabe..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_document_service_update_document_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateDocument -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_DocumentService_UpdateDocument_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -def sample_update_document(): - # Create a client - client = discoveryengine_v1beta.DocumentServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.UpdateDocumentRequest( - ) - - # Make the request - response = client.update_document(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1beta_generated_DocumentService_UpdateDocument_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_recommendation_service_recommend_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_recommendation_service_recommend_async.py deleted file mode 100644 index 818b8ead4440..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_recommendation_service_recommend_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Recommend -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_RecommendationService_Recommend_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -async def sample_recommend(): - # Create a client - client = discoveryengine_v1beta.RecommendationServiceAsyncClient() - - # Initialize request argument(s) - user_event = discoveryengine_v1beta.UserEvent() - user_event.event_type = "event_type_value" - user_event.user_pseudo_id = "user_pseudo_id_value" - - request = discoveryengine_v1beta.RecommendRequest( - serving_config="serving_config_value", - user_event=user_event, - ) - - # Make the request - response = await client.recommend(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1beta_generated_RecommendationService_Recommend_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_recommendation_service_recommend_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_recommendation_service_recommend_sync.py deleted file mode 100644 index 36bcd43f7ad6..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_recommendation_service_recommend_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Recommend -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_RecommendationService_Recommend_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -def sample_recommend(): - # Create a client - client = discoveryengine_v1beta.RecommendationServiceClient() - - # Initialize request argument(s) - user_event = discoveryengine_v1beta.UserEvent() - user_event.event_type = "event_type_value" - user_event.user_pseudo_id = "user_pseudo_id_value" - - request = discoveryengine_v1beta.RecommendRequest( - serving_config="serving_config_value", - user_event=user_event, - ) - - # Make the request - response = client.recommend(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1beta_generated_RecommendationService_Recommend_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_create_schema_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_create_schema_async.py deleted file mode 100644 index 1e44a6c60abd..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_create_schema_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateSchema -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_SchemaService_CreateSchema_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -async def sample_create_schema(): - # Create a client - client = discoveryengine_v1beta.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.CreateSchemaRequest( - parent="parent_value", - schema_id="schema_id_value", - ) - - # Make the request - operation = client.create_schema(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END discoveryengine_v1beta_generated_SchemaService_CreateSchema_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_create_schema_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_create_schema_sync.py deleted file mode 100644 index 0652ba5ecc49..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_create_schema_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateSchema -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_SchemaService_CreateSchema_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -def sample_create_schema(): - # Create a client - client = discoveryengine_v1beta.SchemaServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.CreateSchemaRequest( - parent="parent_value", - schema_id="schema_id_value", - ) - - # Make the request - operation = client.create_schema(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END discoveryengine_v1beta_generated_SchemaService_CreateSchema_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_delete_schema_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_delete_schema_async.py deleted file mode 100644 index a4ad35ded987..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_delete_schema_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteSchema -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_SchemaService_DeleteSchema_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -async def sample_delete_schema(): - # Create a client - client = discoveryengine_v1beta.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.DeleteSchemaRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_schema(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END discoveryengine_v1beta_generated_SchemaService_DeleteSchema_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_delete_schema_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_delete_schema_sync.py deleted file mode 100644 index 8981de597436..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_delete_schema_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteSchema -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_SchemaService_DeleteSchema_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -def sample_delete_schema(): - # Create a client - client = discoveryengine_v1beta.SchemaServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.DeleteSchemaRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_schema(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END discoveryengine_v1beta_generated_SchemaService_DeleteSchema_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_get_schema_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_get_schema_async.py deleted file mode 100644 index f4a57057f3fe..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_get_schema_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetSchema -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_SchemaService_GetSchema_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -async def sample_get_schema(): - # Create a client - client = discoveryengine_v1beta.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.GetSchemaRequest( - name="name_value", - ) - - # Make the request - response = await client.get_schema(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1beta_generated_SchemaService_GetSchema_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_get_schema_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_get_schema_sync.py deleted file mode 100644 index 0aad48195870..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_get_schema_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetSchema -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_SchemaService_GetSchema_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -def sample_get_schema(): - # Create a client - client = discoveryengine_v1beta.SchemaServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.GetSchemaRequest( - name="name_value", - ) - - # Make the request - response = client.get_schema(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1beta_generated_SchemaService_GetSchema_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_list_schemas_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_list_schemas_async.py deleted file mode 100644 index 80cd936b534c..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_list_schemas_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListSchemas -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_SchemaService_ListSchemas_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -async def sample_list_schemas(): - # Create a client - client = discoveryengine_v1beta.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.ListSchemasRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_schemas(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END discoveryengine_v1beta_generated_SchemaService_ListSchemas_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_list_schemas_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_list_schemas_sync.py deleted file mode 100644 index 8188c22dc744..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_list_schemas_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListSchemas -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_SchemaService_ListSchemas_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -def sample_list_schemas(): - # Create a client - client = discoveryengine_v1beta.SchemaServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.ListSchemasRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_schemas(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END discoveryengine_v1beta_generated_SchemaService_ListSchemas_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_update_schema_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_update_schema_async.py deleted file mode 100644 index f525193651c9..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_update_schema_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateSchema -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_SchemaService_UpdateSchema_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -async def sample_update_schema(): - # Create a client - client = discoveryengine_v1beta.SchemaServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.UpdateSchemaRequest( - ) - - # Make the request - operation = client.update_schema(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END discoveryengine_v1beta_generated_SchemaService_UpdateSchema_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_update_schema_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_update_schema_sync.py deleted file mode 100644 index e411a1f88c0e..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_schema_service_update_schema_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateSchema -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_SchemaService_UpdateSchema_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -def sample_update_schema(): - # Create a client - client = discoveryengine_v1beta.SchemaServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.UpdateSchemaRequest( - ) - - # Make the request - operation = client.update_schema(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END discoveryengine_v1beta_generated_SchemaService_UpdateSchema_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_search_service_search_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_search_service_search_async.py deleted file mode 100644 index acf0a5f6ee77..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_search_service_search_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Search -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_SearchService_Search_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -async def sample_search(): - # Create a client - client = discoveryengine_v1beta.SearchServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.SearchRequest( - serving_config="serving_config_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END discoveryengine_v1beta_generated_SearchService_Search_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_search_service_search_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_search_service_search_sync.py deleted file mode 100644 index d2bf3cd00472..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_search_service_search_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Search -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_SearchService_Search_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -def sample_search(): - # Create a client - client = discoveryengine_v1beta.SearchServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.SearchRequest( - serving_config="serving_config_value", - ) - - # Make the request - page_result = client.search(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END discoveryengine_v1beta_generated_SearchService_Search_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_collect_user_event_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_collect_user_event_async.py deleted file mode 100644 index eff216b60ec9..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_collect_user_event_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CollectUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_UserEventService_CollectUserEvent_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -async def sample_collect_user_event(): - # Create a client - client = discoveryengine_v1beta.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = await client.collect_user_event(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1beta_generated_UserEventService_CollectUserEvent_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_collect_user_event_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_collect_user_event_sync.py deleted file mode 100644 index ce0fa980ede5..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_collect_user_event_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CollectUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_UserEventService_CollectUserEvent_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -def sample_collect_user_event(): - # Create a client - client = discoveryengine_v1beta.UserEventServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.CollectUserEventRequest( - parent="parent_value", - user_event="user_event_value", - ) - - # Make the request - response = client.collect_user_event(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1beta_generated_UserEventService_CollectUserEvent_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_import_user_events_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_import_user_events_async.py deleted file mode 100644 index 267845582b52..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_import_user_events_async.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_UserEventService_ImportUserEvents_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -async def sample_import_user_events(): - # Create a client - client = discoveryengine_v1beta.UserEventServiceAsyncClient() - - # Initialize request argument(s) - inline_source = discoveryengine_v1beta.InlineSource() - inline_source.user_events.event_type = "event_type_value" - inline_source.user_events.user_pseudo_id = "user_pseudo_id_value" - - request = discoveryengine_v1beta.ImportUserEventsRequest( - inline_source=inline_source, - parent="parent_value", - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END discoveryengine_v1beta_generated_UserEventService_ImportUserEvents_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_import_user_events_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_import_user_events_sync.py deleted file mode 100644 index f00b3a4f695d..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_import_user_events_sync.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportUserEvents -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_UserEventService_ImportUserEvents_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -def sample_import_user_events(): - # Create a client - client = discoveryengine_v1beta.UserEventServiceClient() - - # Initialize request argument(s) - inline_source = discoveryengine_v1beta.InlineSource() - inline_source.user_events.event_type = "event_type_value" - inline_source.user_events.user_pseudo_id = "user_pseudo_id_value" - - request = discoveryengine_v1beta.ImportUserEventsRequest( - inline_source=inline_source, - parent="parent_value", - ) - - # Make the request - operation = client.import_user_events(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END discoveryengine_v1beta_generated_UserEventService_ImportUserEvents_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_write_user_event_async.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_write_user_event_async.py deleted file mode 100644 index e3c1279f13c8..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_write_user_event_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for WriteUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_UserEventService_WriteUserEvent_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -async def sample_write_user_event(): - # Create a client - client = discoveryengine_v1beta.UserEventServiceAsyncClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.WriteUserEventRequest( - parent="parent_value", - ) - - # Make the request - response = await client.write_user_event(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1beta_generated_UserEventService_WriteUserEvent_async] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_write_user_event_sync.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_write_user_event_sync.py deleted file mode 100644 index 0559a9f48518..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/discoveryengine_v1beta_generated_user_event_service_write_user_event_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for WriteUserEvent -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-discoveryengine - - -# [START discoveryengine_v1beta_generated_UserEventService_WriteUserEvent_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import discoveryengine_v1beta - - -def sample_write_user_event(): - # Create a client - client = discoveryengine_v1beta.UserEventServiceClient() - - # Initialize request argument(s) - request = discoveryengine_v1beta.WriteUserEventRequest( - parent="parent_value", - ) - - # Make the request - response = client.write_user_event(request=request) - - # Handle the response - print(response) - -# [END discoveryengine_v1beta_generated_UserEventService_WriteUserEvent_sync] diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1beta.json b/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1beta.json deleted file mode 100644 index 5ef34e5b313b..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1beta.json +++ /dev/null @@ -1,3843 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.discoveryengine.v1beta", - "version": "v1beta" - } - ], - "language": "PYTHON", - "name": "google-cloud-discoveryengine", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.CompletionServiceAsyncClient", - "shortName": "CompletionServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.CompletionServiceAsyncClient.complete_query", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.CompletionService.CompleteQuery", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "CompleteQuery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.CompleteQueryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1beta.types.CompleteQueryResponse", - "shortName": "complete_query" - }, - "description": "Sample for CompleteQuery", - "file": "discoveryengine_v1beta_generated_completion_service_complete_query_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_CompletionService_CompleteQuery_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": "discoveryengine_v1beta_generated_completion_service_complete_query_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.CompletionServiceClient", - "shortName": "CompletionServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.CompletionServiceClient.complete_query", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.CompletionService.CompleteQuery", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.CompletionService", - "shortName": "CompletionService" - }, - "shortName": "CompleteQuery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.CompleteQueryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1beta.types.CompleteQueryResponse", - "shortName": "complete_query" - }, - "description": "Sample for CompleteQuery", - "file": "discoveryengine_v1beta_generated_completion_service_complete_query_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_CompletionService_CompleteQuery_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": "discoveryengine_v1beta_generated_completion_service_complete_query_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceAsyncClient", - "shortName": "ConversationalSearchServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceAsyncClient.converse_conversation", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService.ConverseConversation", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService", - "shortName": "ConversationalSearchService" - }, - "shortName": "ConverseConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.ConverseConversationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "query", - "type": "google.cloud.discoveryengine_v1beta.types.TextInput" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1beta.types.ConverseConversationResponse", - "shortName": "converse_conversation" - }, - "description": "Sample for ConverseConversation", - "file": "discoveryengine_v1beta_generated_conversational_search_service_converse_conversation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_ConversationalSearchService_ConverseConversation_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": "discoveryengine_v1beta_generated_conversational_search_service_converse_conversation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceClient", - "shortName": "ConversationalSearchServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceClient.converse_conversation", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService.ConverseConversation", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService", - "shortName": "ConversationalSearchService" - }, - "shortName": "ConverseConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.ConverseConversationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "query", - "type": "google.cloud.discoveryengine_v1beta.types.TextInput" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1beta.types.ConverseConversationResponse", - "shortName": "converse_conversation" - }, - "description": "Sample for ConverseConversation", - "file": "discoveryengine_v1beta_generated_conversational_search_service_converse_conversation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_ConversationalSearchService_ConverseConversation_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": "discoveryengine_v1beta_generated_conversational_search_service_converse_conversation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceAsyncClient", - "shortName": "ConversationalSearchServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceAsyncClient.create_conversation", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService.CreateConversation", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService", - "shortName": "ConversationalSearchService" - }, - "shortName": "CreateConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.CreateConversationRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "conversation", - "type": "google.cloud.discoveryengine_v1beta.types.Conversation" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1beta.types.Conversation", - "shortName": "create_conversation" - }, - "description": "Sample for CreateConversation", - "file": "discoveryengine_v1beta_generated_conversational_search_service_create_conversation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_ConversationalSearchService_CreateConversation_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": "discoveryengine_v1beta_generated_conversational_search_service_create_conversation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceClient", - "shortName": "ConversationalSearchServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceClient.create_conversation", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService.CreateConversation", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService", - "shortName": "ConversationalSearchService" - }, - "shortName": "CreateConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.CreateConversationRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "conversation", - "type": "google.cloud.discoveryengine_v1beta.types.Conversation" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1beta.types.Conversation", - "shortName": "create_conversation" - }, - "description": "Sample for CreateConversation", - "file": "discoveryengine_v1beta_generated_conversational_search_service_create_conversation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_ConversationalSearchService_CreateConversation_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": "discoveryengine_v1beta_generated_conversational_search_service_create_conversation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceAsyncClient", - "shortName": "ConversationalSearchServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceAsyncClient.delete_conversation", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService.DeleteConversation", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService", - "shortName": "ConversationalSearchService" - }, - "shortName": "DeleteConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.DeleteConversationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_conversation" - }, - "description": "Sample for DeleteConversation", - "file": "discoveryengine_v1beta_generated_conversational_search_service_delete_conversation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_ConversationalSearchService_DeleteConversation_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": "discoveryengine_v1beta_generated_conversational_search_service_delete_conversation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceClient", - "shortName": "ConversationalSearchServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceClient.delete_conversation", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService.DeleteConversation", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService", - "shortName": "ConversationalSearchService" - }, - "shortName": "DeleteConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.DeleteConversationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_conversation" - }, - "description": "Sample for DeleteConversation", - "file": "discoveryengine_v1beta_generated_conversational_search_service_delete_conversation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_ConversationalSearchService_DeleteConversation_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": "discoveryengine_v1beta_generated_conversational_search_service_delete_conversation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceAsyncClient", - "shortName": "ConversationalSearchServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceAsyncClient.get_conversation", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService.GetConversation", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService", - "shortName": "ConversationalSearchService" - }, - "shortName": "GetConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.GetConversationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1beta.types.Conversation", - "shortName": "get_conversation" - }, - "description": "Sample for GetConversation", - "file": "discoveryengine_v1beta_generated_conversational_search_service_get_conversation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_ConversationalSearchService_GetConversation_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": "discoveryengine_v1beta_generated_conversational_search_service_get_conversation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceClient", - "shortName": "ConversationalSearchServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceClient.get_conversation", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService.GetConversation", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService", - "shortName": "ConversationalSearchService" - }, - "shortName": "GetConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.GetConversationRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1beta.types.Conversation", - "shortName": "get_conversation" - }, - "description": "Sample for GetConversation", - "file": "discoveryengine_v1beta_generated_conversational_search_service_get_conversation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_ConversationalSearchService_GetConversation_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": "discoveryengine_v1beta_generated_conversational_search_service_get_conversation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceAsyncClient", - "shortName": "ConversationalSearchServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceAsyncClient.list_conversations", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService.ListConversations", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService", - "shortName": "ConversationalSearchService" - }, - "shortName": "ListConversations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.ListConversationsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1beta.services.conversational_search_service.pagers.ListConversationsAsyncPager", - "shortName": "list_conversations" - }, - "description": "Sample for ListConversations", - "file": "discoveryengine_v1beta_generated_conversational_search_service_list_conversations_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_ConversationalSearchService_ListConversations_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": "discoveryengine_v1beta_generated_conversational_search_service_list_conversations_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceClient", - "shortName": "ConversationalSearchServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceClient.list_conversations", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService.ListConversations", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService", - "shortName": "ConversationalSearchService" - }, - "shortName": "ListConversations" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.ListConversationsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1beta.services.conversational_search_service.pagers.ListConversationsPager", - "shortName": "list_conversations" - }, - "description": "Sample for ListConversations", - "file": "discoveryengine_v1beta_generated_conversational_search_service_list_conversations_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_ConversationalSearchService_ListConversations_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": "discoveryengine_v1beta_generated_conversational_search_service_list_conversations_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceAsyncClient", - "shortName": "ConversationalSearchServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceAsyncClient.update_conversation", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService.UpdateConversation", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService", - "shortName": "ConversationalSearchService" - }, - "shortName": "UpdateConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.UpdateConversationRequest" - }, - { - "name": "conversation", - "type": "google.cloud.discoveryengine_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, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1beta.types.Conversation", - "shortName": "update_conversation" - }, - "description": "Sample for UpdateConversation", - "file": "discoveryengine_v1beta_generated_conversational_search_service_update_conversation_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_ConversationalSearchService_UpdateConversation_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": "discoveryengine_v1beta_generated_conversational_search_service_update_conversation_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceClient", - "shortName": "ConversationalSearchServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.ConversationalSearchServiceClient.update_conversation", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService.UpdateConversation", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.ConversationalSearchService", - "shortName": "ConversationalSearchService" - }, - "shortName": "UpdateConversation" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.UpdateConversationRequest" - }, - { - "name": "conversation", - "type": "google.cloud.discoveryengine_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, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1beta.types.Conversation", - "shortName": "update_conversation" - }, - "description": "Sample for UpdateConversation", - "file": "discoveryengine_v1beta_generated_conversational_search_service_update_conversation_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_ConversationalSearchService_UpdateConversation_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": "discoveryengine_v1beta_generated_conversational_search_service_update_conversation_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceAsyncClient", - "shortName": "DocumentServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceAsyncClient.create_document", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.DocumentService.CreateDocument", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "CreateDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.CreateDocumentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "document", - "type": "google.cloud.discoveryengine_v1beta.types.Document" - }, - { - "name": "document_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1beta.types.Document", - "shortName": "create_document" - }, - "description": "Sample for CreateDocument", - "file": "discoveryengine_v1beta_generated_document_service_create_document_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_DocumentService_CreateDocument_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": "discoveryengine_v1beta_generated_document_service_create_document_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceClient", - "shortName": "DocumentServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceClient.create_document", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.DocumentService.CreateDocument", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "CreateDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.CreateDocumentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "document", - "type": "google.cloud.discoveryengine_v1beta.types.Document" - }, - { - "name": "document_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1beta.types.Document", - "shortName": "create_document" - }, - "description": "Sample for CreateDocument", - "file": "discoveryengine_v1beta_generated_document_service_create_document_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_DocumentService_CreateDocument_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": "discoveryengine_v1beta_generated_document_service_create_document_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceAsyncClient", - "shortName": "DocumentServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceAsyncClient.delete_document", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.DocumentService.DeleteDocument", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "DeleteDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.DeleteDocumentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_document" - }, - "description": "Sample for DeleteDocument", - "file": "discoveryengine_v1beta_generated_document_service_delete_document_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_DocumentService_DeleteDocument_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": "discoveryengine_v1beta_generated_document_service_delete_document_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceClient", - "shortName": "DocumentServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceClient.delete_document", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.DocumentService.DeleteDocument", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "DeleteDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.DeleteDocumentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_document" - }, - "description": "Sample for DeleteDocument", - "file": "discoveryengine_v1beta_generated_document_service_delete_document_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_DocumentService_DeleteDocument_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": "discoveryengine_v1beta_generated_document_service_delete_document_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceAsyncClient", - "shortName": "DocumentServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceAsyncClient.get_document", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.DocumentService.GetDocument", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "GetDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.GetDocumentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1beta.types.Document", - "shortName": "get_document" - }, - "description": "Sample for GetDocument", - "file": "discoveryengine_v1beta_generated_document_service_get_document_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_DocumentService_GetDocument_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": "discoveryengine_v1beta_generated_document_service_get_document_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceClient", - "shortName": "DocumentServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceClient.get_document", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.DocumentService.GetDocument", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "GetDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.GetDocumentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1beta.types.Document", - "shortName": "get_document" - }, - "description": "Sample for GetDocument", - "file": "discoveryengine_v1beta_generated_document_service_get_document_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_DocumentService_GetDocument_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": "discoveryengine_v1beta_generated_document_service_get_document_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceAsyncClient", - "shortName": "DocumentServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceAsyncClient.import_documents", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.DocumentService.ImportDocuments", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "ImportDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.ImportDocumentsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "import_documents" - }, - "description": "Sample for ImportDocuments", - "file": "discoveryengine_v1beta_generated_document_service_import_documents_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_DocumentService_ImportDocuments_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": "discoveryengine_v1beta_generated_document_service_import_documents_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceClient", - "shortName": "DocumentServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceClient.import_documents", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.DocumentService.ImportDocuments", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "ImportDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.ImportDocumentsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "import_documents" - }, - "description": "Sample for ImportDocuments", - "file": "discoveryengine_v1beta_generated_document_service_import_documents_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_DocumentService_ImportDocuments_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": "discoveryengine_v1beta_generated_document_service_import_documents_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceAsyncClient", - "shortName": "DocumentServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceAsyncClient.list_documents", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.DocumentService.ListDocuments", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "ListDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.ListDocumentsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1beta.services.document_service.pagers.ListDocumentsAsyncPager", - "shortName": "list_documents" - }, - "description": "Sample for ListDocuments", - "file": "discoveryengine_v1beta_generated_document_service_list_documents_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_DocumentService_ListDocuments_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": "discoveryengine_v1beta_generated_document_service_list_documents_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceClient", - "shortName": "DocumentServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceClient.list_documents", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.DocumentService.ListDocuments", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "ListDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.ListDocumentsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1beta.services.document_service.pagers.ListDocumentsPager", - "shortName": "list_documents" - }, - "description": "Sample for ListDocuments", - "file": "discoveryengine_v1beta_generated_document_service_list_documents_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_DocumentService_ListDocuments_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": "discoveryengine_v1beta_generated_document_service_list_documents_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceAsyncClient", - "shortName": "DocumentServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceAsyncClient.purge_documents", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.DocumentService.PurgeDocuments", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "PurgeDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.PurgeDocumentsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "purge_documents" - }, - "description": "Sample for PurgeDocuments", - "file": "discoveryengine_v1beta_generated_document_service_purge_documents_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_DocumentService_PurgeDocuments_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": "discoveryengine_v1beta_generated_document_service_purge_documents_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceClient", - "shortName": "DocumentServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceClient.purge_documents", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.DocumentService.PurgeDocuments", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "PurgeDocuments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.PurgeDocumentsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "purge_documents" - }, - "description": "Sample for PurgeDocuments", - "file": "discoveryengine_v1beta_generated_document_service_purge_documents_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_DocumentService_PurgeDocuments_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": "discoveryengine_v1beta_generated_document_service_purge_documents_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceAsyncClient", - "shortName": "DocumentServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceAsyncClient.update_document", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.DocumentService.UpdateDocument", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "UpdateDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.UpdateDocumentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1beta.types.Document", - "shortName": "update_document" - }, - "description": "Sample for UpdateDocument", - "file": "discoveryengine_v1beta_generated_document_service_update_document_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_DocumentService_UpdateDocument_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": "discoveryengine_v1beta_generated_document_service_update_document_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceClient", - "shortName": "DocumentServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.DocumentServiceClient.update_document", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.DocumentService.UpdateDocument", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.DocumentService", - "shortName": "DocumentService" - }, - "shortName": "UpdateDocument" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.UpdateDocumentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1beta.types.Document", - "shortName": "update_document" - }, - "description": "Sample for UpdateDocument", - "file": "discoveryengine_v1beta_generated_document_service_update_document_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_DocumentService_UpdateDocument_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": "discoveryengine_v1beta_generated_document_service_update_document_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.RecommendationServiceAsyncClient", - "shortName": "RecommendationServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.RecommendationServiceAsyncClient.recommend", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.RecommendationService.Recommend", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.RecommendationService", - "shortName": "RecommendationService" - }, - "shortName": "Recommend" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.RecommendRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1beta.types.RecommendResponse", - "shortName": "recommend" - }, - "description": "Sample for Recommend", - "file": "discoveryengine_v1beta_generated_recommendation_service_recommend_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_RecommendationService_Recommend_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "discoveryengine_v1beta_generated_recommendation_service_recommend_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.RecommendationServiceClient", - "shortName": "RecommendationServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.RecommendationServiceClient.recommend", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.RecommendationService.Recommend", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.RecommendationService", - "shortName": "RecommendationService" - }, - "shortName": "Recommend" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.RecommendRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1beta.types.RecommendResponse", - "shortName": "recommend" - }, - "description": "Sample for Recommend", - "file": "discoveryengine_v1beta_generated_recommendation_service_recommend_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_RecommendationService_Recommend_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "discoveryengine_v1beta_generated_recommendation_service_recommend_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient", - "shortName": "SchemaServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient.create_schema", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.CreateSchema", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "CreateSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.CreateSchemaRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "schema", - "type": "google.cloud.discoveryengine_v1beta.types.Schema" - }, - { - "name": "schema_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_schema" - }, - "description": "Sample for CreateSchema", - "file": "discoveryengine_v1beta_generated_schema_service_create_schema_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SchemaService_CreateSchema_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": "discoveryengine_v1beta_generated_schema_service_create_schema_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient", - "shortName": "SchemaServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient.create_schema", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.CreateSchema", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "CreateSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.CreateSchemaRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "schema", - "type": "google.cloud.discoveryengine_v1beta.types.Schema" - }, - { - "name": "schema_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_schema" - }, - "description": "Sample for CreateSchema", - "file": "discoveryengine_v1beta_generated_schema_service_create_schema_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SchemaService_CreateSchema_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": "discoveryengine_v1beta_generated_schema_service_create_schema_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient", - "shortName": "SchemaServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient.delete_schema", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.DeleteSchema", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "DeleteSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.DeleteSchemaRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_schema" - }, - "description": "Sample for DeleteSchema", - "file": "discoveryengine_v1beta_generated_schema_service_delete_schema_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SchemaService_DeleteSchema_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": "discoveryengine_v1beta_generated_schema_service_delete_schema_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient", - "shortName": "SchemaServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient.delete_schema", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.DeleteSchema", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "DeleteSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.DeleteSchemaRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_schema" - }, - "description": "Sample for DeleteSchema", - "file": "discoveryengine_v1beta_generated_schema_service_delete_schema_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SchemaService_DeleteSchema_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": "discoveryengine_v1beta_generated_schema_service_delete_schema_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient", - "shortName": "SchemaServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient.get_schema", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.GetSchema", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "GetSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.GetSchemaRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1beta.types.Schema", - "shortName": "get_schema" - }, - "description": "Sample for GetSchema", - "file": "discoveryengine_v1beta_generated_schema_service_get_schema_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SchemaService_GetSchema_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": "discoveryengine_v1beta_generated_schema_service_get_schema_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient", - "shortName": "SchemaServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient.get_schema", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.GetSchema", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "GetSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.GetSchemaRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1beta.types.Schema", - "shortName": "get_schema" - }, - "description": "Sample for GetSchema", - "file": "discoveryengine_v1beta_generated_schema_service_get_schema_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SchemaService_GetSchema_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": "discoveryengine_v1beta_generated_schema_service_get_schema_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient", - "shortName": "SchemaServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient.list_schemas", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.ListSchemas", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "ListSchemas" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.ListSchemasRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1beta.services.schema_service.pagers.ListSchemasAsyncPager", - "shortName": "list_schemas" - }, - "description": "Sample for ListSchemas", - "file": "discoveryengine_v1beta_generated_schema_service_list_schemas_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SchemaService_ListSchemas_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": "discoveryengine_v1beta_generated_schema_service_list_schemas_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient", - "shortName": "SchemaServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient.list_schemas", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.ListSchemas", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "ListSchemas" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.ListSchemasRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1beta.services.schema_service.pagers.ListSchemasPager", - "shortName": "list_schemas" - }, - "description": "Sample for ListSchemas", - "file": "discoveryengine_v1beta_generated_schema_service_list_schemas_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SchemaService_ListSchemas_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": "discoveryengine_v1beta_generated_schema_service_list_schemas_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient", - "shortName": "SchemaServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceAsyncClient.update_schema", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.UpdateSchema", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "UpdateSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.UpdateSchemaRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_schema" - }, - "description": "Sample for UpdateSchema", - "file": "discoveryengine_v1beta_generated_schema_service_update_schema_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SchemaService_UpdateSchema_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "discoveryengine_v1beta_generated_schema_service_update_schema_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient", - "shortName": "SchemaServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.SchemaServiceClient.update_schema", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SchemaService.UpdateSchema", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.SchemaService", - "shortName": "SchemaService" - }, - "shortName": "UpdateSchema" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.UpdateSchemaRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_schema" - }, - "description": "Sample for UpdateSchema", - "file": "discoveryengine_v1beta_generated_schema_service_update_schema_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SchemaService_UpdateSchema_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "discoveryengine_v1beta_generated_schema_service_update_schema_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.SearchServiceAsyncClient", - "shortName": "SearchServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.SearchServiceAsyncClient.search", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SearchService.Search", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.SearchService", - "shortName": "SearchService" - }, - "shortName": "Search" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.SearchRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1beta.services.search_service.pagers.SearchAsyncPager", - "shortName": "search" - }, - "description": "Sample for Search", - "file": "discoveryengine_v1beta_generated_search_service_search_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SearchService_Search_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": "discoveryengine_v1beta_generated_search_service_search_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.SearchServiceClient", - "shortName": "SearchServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.SearchServiceClient.search", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.SearchService.Search", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.SearchService", - "shortName": "SearchService" - }, - "shortName": "Search" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.SearchRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1beta.services.search_service.pagers.SearchPager", - "shortName": "search" - }, - "description": "Sample for Search", - "file": "discoveryengine_v1beta_generated_search_service_search_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_SearchService_Search_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": "discoveryengine_v1beta_generated_search_service_search_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.UserEventServiceAsyncClient.collect_user_event", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.UserEventService.CollectUserEvent", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "CollectUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.CollectUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api.httpbody_pb2.HttpBody", - "shortName": "collect_user_event" - }, - "description": "Sample for CollectUserEvent", - "file": "discoveryengine_v1beta_generated_user_event_service_collect_user_event_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_UserEventService_CollectUserEvent_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": "discoveryengine_v1beta_generated_user_event_service_collect_user_event_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.UserEventServiceClient.collect_user_event", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.UserEventService.CollectUserEvent", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "CollectUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.CollectUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api.httpbody_pb2.HttpBody", - "shortName": "collect_user_event" - }, - "description": "Sample for CollectUserEvent", - "file": "discoveryengine_v1beta_generated_user_event_service_collect_user_event_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_UserEventService_CollectUserEvent_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": "discoveryengine_v1beta_generated_user_event_service_collect_user_event_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.UserEventServiceAsyncClient.import_user_events", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.UserEventService.ImportUserEvents", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "ImportUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.ImportUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "import_user_events" - }, - "description": "Sample for ImportUserEvents", - "file": "discoveryengine_v1beta_generated_user_event_service_import_user_events_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_UserEventService_ImportUserEvents_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": "discoveryengine_v1beta_generated_user_event_service_import_user_events_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.UserEventServiceClient.import_user_events", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.UserEventService.ImportUserEvents", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "ImportUserEvents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.ImportUserEventsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "import_user_events" - }, - "description": "Sample for ImportUserEvents", - "file": "discoveryengine_v1beta_generated_user_event_service_import_user_events_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_UserEventService_ImportUserEvents_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": "discoveryengine_v1beta_generated_user_event_service_import_user_events_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.UserEventServiceAsyncClient", - "shortName": "UserEventServiceAsyncClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.UserEventServiceAsyncClient.write_user_event", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.UserEventService.WriteUserEvent", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "WriteUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.WriteUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1beta.types.UserEvent", - "shortName": "write_user_event" - }, - "description": "Sample for WriteUserEvent", - "file": "discoveryengine_v1beta_generated_user_event_service_write_user_event_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_UserEventService_WriteUserEvent_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": "discoveryengine_v1beta_generated_user_event_service_write_user_event_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.discoveryengine_v1beta.UserEventServiceClient", - "shortName": "UserEventServiceClient" - }, - "fullName": "google.cloud.discoveryengine_v1beta.UserEventServiceClient.write_user_event", - "method": { - "fullName": "google.cloud.discoveryengine.v1beta.UserEventService.WriteUserEvent", - "service": { - "fullName": "google.cloud.discoveryengine.v1beta.UserEventService", - "shortName": "UserEventService" - }, - "shortName": "WriteUserEvent" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.discoveryengine_v1beta.types.WriteUserEventRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.discoveryengine_v1beta.types.UserEvent", - "shortName": "write_user_event" - }, - "description": "Sample for WriteUserEvent", - "file": "discoveryengine_v1beta_generated_user_event_service_write_user_event_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1beta_generated_UserEventService_WriteUserEvent_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": "discoveryengine_v1beta_generated_user_event_service_write_user_event_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/scripts/fixup_discoveryengine_v1beta_keywords.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/scripts/fixup_discoveryengine_v1beta_keywords.py deleted file mode 100644 index 713ab2895836..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/scripts/fixup_discoveryengine_v1beta_keywords.py +++ /dev/null @@ -1,199 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class discoveryengineCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'collect_user_event': ('parent', 'user_event', 'uri', 'ets', ), - 'complete_query': ('data_store', 'query', 'query_model', 'user_pseudo_id', 'include_tail_suggestions', ), - 'converse_conversation': ('name', 'query', 'serving_config', 'conversation', 'safe_search', 'user_labels', 'summary_spec', ), - 'create_conversation': ('parent', 'conversation', ), - 'create_document': ('parent', 'document', 'document_id', ), - 'create_schema': ('parent', 'schema', 'schema_id', ), - 'delete_conversation': ('name', ), - 'delete_document': ('name', ), - 'delete_schema': ('name', ), - 'get_conversation': ('name', ), - 'get_document': ('name', ), - 'get_schema': ('name', ), - 'import_documents': ('parent', 'inline_source', 'gcs_source', 'bigquery_source', 'error_config', 'reconciliation_mode', 'auto_generate_ids', 'id_field', ), - 'import_user_events': ('parent', 'inline_source', 'gcs_source', 'bigquery_source', 'error_config', ), - 'list_conversations': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'list_documents': ('parent', 'page_size', 'page_token', ), - 'list_schemas': ('parent', 'page_size', 'page_token', ), - 'purge_documents': ('parent', 'filter', 'force', ), - 'recommend': ('serving_config', 'user_event', 'page_size', 'filter', 'validate_only', 'params', 'user_labels', ), - 'search': ('serving_config', 'branch', 'query', 'image_query', 'page_size', 'page_token', 'offset', 'filter', 'order_by', 'user_info', 'facet_specs', 'boost_spec', 'params', 'query_expansion_spec', 'spell_correction_spec', 'user_pseudo_id', 'content_search_spec', 'embedding_spec', 'ranking_expression', 'safe_search', 'user_labels', ), - 'update_conversation': ('conversation', 'update_mask', ), - 'update_document': ('document', 'allow_missing', ), - 'update_schema': ('schema', 'allow_missing', ), - 'write_user_event': ('parent', 'user_event', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=discoveryengineCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the discoveryengine client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/setup.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/setup.py deleted file mode 100644 index 513896d68575..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/setup.py +++ /dev/null @@ -1,90 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-discoveryengine' - - -description = "Google Cloud Discoveryengine API client library" - -version = {} -with open(os.path.join(package_root, 'google/cloud/discoveryengine/gapic_version.py')) as fp: - exec(fp.read(), version) -version = version["__version__"] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "proto-plus >= 1.22.0, <2.0.0dev", - "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", - "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", -] -url = "https://github.com/googleapis/python-discoveryengine" - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, "README.rst") -with io.open(readme_filename, encoding="utf-8") as readme_file: - readme = readme_file.read() - -packages = [ - package - for package in setuptools.PEP420PackageFinder.find() - if package.startswith("google") -] - -namespaces = ["google", "google.cloud"] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - namespace_packages=namespaces, - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.10.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.10.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.11.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.11.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.12.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.12.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.7.txt deleted file mode 100644 index 6c44adfea7ee..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.7.txt +++ /dev/null @@ -1,9 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.0 -proto-plus==1.22.0 -protobuf==3.19.5 diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.8.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.8.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.9.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/testing/constraints-3.9.txt +++ /dev/null @@ -1,6 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/__init__.py deleted file mode 100644 index 1b4db446eb8d..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/__init__.py deleted file mode 100644 index 1b4db446eb8d..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/__init__.py deleted file mode 100644 index 1b4db446eb8d..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/__init__.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/__init__.py deleted file mode 100644 index 1b4db446eb8d..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_completion_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_completion_service.py deleted file mode 100644 index 4c8d6b6683dc..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_completion_service.py +++ /dev/null @@ -1,1920 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.discoveryengine_v1beta.services.completion_service import CompletionServiceAsyncClient -from google.cloud.discoveryengine_v1beta.services.completion_service import CompletionServiceClient -from google.cloud.discoveryengine_v1beta.services.completion_service import transports -from google.cloud.discoveryengine_v1beta.types import completion_service -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert CompletionServiceClient._get_default_mtls_endpoint(None) is None - assert CompletionServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert CompletionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (CompletionServiceClient, "grpc"), - (CompletionServiceAsyncClient, "grpc_asyncio"), - (CompletionServiceClient, "rest"), -]) -def test_completion_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.CompletionServiceGrpcTransport, "grpc"), - (transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.CompletionServiceRestTransport, "rest"), -]) -def test_completion_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", [ - (CompletionServiceClient, "grpc"), - (CompletionServiceAsyncClient, "grpc_asyncio"), - (CompletionServiceClient, "rest"), -]) -def test_completion_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -def test_completion_service_client_get_transport_class(): - transport = CompletionServiceClient.get_transport_class() - available_transports = [ - transports.CompletionServiceGrpcTransport, - transports.CompletionServiceRestTransport, - ] - assert transport in available_transports - - transport = CompletionServiceClient.get_transport_class("grpc") - assert transport == transports.CompletionServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (CompletionServiceClient, transports.CompletionServiceRestTransport, "rest"), -]) -@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) -@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) -def test_completion_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(CompletionServiceClient, '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(CompletionServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "true"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", "false"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (CompletionServiceClient, transports.CompletionServiceRestTransport, "rest", "true"), - (CompletionServiceClient, transports.CompletionServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) -@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_completion_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 - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - CompletionServiceClient, CompletionServiceAsyncClient -]) -@mock.patch.object(CompletionServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceClient)) -@mock.patch.object(CompletionServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(CompletionServiceAsyncClient)) -def test_completion_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc"), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (CompletionServiceClient, transports.CompletionServiceRestTransport, "rest"), -]) -def test_completion_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, - 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", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (CompletionServiceClient, transports.CompletionServiceRestTransport, "rest", None), -]) -def test_completion_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, - scopes=None, - client_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_completion_service_client_client_options_from_dict(): - with mock.patch('google.cloud.discoveryengine_v1beta.services.completion_service.transports.CompletionServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = CompletionServiceClient( - 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", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport, "grpc", grpc_helpers), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_completion_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, - scopes=None, - client_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - completion_service.CompleteQueryRequest, - dict, -]) -def test_complete_query(request_type, transport: str = 'grpc'): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = completion_service.CompleteQueryResponse( - tail_match_triggered=True, - ) - response = client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, completion_service.CompleteQueryResponse) - assert response.tail_match_triggered is True - - -def test_complete_query_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - client.complete_query() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - -@pytest.mark.asyncio -async def test_complete_query_async(transport: str = 'grpc_asyncio', request_type=completion_service.CompleteQueryRequest): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse( - tail_match_triggered=True, - )) - response = await client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == completion_service.CompleteQueryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, completion_service.CompleteQueryResponse) - assert response.tail_match_triggered is True - - -@pytest.mark.asyncio -async def test_complete_query_async_from_dict(): - await test_complete_query_async(request_type=dict) - - -def test_complete_query_field_headers(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = completion_service.CompleteQueryRequest() - - request.data_store = 'data_store_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - call.return_value = completion_service.CompleteQueryResponse() - client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'data_store=data_store_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_complete_query_field_headers_async(): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = completion_service.CompleteQueryRequest() - - request.data_store = 'data_store_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.complete_query), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(completion_service.CompleteQueryResponse()) - await client.complete_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'data_store=data_store_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - completion_service.CompleteQueryRequest, - dict, -]) -def test_complete_query_rest(request_type): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'data_store': 'projects/sample1/locations/sample2/dataStores/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 = completion_service.CompleteQueryResponse( - tail_match_triggered=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = completion_service.CompleteQueryResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.complete_query(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, completion_service.CompleteQueryResponse) - assert response.tail_match_triggered is True - - -def test_complete_query_rest_required_fields(request_type=completion_service.CompleteQueryRequest): - transport_class = transports.CompletionServiceRestTransport - - request_init = {} - request_init["data_store"] = "" - request_init["query"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "query" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).complete_query._get_unset_required_fields(jsonified_request) - 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["dataStore"] = 'data_store_value' - jsonified_request["query"] = 'query_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).complete_query._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("include_tail_suggestions", "query", "query_model", "user_pseudo_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "dataStore" in jsonified_request - assert jsonified_request["dataStore"] == 'data_store_value' - assert "query" in jsonified_request - assert jsonified_request["query"] == 'query_value' - - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = completion_service.CompleteQueryResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = completion_service.CompleteQueryResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.complete_query(request) - - expected_params = [ - ( - "query", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_complete_query_rest_unset_required_fields(): - transport = transports.CompletionServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.complete_query._get_unset_required_fields({}) - assert set(unset_fields) == (set(("includeTailSuggestions", "query", "queryModel", "userPseudoId", )) & set(("dataStore", "query", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_complete_query_rest_interceptors(null_interceptor): - transport = transports.CompletionServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.CompletionServiceRestInterceptor(), - ) - client = CompletionServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.CompletionServiceRestInterceptor, "post_complete_query") as post, \ - mock.patch.object(transports.CompletionServiceRestInterceptor, "pre_complete_query") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = completion_service.CompleteQueryRequest.pb(completion_service.CompleteQueryRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = completion_service.CompleteQueryResponse.to_json(completion_service.CompleteQueryResponse()) - - request = completion_service.CompleteQueryRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = completion_service.CompleteQueryResponse() - - client.complete_query(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_complete_query_rest_bad_request(transport: str = 'rest', request_type=completion_service.CompleteQueryRequest): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'data_store': 'projects/sample1/locations/sample2/dataStores/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.complete_query(request) - - -def test_complete_query_rest_error(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CompletionServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = CompletionServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CompletionServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.CompletionServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.CompletionServiceGrpcTransport, - transports.CompletionServiceGrpcAsyncIOTransport, - transports.CompletionServiceRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = CompletionServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.CompletionServiceGrpcTransport, - ) - -def test_completion_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.CompletionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_completion_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.discoveryengine_v1beta.services.completion_service.transports.CompletionServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.CompletionServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'complete_query', - 'get_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_completion_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.discoveryengine_v1beta.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CompletionServiceTransport( - 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_completion_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.discoveryengine_v1beta.services.completion_service.transports.CompletionServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CompletionServiceTransport() - adc.assert_called_once() - - -def test_completion_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) - CompletionServiceClient() - 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.CompletionServiceGrpcTransport, - transports.CompletionServiceGrpcAsyncIOTransport, - ], -) -def test_completion_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.CompletionServiceGrpcTransport, - transports.CompletionServiceGrpcAsyncIOTransport, - transports.CompletionServiceRestTransport, - ], -) -def test_completion_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.CompletionServiceGrpcTransport, grpc_helpers), - (transports.CompletionServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_completion_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) -def test_completion_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_completion_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.CompletionServiceRestTransport ( - 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_completion_service_host_no_port(transport_name): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_completion_service_host_with_port(transport_name): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_completion_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = CompletionServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = CompletionServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.complete_query._session - session2 = client2.transport.complete_query._session - assert session1 != session2 -def test_completion_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CompletionServiceGrpcTransport( - 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_completion_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.CompletionServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) -def test_completion_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.CompletionServiceGrpcTransport, transports.CompletionServiceGrpcAsyncIOTransport]) -def test_completion_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_data_store_path(): - project = "squid" - location = "clam" - data_store = "whelk" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) - actual = CompletionServiceClient.data_store_path(project, location, data_store) - assert expected == actual - - -def test_parse_data_store_path(): - expected = { - "project": "octopus", - "location": "oyster", - "data_store": "nudibranch", - } - path = CompletionServiceClient.data_store_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_data_store_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = CompletionServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = CompletionServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = CompletionServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = CompletionServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = CompletionServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = CompletionServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = CompletionServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = CompletionServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = CompletionServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = CompletionServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = CompletionServiceClient.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.CompletionServiceTransport, '_prep_wrapped_messages') as prep: - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.CompletionServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = CompletionServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_get_operation(transport: str = "grpc"): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = CompletionServiceClient( - 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 = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = CompletionServiceClient( - 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 = CompletionServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = CompletionServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = CompletionServiceClient( - 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", [ - (CompletionServiceClient, transports.CompletionServiceGrpcTransport), - (CompletionServiceAsyncClient, transports.CompletionServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_conversational_search_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_conversational_search_service.py deleted file mode 100644 index 5eab6d6bb3a0..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_conversational_search_service.py +++ /dev/null @@ -1,4908 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.discoveryengine_v1beta.services.conversational_search_service import ConversationalSearchServiceAsyncClient -from google.cloud.discoveryengine_v1beta.services.conversational_search_service import ConversationalSearchServiceClient -from google.cloud.discoveryengine_v1beta.services.conversational_search_service import pagers -from google.cloud.discoveryengine_v1beta.services.conversational_search_service import transports -from google.cloud.discoveryengine_v1beta.types import conversation -from google.cloud.discoveryengine_v1beta.types import conversation as gcd_conversation -from google.cloud.discoveryengine_v1beta.types import conversational_search_service -from google.cloud.discoveryengine_v1beta.types import search_service -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert ConversationalSearchServiceClient._get_default_mtls_endpoint(None) is None - assert ConversationalSearchServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ConversationalSearchServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ConversationalSearchServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ConversationalSearchServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ConversationalSearchServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ConversationalSearchServiceClient, "grpc"), - (ConversationalSearchServiceAsyncClient, "grpc_asyncio"), - (ConversationalSearchServiceClient, "rest"), -]) -def test_conversational_search_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ConversationalSearchServiceGrpcTransport, "grpc"), - (transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ConversationalSearchServiceRestTransport, "rest"), -]) -def test_conversational_search_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", [ - (ConversationalSearchServiceClient, "grpc"), - (ConversationalSearchServiceAsyncClient, "grpc_asyncio"), - (ConversationalSearchServiceClient, "rest"), -]) -def test_conversational_search_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -def test_conversational_search_service_client_get_transport_class(): - transport = ConversationalSearchServiceClient.get_transport_class() - available_transports = [ - transports.ConversationalSearchServiceGrpcTransport, - transports.ConversationalSearchServiceRestTransport, - ] - assert transport in available_transports - - transport = ConversationalSearchServiceClient.get_transport_class("grpc") - assert transport == transports.ConversationalSearchServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport, "grpc"), - (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (ConversationalSearchServiceClient, transports.ConversationalSearchServiceRestTransport, "rest"), -]) -@mock.patch.object(ConversationalSearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationalSearchServiceClient)) -@mock.patch.object(ConversationalSearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationalSearchServiceAsyncClient)) -def test_conversational_search_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(ConversationalSearchServiceClient, '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(ConversationalSearchServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport, "grpc", "true"), - (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport, "grpc", "false"), - (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (ConversationalSearchServiceClient, transports.ConversationalSearchServiceRestTransport, "rest", "true"), - (ConversationalSearchServiceClient, transports.ConversationalSearchServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(ConversationalSearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationalSearchServiceClient)) -@mock.patch.object(ConversationalSearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationalSearchServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_conversational_search_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 - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - ConversationalSearchServiceClient, ConversationalSearchServiceAsyncClient -]) -@mock.patch.object(ConversationalSearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationalSearchServiceClient)) -@mock.patch.object(ConversationalSearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConversationalSearchServiceAsyncClient)) -def test_conversational_search_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport, "grpc"), - (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (ConversationalSearchServiceClient, transports.ConversationalSearchServiceRestTransport, "rest"), -]) -def test_conversational_search_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, - 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", [ - (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport, "grpc", grpc_helpers), - (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (ConversationalSearchServiceClient, transports.ConversationalSearchServiceRestTransport, "rest", None), -]) -def test_conversational_search_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, - scopes=None, - client_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_conversational_search_service_client_client_options_from_dict(): - with mock.patch('google.cloud.discoveryengine_v1beta.services.conversational_search_service.transports.ConversationalSearchServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ConversationalSearchServiceClient( - 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", [ - (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport, "grpc", grpc_helpers), - (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_conversational_search_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, - scopes=None, - client_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - conversational_search_service.ConverseConversationRequest, - dict, -]) -def test_converse_conversation(request_type, transport: str = 'grpc'): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.converse_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversational_search_service.ConverseConversationResponse( - related_questions=['related_questions_value'], - ) - response = client.converse_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] == conversational_search_service.ConverseConversationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, conversational_search_service.ConverseConversationResponse) - assert response.related_questions == ['related_questions_value'] - - -def test_converse_conversation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.converse_conversation), - '__call__') as call: - client.converse_conversation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversational_search_service.ConverseConversationRequest() - -@pytest.mark.asyncio -async def test_converse_conversation_async(transport: str = 'grpc_asyncio', request_type=conversational_search_service.ConverseConversationRequest): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.converse_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversational_search_service.ConverseConversationResponse( - related_questions=['related_questions_value'], - )) - response = await client.converse_conversation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == conversational_search_service.ConverseConversationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, conversational_search_service.ConverseConversationResponse) - assert response.related_questions == ['related_questions_value'] - - -@pytest.mark.asyncio -async def test_converse_conversation_async_from_dict(): - await test_converse_conversation_async(request_type=dict) - - -def test_converse_conversation_field_headers(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversational_search_service.ConverseConversationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.converse_conversation), - '__call__') as call: - call.return_value = conversational_search_service.ConverseConversationResponse() - client.converse_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', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_converse_conversation_field_headers_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversational_search_service.ConverseConversationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.converse_conversation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversational_search_service.ConverseConversationResponse()) - await client.converse_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', - 'name=name_value', - ) in kw['metadata'] - - -def test_converse_conversation_flattened(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.converse_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversational_search_service.ConverseConversationResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.converse_conversation( - name='name_value', - query=conversation.TextInput(input='input_value'), - ) - - # Establish that the 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].query - mock_val = conversation.TextInput(input='input_value') - assert arg == mock_val - - -def test_converse_conversation_flattened_error(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.converse_conversation( - conversational_search_service.ConverseConversationRequest(), - name='name_value', - query=conversation.TextInput(input='input_value'), - ) - -@pytest.mark.asyncio -async def test_converse_conversation_flattened_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.converse_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversational_search_service.ConverseConversationResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversational_search_service.ConverseConversationResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.converse_conversation( - name='name_value', - query=conversation.TextInput(input='input_value'), - ) - - # Establish that 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].query - mock_val = conversation.TextInput(input='input_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_converse_conversation_flattened_error_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.converse_conversation( - conversational_search_service.ConverseConversationRequest(), - name='name_value', - query=conversation.TextInput(input='input_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - conversational_search_service.CreateConversationRequest, - dict, -]) -def test_create_conversation(request_type, transport: str = 'grpc'): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_conversation.Conversation( - name='name_value', - state=gcd_conversation.Conversation.State.IN_PROGRESS, - user_pseudo_id='user_pseudo_id_value', - ) - response = client.create_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] == conversational_search_service.CreateConversationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_conversation.Conversation) - assert response.name == 'name_value' - assert response.state == gcd_conversation.Conversation.State.IN_PROGRESS - assert response.user_pseudo_id == 'user_pseudo_id_value' - - -def test_create_conversation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_conversation), - '__call__') as call: - client.create_conversation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversational_search_service.CreateConversationRequest() - -@pytest.mark.asyncio -async def test_create_conversation_async(transport: str = 'grpc_asyncio', request_type=conversational_search_service.CreateConversationRequest): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation.Conversation( - name='name_value', - state=gcd_conversation.Conversation.State.IN_PROGRESS, - user_pseudo_id='user_pseudo_id_value', - )) - response = await client.create_conversation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == conversational_search_service.CreateConversationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_conversation.Conversation) - assert response.name == 'name_value' - assert response.state == gcd_conversation.Conversation.State.IN_PROGRESS - assert response.user_pseudo_id == 'user_pseudo_id_value' - - -@pytest.mark.asyncio -async def test_create_conversation_async_from_dict(): - await test_create_conversation_async(request_type=dict) - - -def test_create_conversation_field_headers(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversational_search_service.CreateConversationRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_conversation), - '__call__') as call: - call.return_value = gcd_conversation.Conversation() - client.create_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', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_conversation_field_headers_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversational_search_service.CreateConversationRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_conversation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation.Conversation()) - await client.create_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', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_conversation_flattened(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_conversation.Conversation() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_conversation( - parent='parent_value', - conversation=gcd_conversation.Conversation(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].conversation - mock_val = gcd_conversation.Conversation(name='name_value') - assert arg == mock_val - - -def test_create_conversation_flattened_error(): - client = ConversationalSearchServiceClient( - credentials=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_conversation( - conversational_search_service.CreateConversationRequest(), - parent='parent_value', - conversation=gcd_conversation.Conversation(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_conversation_flattened_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_conversation.Conversation() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_conversation.Conversation()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_conversation( - parent='parent_value', - conversation=gcd_conversation.Conversation(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].conversation - mock_val = gcd_conversation.Conversation(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_conversation_flattened_error_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_conversation( - conversational_search_service.CreateConversationRequest(), - parent='parent_value', - conversation=gcd_conversation.Conversation(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - conversational_search_service.DeleteConversationRequest, - dict, -]) -def test_delete_conversation(request_type, transport: str = 'grpc'): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_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] == conversational_search_service.DeleteConversationRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_conversation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_conversation), - '__call__') as call: - client.delete_conversation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversational_search_service.DeleteConversationRequest() - -@pytest.mark.asyncio -async def test_delete_conversation_async(transport: str = 'grpc_asyncio', request_type=conversational_search_service.DeleteConversationRequest): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_conversation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == conversational_search_service.DeleteConversationRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_conversation_async_from_dict(): - await test_delete_conversation_async(request_type=dict) - - -def test_delete_conversation_field_headers(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversational_search_service.DeleteConversationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_conversation), - '__call__') as call: - call.return_value = None - client.delete_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', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_conversation_field_headers_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversational_search_service.DeleteConversationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_conversation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_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', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_conversation_flattened(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, 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 = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_conversation( - 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_conversation_flattened_error(): - client = ConversationalSearchServiceClient( - credentials=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_conversation( - conversational_search_service.DeleteConversationRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_conversation_flattened_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, 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 = 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_conversation( - 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_conversation_flattened_error_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_conversation( - conversational_search_service.DeleteConversationRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - conversational_search_service.UpdateConversationRequest, - dict, -]) -def test_update_conversation(request_type, transport: str = 'grpc'): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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 = gcd_conversation.Conversation( - name='name_value', - state=gcd_conversation.Conversation.State.IN_PROGRESS, - user_pseudo_id='user_pseudo_id_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] - assert args[0] == conversational_search_service.UpdateConversationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_conversation.Conversation) - assert response.name == 'name_value' - assert response.state == gcd_conversation.Conversation.State.IN_PROGRESS - assert response.user_pseudo_id == 'user_pseudo_id_value' - - -def test_update_conversation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_conversation), - '__call__') as call: - client.update_conversation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversational_search_service.UpdateConversationRequest() - -@pytest.mark.asyncio -async def test_update_conversation_async(transport: str = 'grpc_asyncio', request_type=conversational_search_service.UpdateConversationRequest): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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(gcd_conversation.Conversation( - name='name_value', - state=gcd_conversation.Conversation.State.IN_PROGRESS, - user_pseudo_id='user_pseudo_id_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] - assert args[0] == conversational_search_service.UpdateConversationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_conversation.Conversation) - assert response.name == 'name_value' - assert response.state == gcd_conversation.Conversation.State.IN_PROGRESS - assert response.user_pseudo_id == 'user_pseudo_id_value' - - -@pytest.mark.asyncio -async def test_update_conversation_async_from_dict(): - await test_update_conversation_async(request_type=dict) - - -def test_update_conversation_field_headers(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversational_search_service.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 = gcd_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 = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversational_search_service.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(gcd_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 = ConversationalSearchServiceClient( - 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 = gcd_conversation.Conversation() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_conversation( - conversation=gcd_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 = gcd_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 = ConversationalSearchServiceClient( - credentials=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( - conversational_search_service.UpdateConversationRequest(), - conversation=gcd_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 = ConversationalSearchServiceAsyncClient( - 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 = gcd_conversation.Conversation() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_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=gcd_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 = gcd_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 = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_conversation( - conversational_search_service.UpdateConversationRequest(), - conversation=gcd_conversation.Conversation(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - conversational_search_service.GetConversationRequest, - dict, -]) -def test_get_conversation(request_type, transport: str = 'grpc'): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation.Conversation( - name='name_value', - state=conversation.Conversation.State.IN_PROGRESS, - user_pseudo_id='user_pseudo_id_value', - ) - response = client.get_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] == conversational_search_service.GetConversationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, conversation.Conversation) - assert response.name == 'name_value' - assert response.state == conversation.Conversation.State.IN_PROGRESS - assert response.user_pseudo_id == 'user_pseudo_id_value' - - -def test_get_conversation_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_conversation), - '__call__') as call: - client.get_conversation() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversational_search_service.GetConversationRequest() - -@pytest.mark.asyncio -async def test_get_conversation_async(transport: str = 'grpc_asyncio', request_type=conversational_search_service.GetConversationRequest): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation( - name='name_value', - state=conversation.Conversation.State.IN_PROGRESS, - user_pseudo_id='user_pseudo_id_value', - )) - response = await client.get_conversation(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == conversational_search_service.GetConversationRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, conversation.Conversation) - assert response.name == 'name_value' - assert response.state == conversation.Conversation.State.IN_PROGRESS - assert response.user_pseudo_id == 'user_pseudo_id_value' - - -@pytest.mark.asyncio -async def test_get_conversation_async_from_dict(): - await test_get_conversation_async(request_type=dict) - - -def test_get_conversation_field_headers(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversational_search_service.GetConversationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_conversation), - '__call__') as call: - call.return_value = conversation.Conversation() - client.get_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', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_conversation_field_headers_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversational_search_service.GetConversationRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_conversation), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation()) - await client.get_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', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_conversation_flattened(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation.Conversation() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_conversation( - 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_conversation_flattened_error(): - client = ConversationalSearchServiceClient( - credentials=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_conversation( - conversational_search_service.GetConversationRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_conversation_flattened_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_conversation), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversation.Conversation() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversation.Conversation()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_conversation( - 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_conversation_flattened_error_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_conversation( - conversational_search_service.GetConversationRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - conversational_search_service.ListConversationsRequest, - dict, -]) -def test_list_conversations(request_type, transport: str = 'grpc'): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_conversations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversational_search_service.ListConversationsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_conversations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == conversational_search_service.ListConversationsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConversationsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_conversations_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversations), - '__call__') as call: - client.list_conversations() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == conversational_search_service.ListConversationsRequest() - -@pytest.mark.asyncio -async def test_list_conversations_async(transport: str = 'grpc_asyncio', request_type=conversational_search_service.ListConversationsRequest): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_conversations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(conversational_search_service.ListConversationsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_conversations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == conversational_search_service.ListConversationsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConversationsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_conversations_async_from_dict(): - await test_list_conversations_async(request_type=dict) - - -def test_list_conversations_field_headers(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversational_search_service.ListConversationsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversations), - '__call__') as call: - call.return_value = conversational_search_service.ListConversationsResponse() - client.list_conversations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_conversations_field_headers_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = conversational_search_service.ListConversationsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversations), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversational_search_service.ListConversationsResponse()) - await client.list_conversations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_conversations_flattened(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversational_search_service.ListConversationsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_conversations( - 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_conversations_flattened_error(): - client = ConversationalSearchServiceClient( - credentials=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_conversations( - conversational_search_service.ListConversationsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_conversations_flattened_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversations), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = conversational_search_service.ListConversationsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(conversational_search_service.ListConversationsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_conversations( - 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_conversations_flattened_error_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_conversations( - conversational_search_service.ListConversationsRequest(), - parent='parent_value', - ) - - -def test_list_conversations_pager(transport_name: str = "grpc"): - client = ConversationalSearchServiceClient( - 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_conversations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - conversation.Conversation(), - ], - next_page_token='abc', - ), - conversational_search_service.ListConversationsResponse( - conversations=[], - next_page_token='def', - ), - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - ], - next_page_token='ghi', - ), - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_conversations(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, conversation.Conversation) - for i in results) -def test_list_conversations_pages(transport_name: str = "grpc"): - client = ConversationalSearchServiceClient( - 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_conversations), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - conversation.Conversation(), - ], - next_page_token='abc', - ), - conversational_search_service.ListConversationsResponse( - conversations=[], - next_page_token='def', - ), - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - ], - next_page_token='ghi', - ), - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - ], - ), - RuntimeError, - ) - pages = list(client.list_conversations(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_conversations_async_pager(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - conversation.Conversation(), - ], - next_page_token='abc', - ), - conversational_search_service.ListConversationsResponse( - conversations=[], - next_page_token='def', - ), - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - ], - next_page_token='ghi', - ), - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_conversations(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, conversation.Conversation) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_conversations_async_pages(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_conversations), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - conversation.Conversation(), - ], - next_page_token='abc', - ), - conversational_search_service.ListConversationsResponse( - conversations=[], - next_page_token='def', - ), - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - ], - next_page_token='ghi', - ), - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_conversations(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", [ - conversational_search_service.ConverseConversationRequest, - dict, -]) -def test_converse_conversation_rest(request_type): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/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 = conversational_search_service.ConverseConversationResponse( - related_questions=['related_questions_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 = conversational_search_service.ConverseConversationResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.converse_conversation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, conversational_search_service.ConverseConversationResponse) - assert response.related_questions == ['related_questions_value'] - - -def test_converse_conversation_rest_required_fields(request_type=conversational_search_service.ConverseConversationRequest): - transport_class = transports.ConversationalSearchServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).converse_conversation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).converse_conversation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = conversational_search_service.ConverseConversationResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = conversational_search_service.ConverseConversationResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.converse_conversation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_converse_conversation_rest_unset_required_fields(): - transport = transports.ConversationalSearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.converse_conversation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "query", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_converse_conversation_rest_interceptors(null_interceptor): - transport = transports.ConversationalSearchServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationalSearchServiceRestInterceptor(), - ) - client = ConversationalSearchServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "post_converse_conversation") as post, \ - mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "pre_converse_conversation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversational_search_service.ConverseConversationRequest.pb(conversational_search_service.ConverseConversationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = conversational_search_service.ConverseConversationResponse.to_json(conversational_search_service.ConverseConversationResponse()) - - request = conversational_search_service.ConverseConversationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = conversational_search_service.ConverseConversationResponse() - - client.converse_conversation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_converse_conversation_rest_bad_request(transport: str = 'rest', request_type=conversational_search_service.ConverseConversationRequest): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.converse_conversation(request) - - -def test_converse_conversation_rest_flattened(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversational_search_service.ConverseConversationResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - query=conversation.TextInput(input='input_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 = conversational_search_service.ConverseConversationResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.converse_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/{name=projects/*/locations/*/dataStores/*/conversations/*}:converse" % client.transport._host, args[1]) - - -def test_converse_conversation_rest_flattened_error(transport: str = 'rest'): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.converse_conversation( - conversational_search_service.ConverseConversationRequest(), - name='name_value', - query=conversation.TextInput(input='input_value'), - ) - - -def test_converse_conversation_rest_error(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - conversational_search_service.CreateConversationRequest, - dict, -]) -def test_create_conversation_rest(request_type): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - request_init["conversation"] = {'name': 'name_value', 'state': 1, 'user_pseudo_id': 'user_pseudo_id_value', 'messages': [{'user_input': {'input': 'input_value', 'context': {'context_documents': ['context_documents_value1', 'context_documents_value2'], 'active_document': 'active_document_value'}}, 'reply': {'reply': 'reply_value', 'references': [{'uri': 'uri_value', 'anchor_text': 'anchor_text_value', 'start': 558, 'end': 311}], 'summary': {'summary_text': 'summary_text_value', 'summary_skipped_reasons': [1], 'safety_attributes': {'categories': ['categories_value1', 'categories_value2'], 'scores': [0.656, 0.657]}}}, 'create_time': {'seconds': 751, 'nanos': 543}}], 'start_time': {}, 'end_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 = conversational_search_service.CreateConversationRequest.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 = gcd_conversation.Conversation( - name='name_value', - state=gcd_conversation.Conversation.State.IN_PROGRESS, - user_pseudo_id='user_pseudo_id_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 = gcd_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 - response = client.create_conversation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_conversation.Conversation) - assert response.name == 'name_value' - assert response.state == gcd_conversation.Conversation.State.IN_PROGRESS - assert response.user_pseudo_id == 'user_pseudo_id_value' - - -def test_create_conversation_rest_required_fields(request_type=conversational_search_service.CreateConversationRequest): - transport_class = transports.ConversationalSearchServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_conversation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_conversation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_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': "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 = gcd_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 - - response = client.create_conversation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_conversation_rest_unset_required_fields(): - transport = transports.ConversationalSearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_conversation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "conversation", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_conversation_rest_interceptors(null_interceptor): - transport = transports.ConversationalSearchServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationalSearchServiceRestInterceptor(), - ) - client = ConversationalSearchServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "post_create_conversation") as post, \ - mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "pre_create_conversation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversational_search_service.CreateConversationRequest.pb(conversational_search_service.CreateConversationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_conversation.Conversation.to_json(gcd_conversation.Conversation()) - - request = conversational_search_service.CreateConversationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_conversation.Conversation() - - client.create_conversation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_conversation_rest_bad_request(transport: str = 'rest', request_type=conversational_search_service.CreateConversationRequest): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_conversation(request) - - -def test_create_conversation_rest_flattened(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_conversation.Conversation() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - conversation=gcd_conversation.Conversation(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 = gcd_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 - - client.create_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/{parent=projects/*/locations/*/dataStores/*}/conversations" % client.transport._host, args[1]) - - -def test_create_conversation_rest_flattened_error(transport: str = 'rest'): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.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_conversation( - conversational_search_service.CreateConversationRequest(), - parent='parent_value', - conversation=gcd_conversation.Conversation(name='name_value'), - ) - - -def test_create_conversation_rest_error(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - conversational_search_service.DeleteConversationRequest, - dict, -]) -def test_delete_conversation_rest(request_type): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/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 = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_conversation(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_conversation_rest_required_fields(request_type=conversational_search_service.DeleteConversationRequest): - transport_class = transports.ConversationalSearchServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_conversation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_conversation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ConversationalSearchServiceClient( - 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 - - response = client.delete_conversation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_conversation_rest_unset_required_fields(): - transport = transports.ConversationalSearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_conversation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_conversation_rest_interceptors(null_interceptor): - transport = transports.ConversationalSearchServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationalSearchServiceRestInterceptor(), - ) - client = ConversationalSearchServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "pre_delete_conversation") as pre: - pre.assert_not_called() - pb_message = conversational_search_service.DeleteConversationRequest.pb(conversational_search_service.DeleteConversationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = conversational_search_service.DeleteConversationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_conversation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_conversation_rest_bad_request(transport: str = 'rest', request_type=conversational_search_service.DeleteConversationRequest): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_conversation(request) - - -def test_delete_conversation_rest_flattened(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/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 = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_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/{name=projects/*/locations/*/dataStores/*/conversations/*}" % client.transport._host, args[1]) - - -def test_delete_conversation_rest_flattened_error(transport: str = 'rest'): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.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_conversation( - conversational_search_service.DeleteConversationRequest(), - name='name_value', - ) - - -def test_delete_conversation_rest_error(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - conversational_search_service.UpdateConversationRequest, - dict, -]) -def test_update_conversation_rest(request_type): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'conversation': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'}} - request_init["conversation"] = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4', 'state': 1, 'user_pseudo_id': 'user_pseudo_id_value', 'messages': [{'user_input': {'input': 'input_value', 'context': {'context_documents': ['context_documents_value1', 'context_documents_value2'], 'active_document': 'active_document_value'}}, 'reply': {'reply': 'reply_value', 'references': [{'uri': 'uri_value', 'anchor_text': 'anchor_text_value', 'start': 558, 'end': 311}], 'summary': {'summary_text': 'summary_text_value', 'summary_skipped_reasons': [1], 'safety_attributes': {'categories': ['categories_value1', 'categories_value2'], 'scores': [0.656, 0.657]}}}, 'create_time': {'seconds': 751, 'nanos': 543}}], 'start_time': {}, 'end_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 = conversational_search_service.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 = gcd_conversation.Conversation( - name='name_value', - state=gcd_conversation.Conversation.State.IN_PROGRESS, - user_pseudo_id='user_pseudo_id_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 = gcd_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 - response = client.update_conversation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_conversation.Conversation) - assert response.name == 'name_value' - assert response.state == gcd_conversation.Conversation.State.IN_PROGRESS - assert response.user_pseudo_id == 'user_pseudo_id_value' - - -def test_update_conversation_rest_required_fields(request_type=conversational_search_service.UpdateConversationRequest): - transport_class = transports.ConversationalSearchServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_conversation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_conversation._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_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 = gcd_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 - - response = client.update_conversation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_conversation_rest_unset_required_fields(): - transport = transports.ConversationalSearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_conversation._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("conversation", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_conversation_rest_interceptors(null_interceptor): - transport = transports.ConversationalSearchServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationalSearchServiceRestInterceptor(), - ) - client = ConversationalSearchServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "post_update_conversation") as post, \ - mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "pre_update_conversation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversational_search_service.UpdateConversationRequest.pb(conversational_search_service.UpdateConversationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_conversation.Conversation.to_json(gcd_conversation.Conversation()) - - request = conversational_search_service.UpdateConversationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_conversation.Conversation() - - client.update_conversation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_conversation_rest_bad_request(transport: str = 'rest', request_type=conversational_search_service.UpdateConversationRequest): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'conversation': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_conversation(request) - - -def test_update_conversation_rest_flattened(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_conversation.Conversation() - - # get arguments that satisfy an http rule for this method - sample_request = {'conversation': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'}} - - # get truthy value for each flattened field - mock_args = dict( - conversation=gcd_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 = gcd_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 - - 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/*/dataStores/*/conversations/*}" % client.transport._host, args[1]) - - -def test_update_conversation_rest_flattened_error(transport: str = 'rest'): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.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( - conversational_search_service.UpdateConversationRequest(), - conversation=gcd_conversation.Conversation(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_conversation_rest_error(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - conversational_search_service.GetConversationRequest, - dict, -]) -def test_get_conversation_rest(request_type): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/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 = conversation.Conversation( - name='name_value', - state=conversation.Conversation.State.IN_PROGRESS, - user_pseudo_id='user_pseudo_id_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 = 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 - response = client.get_conversation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, conversation.Conversation) - assert response.name == 'name_value' - assert response.state == conversation.Conversation.State.IN_PROGRESS - assert response.user_pseudo_id == 'user_pseudo_id_value' - - -def test_get_conversation_rest_required_fields(request_type=conversational_search_service.GetConversationRequest): - transport_class = transports.ConversationalSearchServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_conversation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_conversation._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = 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': "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 = 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 - - response = client.get_conversation(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_conversation_rest_unset_required_fields(): - transport = transports.ConversationalSearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_conversation._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_conversation_rest_interceptors(null_interceptor): - transport = transports.ConversationalSearchServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationalSearchServiceRestInterceptor(), - ) - client = ConversationalSearchServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "post_get_conversation") as post, \ - mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "pre_get_conversation") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversational_search_service.GetConversationRequest.pb(conversational_search_service.GetConversationRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = conversation.Conversation.to_json(conversation.Conversation()) - - request = conversational_search_service.GetConversationRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = conversation.Conversation() - - client.get_conversation(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_conversation_rest_bad_request(transport: str = 'rest', request_type=conversational_search_service.GetConversationRequest): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_conversation(request) - - -def test_get_conversation_rest_flattened(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversation.Conversation() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/conversations/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 = 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 - - client.get_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/{name=projects/*/locations/*/dataStores/*/conversations/*}" % client.transport._host, args[1]) - - -def test_get_conversation_rest_flattened_error(transport: str = 'rest'): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.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_conversation( - conversational_search_service.GetConversationRequest(), - name='name_value', - ) - - -def test_get_conversation_rest_error(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - conversational_search_service.ListConversationsRequest, - dict, -]) -def test_list_conversations_rest(request_type): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/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 = conversational_search_service.ListConversationsResponse( - next_page_token='next_page_token_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 = conversational_search_service.ListConversationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_conversations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConversationsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_conversations_rest_required_fields(request_type=conversational_search_service.ListConversationsRequest): - transport_class = transports.ConversationalSearchServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_conversations._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_conversations._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = conversational_search_service.ListConversationsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = conversational_search_service.ListConversationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_conversations(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_conversations_rest_unset_required_fields(): - transport = transports.ConversationalSearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_conversations._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_conversations_rest_interceptors(null_interceptor): - transport = transports.ConversationalSearchServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConversationalSearchServiceRestInterceptor(), - ) - client = ConversationalSearchServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "post_list_conversations") as post, \ - mock.patch.object(transports.ConversationalSearchServiceRestInterceptor, "pre_list_conversations") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = conversational_search_service.ListConversationsRequest.pb(conversational_search_service.ListConversationsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = conversational_search_service.ListConversationsResponse.to_json(conversational_search_service.ListConversationsResponse()) - - request = conversational_search_service.ListConversationsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = conversational_search_service.ListConversationsResponse() - - client.list_conversations(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_conversations_rest_bad_request(transport: str = 'rest', request_type=conversational_search_service.ListConversationsRequest): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_conversations(request) - - -def test_list_conversations_rest_flattened(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = conversational_search_service.ListConversationsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/dataStores/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 = conversational_search_service.ListConversationsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_conversations(**mock_args) - - # Establish that the underlying call 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/*/dataStores/*}/conversations" % client.transport._host, args[1]) - - -def test_list_conversations_rest_flattened_error(transport: str = 'rest'): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.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_conversations( - conversational_search_service.ListConversationsRequest(), - parent='parent_value', - ) - - -def test_list_conversations_rest_pager(transport: str = 'rest'): - client = ConversationalSearchServiceClient( - 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 = ( - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - conversation.Conversation(), - ], - next_page_token='abc', - ), - conversational_search_service.ListConversationsResponse( - conversations=[], - next_page_token='def', - ), - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - ], - next_page_token='ghi', - ), - conversational_search_service.ListConversationsResponse( - conversations=[ - conversation.Conversation(), - conversation.Conversation(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(conversational_search_service.ListConversationsResponse.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/dataStores/sample3'} - - pager = client.list_conversations(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, conversation.Conversation) - for i in results) - - pages = list(client.list_conversations(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.ConversationalSearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ConversationalSearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ConversationalSearchServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ConversationalSearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ConversationalSearchServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ConversationalSearchServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ConversationalSearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ConversationalSearchServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ConversationalSearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ConversationalSearchServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ConversationalSearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ConversationalSearchServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ConversationalSearchServiceGrpcTransport, - transports.ConversationalSearchServiceGrpcAsyncIOTransport, - transports.ConversationalSearchServiceRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = ConversationalSearchServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ConversationalSearchServiceGrpcTransport, - ) - -def test_conversational_search_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ConversationalSearchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_conversational_search_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.discoveryengine_v1beta.services.conversational_search_service.transports.ConversationalSearchServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ConversationalSearchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'converse_conversation', - 'create_conversation', - 'delete_conversation', - 'update_conversation', - 'get_conversation', - 'list_conversations', - 'get_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_conversational_search_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.discoveryengine_v1beta.services.conversational_search_service.transports.ConversationalSearchServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ConversationalSearchServiceTransport( - 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_conversational_search_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.discoveryengine_v1beta.services.conversational_search_service.transports.ConversationalSearchServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ConversationalSearchServiceTransport() - adc.assert_called_once() - - -def test_conversational_search_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) - ConversationalSearchServiceClient() - 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.ConversationalSearchServiceGrpcTransport, - transports.ConversationalSearchServiceGrpcAsyncIOTransport, - ], -) -def test_conversational_search_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.ConversationalSearchServiceGrpcTransport, - transports.ConversationalSearchServiceGrpcAsyncIOTransport, - transports.ConversationalSearchServiceRestTransport, - ], -) -def test_conversational_search_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.ConversationalSearchServiceGrpcTransport, grpc_helpers), - (transports.ConversationalSearchServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_conversational_search_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ConversationalSearchServiceGrpcTransport, transports.ConversationalSearchServiceGrpcAsyncIOTransport]) -def test_conversational_search_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_conversational_search_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.ConversationalSearchServiceRestTransport ( - 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_conversational_search_service_host_no_port(transport_name): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_conversational_search_service_host_with_port(transport_name): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_conversational_search_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = ConversationalSearchServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = ConversationalSearchServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.converse_conversation._session - session2 = client2.transport.converse_conversation._session - assert session1 != session2 - session1 = client1.transport.create_conversation._session - session2 = client2.transport.create_conversation._session - assert session1 != session2 - 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 - session1 = client1.transport.list_conversations._session - session2 = client2.transport.list_conversations._session - assert session1 != session2 -def test_conversational_search_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ConversationalSearchServiceGrpcTransport( - 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_conversational_search_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ConversationalSearchServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.ConversationalSearchServiceGrpcTransport, transports.ConversationalSearchServiceGrpcAsyncIOTransport]) -def test_conversational_search_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.ConversationalSearchServiceGrpcTransport, transports.ConversationalSearchServiceGrpcAsyncIOTransport]) -def test_conversational_search_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_conversation_path(): - project = "squid" - location = "clam" - data_store = "whelk" - conversation = "octopus" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}/conversations/{conversation}".format(project=project, location=location, data_store=data_store, conversation=conversation, ) - actual = ConversationalSearchServiceClient.conversation_path(project, location, data_store, conversation) - assert expected == actual - - -def test_parse_conversation_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "data_store": "cuttlefish", - "conversation": "mussel", - } - path = ConversationalSearchServiceClient.conversation_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationalSearchServiceClient.parse_conversation_path(path) - assert expected == actual - -def test_data_store_path(): - project = "winkle" - location = "nautilus" - data_store = "scallop" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) - actual = ConversationalSearchServiceClient.data_store_path(project, location, data_store) - assert expected == actual - - -def test_parse_data_store_path(): - expected = { - "project": "abalone", - "location": "squid", - "data_store": "clam", - } - path = ConversationalSearchServiceClient.data_store_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationalSearchServiceClient.parse_data_store_path(path) - assert expected == actual - -def test_document_path(): - project = "whelk" - location = "octopus" - data_store = "oyster" - branch = "nudibranch" - document = "cuttlefish" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) - actual = ConversationalSearchServiceClient.document_path(project, location, data_store, branch, document) - assert expected == actual - - -def test_parse_document_path(): - expected = { - "project": "mussel", - "location": "winkle", - "data_store": "nautilus", - "branch": "scallop", - "document": "abalone", - } - path = ConversationalSearchServiceClient.document_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationalSearchServiceClient.parse_document_path(path) - assert expected == actual - -def test_serving_config_path(): - project = "squid" - location = "clam" - data_store = "whelk" - serving_config = "octopus" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}/servingConfigs/{serving_config}".format(project=project, location=location, data_store=data_store, serving_config=serving_config, ) - actual = ConversationalSearchServiceClient.serving_config_path(project, location, data_store, serving_config) - assert expected == actual - - -def test_parse_serving_config_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "data_store": "cuttlefish", - "serving_config": "mussel", - } - path = ConversationalSearchServiceClient.serving_config_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationalSearchServiceClient.parse_serving_config_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ConversationalSearchServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nautilus", - } - path = ConversationalSearchServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationalSearchServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "scallop" - expected = "folders/{folder}".format(folder=folder, ) - actual = ConversationalSearchServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "abalone", - } - path = ConversationalSearchServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationalSearchServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "squid" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ConversationalSearchServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "clam", - } - path = ConversationalSearchServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationalSearchServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "whelk" - expected = "projects/{project}".format(project=project, ) - actual = ConversationalSearchServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "octopus", - } - path = ConversationalSearchServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationalSearchServiceClient.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 = ConversationalSearchServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - } - path = ConversationalSearchServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ConversationalSearchServiceClient.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.ConversationalSearchServiceTransport, '_prep_wrapped_messages') as prep: - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ConversationalSearchServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = ConversationalSearchServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_get_operation(transport: str = "grpc"): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = ConversationalSearchServiceClient( - 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 = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = ConversationalSearchServiceClient( - 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 = ConversationalSearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ConversationalSearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = ConversationalSearchServiceClient( - 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", [ - (ConversationalSearchServiceClient, transports.ConversationalSearchServiceGrpcTransport), - (ConversationalSearchServiceAsyncClient, transports.ConversationalSearchServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_document_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_document_service.py deleted file mode 100644 index 69f92669c32a..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_document_service.py +++ /dev/null @@ -1,4999 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.discoveryengine_v1beta.services.document_service import DocumentServiceAsyncClient -from google.cloud.discoveryengine_v1beta.services.document_service import DocumentServiceClient -from google.cloud.discoveryengine_v1beta.services.document_service import pagers -from google.cloud.discoveryengine_v1beta.services.document_service import transports -from google.cloud.discoveryengine_v1beta.types import document -from google.cloud.discoveryengine_v1beta.types import document as gcd_document -from google.cloud.discoveryengine_v1beta.types import document_service -from google.cloud.discoveryengine_v1beta.types import import_config -from google.cloud.discoveryengine_v1beta.types import purge_config -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import struct_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert DocumentServiceClient._get_default_mtls_endpoint(None) is None - assert DocumentServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert DocumentServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert DocumentServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert DocumentServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert DocumentServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (DocumentServiceClient, "grpc"), - (DocumentServiceAsyncClient, "grpc_asyncio"), - (DocumentServiceClient, "rest"), -]) -def test_document_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.DocumentServiceGrpcTransport, "grpc"), - (transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.DocumentServiceRestTransport, "rest"), -]) -def test_document_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", [ - (DocumentServiceClient, "grpc"), - (DocumentServiceAsyncClient, "grpc_asyncio"), - (DocumentServiceClient, "rest"), -]) -def test_document_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -def test_document_service_client_get_transport_class(): - transport = DocumentServiceClient.get_transport_class() - available_transports = [ - transports.DocumentServiceGrpcTransport, - transports.DocumentServiceRestTransport, - ] - assert transport in available_transports - - transport = DocumentServiceClient.get_transport_class("grpc") - assert transport == transports.DocumentServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc"), - (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (DocumentServiceClient, transports.DocumentServiceRestTransport, "rest"), -]) -@mock.patch.object(DocumentServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceClient)) -@mock.patch.object(DocumentServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceAsyncClient)) -def test_document_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(DocumentServiceClient, '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(DocumentServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc", "true"), - (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc", "false"), - (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (DocumentServiceClient, transports.DocumentServiceRestTransport, "rest", "true"), - (DocumentServiceClient, transports.DocumentServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(DocumentServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceClient)) -@mock.patch.object(DocumentServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_document_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 - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - DocumentServiceClient, DocumentServiceAsyncClient -]) -@mock.patch.object(DocumentServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceClient)) -@mock.patch.object(DocumentServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DocumentServiceAsyncClient)) -def test_document_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc"), - (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (DocumentServiceClient, transports.DocumentServiceRestTransport, "rest"), -]) -def test_document_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, - 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", [ - (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc", grpc_helpers), - (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (DocumentServiceClient, transports.DocumentServiceRestTransport, "rest", None), -]) -def test_document_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, - scopes=None, - client_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_document_service_client_client_options_from_dict(): - with mock.patch('google.cloud.discoveryengine_v1beta.services.document_service.transports.DocumentServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = DocumentServiceClient( - 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", [ - (DocumentServiceClient, transports.DocumentServiceGrpcTransport, "grpc", grpc_helpers), - (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_document_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, - scopes=None, - client_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - document_service.GetDocumentRequest, - dict, -]) -def test_get_document(request_type, transport: str = 'grpc'): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document.Document( - name='name_value', - id='id_value', - schema_id='schema_id_value', - parent_document_id='parent_document_id_value', - json_data='json_data_value', - ) - response = client.get_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.GetDocumentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, document.Document) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.schema_id == 'schema_id_value' - assert response.parent_document_id == 'parent_document_id_value' - - -def test_get_document_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_document), - '__call__') as call: - client.get_document() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.GetDocumentRequest() - -@pytest.mark.asyncio -async def test_get_document_async(transport: str = 'grpc_asyncio', request_type=document_service.GetDocumentRequest): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document.Document( - name='name_value', - id='id_value', - schema_id='schema_id_value', - parent_document_id='parent_document_id_value', - )) - response = await client.get_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.GetDocumentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, document.Document) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.schema_id == 'schema_id_value' - assert response.parent_document_id == 'parent_document_id_value' - - -@pytest.mark.asyncio -async def test_get_document_async_from_dict(): - await test_get_document_async(request_type=dict) - - -def test_get_document_field_headers(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.GetDocumentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_document), - '__call__') as call: - call.return_value = document.Document() - client.get_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_document_field_headers_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.GetDocumentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_document), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.Document()) - await client.get_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_document_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document.Document() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_document( - 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_document_flattened_error(): - client = DocumentServiceClient( - credentials=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_document( - document_service.GetDocumentRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_document_flattened_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document.Document() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.Document()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_document( - 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_document_flattened_error_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_document( - document_service.GetDocumentRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_service.ListDocumentsRequest, - dict, -]) -def test_list_documents(request_type, transport: str = 'grpc'): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_documents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_service.ListDocumentsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_documents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.ListDocumentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDocumentsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_documents_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_documents), - '__call__') as call: - client.list_documents() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.ListDocumentsRequest() - -@pytest.mark.asyncio -async def test_list_documents_async(transport: str = 'grpc_asyncio', request_type=document_service.ListDocumentsRequest): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_documents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document_service.ListDocumentsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_documents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.ListDocumentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDocumentsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_documents_async_from_dict(): - await test_list_documents_async(request_type=dict) - - -def test_list_documents_field_headers(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.ListDocumentsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_documents), - '__call__') as call: - call.return_value = document_service.ListDocumentsResponse() - client.list_documents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_documents_field_headers_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.ListDocumentsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_documents), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_service.ListDocumentsResponse()) - await client.list_documents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_documents_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_documents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_service.ListDocumentsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_documents( - 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_documents_flattened_error(): - client = DocumentServiceClient( - credentials=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_documents( - document_service.ListDocumentsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_documents_flattened_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_documents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document_service.ListDocumentsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document_service.ListDocumentsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_documents( - 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_documents_flattened_error_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_documents( - document_service.ListDocumentsRequest(), - parent='parent_value', - ) - - -def test_list_documents_pager(transport_name: str = "grpc"): - client = DocumentServiceClient( - 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_documents), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - document.Document(), - ], - next_page_token='abc', - ), - document_service.ListDocumentsResponse( - documents=[], - next_page_token='def', - ), - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - ], - next_page_token='ghi', - ), - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_documents(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, document.Document) - for i in results) -def test_list_documents_pages(transport_name: str = "grpc"): - client = DocumentServiceClient( - 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_documents), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - document.Document(), - ], - next_page_token='abc', - ), - document_service.ListDocumentsResponse( - documents=[], - next_page_token='def', - ), - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - ], - next_page_token='ghi', - ), - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - ], - ), - RuntimeError, - ) - pages = list(client.list_documents(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_documents_async_pager(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_documents), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - document.Document(), - ], - next_page_token='abc', - ), - document_service.ListDocumentsResponse( - documents=[], - next_page_token='def', - ), - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - ], - next_page_token='ghi', - ), - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_documents(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, document.Document) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_documents_async_pages(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_documents), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - document.Document(), - ], - next_page_token='abc', - ), - document_service.ListDocumentsResponse( - documents=[], - next_page_token='def', - ), - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - ], - next_page_token='ghi', - ), - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_documents(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", [ - document_service.CreateDocumentRequest, - dict, -]) -def test_create_document(request_type, transport: str = 'grpc'): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_document.Document( - name='name_value', - id='id_value', - schema_id='schema_id_value', - parent_document_id='parent_document_id_value', - json_data='json_data_value', - ) - response = client.create_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.CreateDocumentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_document.Document) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.schema_id == 'schema_id_value' - assert response.parent_document_id == 'parent_document_id_value' - - -def test_create_document_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_document), - '__call__') as call: - client.create_document() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.CreateDocumentRequest() - -@pytest.mark.asyncio -async def test_create_document_async(transport: str = 'grpc_asyncio', request_type=document_service.CreateDocumentRequest): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_document.Document( - name='name_value', - id='id_value', - schema_id='schema_id_value', - parent_document_id='parent_document_id_value', - )) - response = await client.create_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.CreateDocumentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_document.Document) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.schema_id == 'schema_id_value' - assert response.parent_document_id == 'parent_document_id_value' - - -@pytest.mark.asyncio -async def test_create_document_async_from_dict(): - await test_create_document_async(request_type=dict) - - -def test_create_document_field_headers(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.CreateDocumentRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_document), - '__call__') as call: - call.return_value = gcd_document.Document() - client.create_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_document_field_headers_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.CreateDocumentRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_document), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_document.Document()) - await client.create_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_document_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_document.Document() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_document( - parent='parent_value', - document=gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), - document_id='document_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].document - mock_val = gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})) - assert arg == mock_val - arg = args[0].document_id - mock_val = 'document_id_value' - assert arg == mock_val - - -def test_create_document_flattened_error(): - client = DocumentServiceClient( - credentials=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_document( - document_service.CreateDocumentRequest(), - parent='parent_value', - document=gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), - document_id='document_id_value', - ) - -@pytest.mark.asyncio -async def test_create_document_flattened_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = gcd_document.Document() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_document.Document()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_document( - parent='parent_value', - document=gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), - document_id='document_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].document - mock_val = gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})) - assert arg == mock_val - arg = args[0].document_id - mock_val = 'document_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_document_flattened_error_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_document( - document_service.CreateDocumentRequest(), - parent='parent_value', - document=gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), - document_id='document_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - document_service.UpdateDocumentRequest, - dict, -]) -def test_update_document(request_type, transport: str = 'grpc'): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = document.Document( - name='name_value', - id='id_value', - schema_id='schema_id_value', - parent_document_id='parent_document_id_value', - json_data='json_data_value', - ) - response = client.update_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.UpdateDocumentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, document.Document) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.schema_id == 'schema_id_value' - assert response.parent_document_id == 'parent_document_id_value' - - -def test_update_document_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_document), - '__call__') as call: - client.update_document() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.UpdateDocumentRequest() - -@pytest.mark.asyncio -async def test_update_document_async(transport: str = 'grpc_asyncio', request_type=document_service.UpdateDocumentRequest): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(document.Document( - name='name_value', - id='id_value', - schema_id='schema_id_value', - parent_document_id='parent_document_id_value', - )) - response = await client.update_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.UpdateDocumentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, document.Document) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.schema_id == 'schema_id_value' - assert response.parent_document_id == 'parent_document_id_value' - - -@pytest.mark.asyncio -async def test_update_document_async_from_dict(): - await test_update_document_async(request_type=dict) - - -def test_update_document_field_headers(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.UpdateDocumentRequest() - - request.document.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_document), - '__call__') as call: - call.return_value = document.Document() - client.update_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'document.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_document_field_headers_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.UpdateDocumentRequest() - - request.document.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_document), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(document.Document()) - await client.update_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'document.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - document_service.DeleteDocumentRequest, - dict, -]) -def test_delete_document(request_type, transport: str = 'grpc'): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.DeleteDocumentRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_document_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_document), - '__call__') as call: - client.delete_document() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.DeleteDocumentRequest() - -@pytest.mark.asyncio -async def test_delete_document_async(transport: str = 'grpc_asyncio', request_type=document_service.DeleteDocumentRequest): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_document), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == document_service.DeleteDocumentRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_document_async_from_dict(): - await test_delete_document_async(request_type=dict) - - -def test_delete_document_field_headers(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.DeleteDocumentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_document), - '__call__') as call: - call.return_value = None - client.delete_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_document_field_headers_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = document_service.DeleteDocumentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_document), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_document(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_document_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_document), - '__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_document( - 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_document_flattened_error(): - client = DocumentServiceClient( - credentials=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_document( - document_service.DeleteDocumentRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_document_flattened_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_document), - '__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_document( - 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_document_flattened_error_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_document( - document_service.DeleteDocumentRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportDocumentsRequest, - dict, -]) -def test_import_documents(request_type, transport: str = 'grpc'): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_documents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_documents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportDocumentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_documents_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_documents), - '__call__') as call: - client.import_documents() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportDocumentsRequest() - -@pytest.mark.asyncio -async def test_import_documents_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportDocumentsRequest): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_documents), - '__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_documents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportDocumentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_documents_async_from_dict(): - await test_import_documents_async(request_type=dict) - - -def test_import_documents_field_headers(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportDocumentsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_documents), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_documents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_import_documents_field_headers_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportDocumentsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_documents), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_documents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - purge_config.PurgeDocumentsRequest, - dict, -]) -def test_purge_documents(request_type, transport: str = 'grpc'): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_documents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.purge_documents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeDocumentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_purge_documents_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_documents), - '__call__') as call: - client.purge_documents() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeDocumentsRequest() - -@pytest.mark.asyncio -async def test_purge_documents_async(transport: str = 'grpc_asyncio', request_type=purge_config.PurgeDocumentsRequest): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_documents), - '__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.purge_documents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == purge_config.PurgeDocumentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_purge_documents_async_from_dict(): - await test_purge_documents_async(request_type=dict) - - -def test_purge_documents_field_headers(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = purge_config.PurgeDocumentsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_documents), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.purge_documents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_purge_documents_field_headers_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = purge_config.PurgeDocumentsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.purge_documents), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.purge_documents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - document_service.GetDocumentRequest, - dict, -]) -def test_get_document_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document.Document( - name='name_value', - id='id_value', - schema_id='schema_id_value', - parent_document_id='parent_document_id_value', - json_data='json_data_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 = document.Document.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_document(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, document.Document) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.schema_id == 'schema_id_value' - assert response.parent_document_id == 'parent_document_id_value' - - -def test_get_document_rest_required_fields(request_type=document_service.GetDocumentRequest): - transport_class = transports.DocumentServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document.Document() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = document.Document.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_document(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_document_rest_unset_required_fields(): - transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_document._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_document_rest_interceptors(null_interceptor): - transport = transports.DocumentServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), - ) - client = DocumentServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "post_get_document") as post, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_get_document") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_service.GetDocumentRequest.pb(document_service.GetDocumentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document.Document.to_json(document.Document()) - - request = document_service.GetDocumentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document.Document() - - client.get_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_document_rest_bad_request(transport: str = 'rest', request_type=document_service.GetDocumentRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_document(request) - - -def test_get_document_rest_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document.Document() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = document.Document.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_document(**mock_args) - - # Establish that the underlying call 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/*/dataStores/*/branches/*/documents/*}" % client.transport._host, args[1]) - - -def test_get_document_rest_flattened_error(transport: str = 'rest'): - client = DocumentServiceClient( - credentials=ga_credentials.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_document( - document_service.GetDocumentRequest(), - name='name_value', - ) - - -def test_get_document_rest_error(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_service.ListDocumentsRequest, - dict, -]) -def test_list_documents_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/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 = document_service.ListDocumentsResponse( - next_page_token='next_page_token_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 = document_service.ListDocumentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_documents(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDocumentsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_documents_rest_required_fields(request_type=document_service.ListDocumentsRequest): - transport_class = transports.DocumentServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_documents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_documents._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document_service.ListDocumentsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = document_service.ListDocumentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_documents(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_documents_rest_unset_required_fields(): - transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_documents._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_documents_rest_interceptors(null_interceptor): - transport = transports.DocumentServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), - ) - client = DocumentServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "post_list_documents") as post, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_list_documents") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_service.ListDocumentsRequest.pb(document_service.ListDocumentsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document_service.ListDocumentsResponse.to_json(document_service.ListDocumentsResponse()) - - request = document_service.ListDocumentsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document_service.ListDocumentsResponse() - - client.list_documents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_documents_rest_bad_request(transport: str = 'rest', request_type=document_service.ListDocumentsRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_documents(request) - - -def test_list_documents_rest_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = document_service.ListDocumentsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = document_service.ListDocumentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_documents(**mock_args) - - # Establish that the underlying call 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/*/dataStores/*/branches/*}/documents" % client.transport._host, args[1]) - - -def test_list_documents_rest_flattened_error(transport: str = 'rest'): - client = DocumentServiceClient( - credentials=ga_credentials.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_documents( - document_service.ListDocumentsRequest(), - parent='parent_value', - ) - - -def test_list_documents_rest_pager(transport: str = 'rest'): - client = DocumentServiceClient( - 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 = ( - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - document.Document(), - ], - next_page_token='abc', - ), - document_service.ListDocumentsResponse( - documents=[], - next_page_token='def', - ), - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - ], - next_page_token='ghi', - ), - document_service.ListDocumentsResponse( - documents=[ - document.Document(), - document.Document(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(document_service.ListDocumentsResponse.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/dataStores/sample3/branches/sample4'} - - pager = client.list_documents(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, document.Document) - for i in results) - - pages = list(client.list_documents(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - document_service.CreateDocumentRequest, - dict, -]) -def test_create_document_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} - request_init["document"] = {'struct_data': {'fields': {}}, 'json_data': 'json_data_value', 'name': 'name_value', 'id': 'id_value', 'schema_id': 'schema_id_value', 'content': {'raw_bytes': b'raw_bytes_blob', 'uri': 'uri_value', 'mime_type': 'mime_type_value'}, 'parent_document_id': 'parent_document_id_value', 'derived_struct_data': {}} - # 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 = document_service.CreateDocumentRequest.meta.fields["document"] - - 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["document"].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["document"][field])): - del request_init["document"][field][i][subfield] - else: - del request_init["document"][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 = gcd_document.Document( - name='name_value', - id='id_value', - schema_id='schema_id_value', - parent_document_id='parent_document_id_value', - json_data='json_data_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 = gcd_document.Document.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_document(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, gcd_document.Document) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.schema_id == 'schema_id_value' - assert response.parent_document_id == 'parent_document_id_value' - - -def test_create_document_rest_required_fields(request_type=document_service.CreateDocumentRequest): - transport_class = transports.DocumentServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["document_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "documentId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "documentId" in jsonified_request - assert jsonified_request["documentId"] == request_init["document_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["documentId"] = 'document_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_document._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("document_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "documentId" in jsonified_request - assert jsonified_request["documentId"] == 'document_id_value' - - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = gcd_document.Document() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = gcd_document.Document.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_document(request) - - expected_params = [ - ( - "documentId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_document_rest_unset_required_fields(): - transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_document._get_unset_required_fields({}) - assert set(unset_fields) == (set(("documentId", )) & set(("parent", "document", "documentId", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_document_rest_interceptors(null_interceptor): - transport = transports.DocumentServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), - ) - client = DocumentServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "post_create_document") as post, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_create_document") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_service.CreateDocumentRequest.pb(document_service.CreateDocumentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = gcd_document.Document.to_json(gcd_document.Document()) - - request = document_service.CreateDocumentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = gcd_document.Document() - - client.create_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_document_rest_bad_request(transport: str = 'rest', request_type=document_service.CreateDocumentRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_document(request) - - -def test_create_document_rest_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = gcd_document.Document() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - document=gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), - document_id='document_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 = gcd_document.Document.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_document(**mock_args) - - # Establish that the underlying call 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/*/dataStores/*/branches/*}/documents" % client.transport._host, args[1]) - - -def test_create_document_rest_flattened_error(transport: str = 'rest'): - client = DocumentServiceClient( - credentials=ga_credentials.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_document( - document_service.CreateDocumentRequest(), - parent='parent_value', - document=gcd_document.Document(struct_data=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), - document_id='document_id_value', - ) - - -def test_create_document_rest_error(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_service.UpdateDocumentRequest, - dict, -]) -def test_update_document_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'document': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'}} - request_init["document"] = {'struct_data': {'fields': {}}, 'json_data': 'json_data_value', 'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5', 'id': 'id_value', 'schema_id': 'schema_id_value', 'content': {'raw_bytes': b'raw_bytes_blob', 'uri': 'uri_value', 'mime_type': 'mime_type_value'}, 'parent_document_id': 'parent_document_id_value', 'derived_struct_data': {}} - # 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 = document_service.UpdateDocumentRequest.meta.fields["document"] - - 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["document"].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["document"][field])): - del request_init["document"][field][i][subfield] - else: - del request_init["document"][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 = document.Document( - name='name_value', - id='id_value', - schema_id='schema_id_value', - parent_document_id='parent_document_id_value', - json_data='json_data_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 = document.Document.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_document(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, document.Document) - assert response.name == 'name_value' - assert response.id == 'id_value' - assert response.schema_id == 'schema_id_value' - assert response.parent_document_id == 'parent_document_id_value' - - -def test_update_document_rest_required_fields(request_type=document_service.UpdateDocumentRequest): - transport_class = transports.DocumentServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_document._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_missing", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = document.Document() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = document.Document.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_document(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_document_rest_unset_required_fields(): - transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_document._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowMissing", )) & set(("document", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_document_rest_interceptors(null_interceptor): - transport = transports.DocumentServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), - ) - client = DocumentServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "post_update_document") as post, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_update_document") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = document_service.UpdateDocumentRequest.pb(document_service.UpdateDocumentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = document.Document.to_json(document.Document()) - - request = document_service.UpdateDocumentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = document.Document() - - client.update_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_document_rest_bad_request(transport: str = 'rest', request_type=document_service.UpdateDocumentRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'document': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_document(request) - - -def test_update_document_rest_error(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - document_service.DeleteDocumentRequest, - dict, -]) -def test_delete_document_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_document(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_document_rest_required_fields(request_type=document_service.DeleteDocumentRequest): - transport_class = transports.DocumentServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_document._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = DocumentServiceClient( - 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 - - response = client.delete_document(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_document_rest_unset_required_fields(): - transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_document._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_document_rest_interceptors(null_interceptor): - transport = transports.DocumentServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), - ) - client = DocumentServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_delete_document") as pre: - pre.assert_not_called() - pb_message = document_service.DeleteDocumentRequest.pb(document_service.DeleteDocumentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = document_service.DeleteDocumentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_document(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_document_rest_bad_request(transport: str = 'rest', request_type=document_service.DeleteDocumentRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_document(request) - - -def test_delete_document_rest_flattened(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and 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': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4/documents/sample5'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_document(**mock_args) - - # Establish that the underlying call 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/*/dataStores/*/branches/*/documents/*}" % client.transport._host, args[1]) - - -def test_delete_document_rest_flattened_error(transport: str = 'rest'): - client = DocumentServiceClient( - credentials=ga_credentials.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_document( - document_service.DeleteDocumentRequest(), - name='name_value', - ) - - -def test_delete_document_rest_error(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportDocumentsRequest, - dict, -]) -def test_import_documents_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.import_documents(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_import_documents_rest_required_fields(request_type=import_config.ImportDocumentsRequest): - transport_class = transports.DocumentServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_documents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_documents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.import_documents(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_import_documents_rest_unset_required_fields(): - transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.import_documents._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_import_documents_rest_interceptors(null_interceptor): - transport = transports.DocumentServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), - ) - client = DocumentServiceClient(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.DocumentServiceRestInterceptor, "post_import_documents") as post, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_import_documents") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = import_config.ImportDocumentsRequest.pb(import_config.ImportDocumentsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = import_config.ImportDocumentsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.import_documents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_import_documents_rest_bad_request(transport: str = 'rest', request_type=import_config.ImportDocumentsRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.import_documents(request) - - -def test_import_documents_rest_error(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - purge_config.PurgeDocumentsRequest, - dict, -]) -def test_purge_documents_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.purge_documents(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_purge_documents_rest_required_fields(request_type=purge_config.PurgeDocumentsRequest): - transport_class = transports.DocumentServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["filter"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).purge_documents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - jsonified_request["filter"] = 'filter_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).purge_documents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "filter" in jsonified_request - assert jsonified_request["filter"] == 'filter_value' - - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.purge_documents(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_purge_documents_rest_unset_required_fields(): - transport = transports.DocumentServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.purge_documents._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "filter", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_purge_documents_rest_interceptors(null_interceptor): - transport = transports.DocumentServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DocumentServiceRestInterceptor(), - ) - client = DocumentServiceClient(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.DocumentServiceRestInterceptor, "post_purge_documents") as post, \ - mock.patch.object(transports.DocumentServiceRestInterceptor, "pre_purge_documents") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = purge_config.PurgeDocumentsRequest.pb(purge_config.PurgeDocumentsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = purge_config.PurgeDocumentsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.purge_documents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_purge_documents_rest_bad_request(transport: str = 'rest', request_type=purge_config.PurgeDocumentsRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3/branches/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.purge_documents(request) - - -def test_purge_documents_rest_error(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.DocumentServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.DocumentServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DocumentServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.DocumentServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = DocumentServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = DocumentServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.DocumentServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DocumentServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.DocumentServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = DocumentServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.DocumentServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.DocumentServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.DocumentServiceGrpcTransport, - transports.DocumentServiceGrpcAsyncIOTransport, - transports.DocumentServiceRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = DocumentServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.DocumentServiceGrpcTransport, - ) - -def test_document_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.DocumentServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_document_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.discoveryengine_v1beta.services.document_service.transports.DocumentServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.DocumentServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_document', - 'list_documents', - 'create_document', - 'update_document', - 'delete_document', - 'import_documents', - 'purge_documents', - 'get_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_document_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.discoveryengine_v1beta.services.document_service.transports.DocumentServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DocumentServiceTransport( - 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_document_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.discoveryengine_v1beta.services.document_service.transports.DocumentServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.DocumentServiceTransport() - adc.assert_called_once() - - -def test_document_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) - DocumentServiceClient() - 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.DocumentServiceGrpcTransport, - transports.DocumentServiceGrpcAsyncIOTransport, - ], -) -def test_document_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.DocumentServiceGrpcTransport, - transports.DocumentServiceGrpcAsyncIOTransport, - transports.DocumentServiceRestTransport, - ], -) -def test_document_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.DocumentServiceGrpcTransport, grpc_helpers), - (transports.DocumentServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_document_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.DocumentServiceGrpcTransport, transports.DocumentServiceGrpcAsyncIOTransport]) -def test_document_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_document_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.DocumentServiceRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_document_service_rest_lro_client(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_document_service_host_no_port(transport_name): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_document_service_host_with_port(transport_name): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_document_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = DocumentServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = DocumentServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_document._session - session2 = client2.transport.get_document._session - assert session1 != session2 - session1 = client1.transport.list_documents._session - session2 = client2.transport.list_documents._session - assert session1 != session2 - session1 = client1.transport.create_document._session - session2 = client2.transport.create_document._session - assert session1 != session2 - session1 = client1.transport.update_document._session - session2 = client2.transport.update_document._session - assert session1 != session2 - session1 = client1.transport.delete_document._session - session2 = client2.transport.delete_document._session - assert session1 != session2 - session1 = client1.transport.import_documents._session - session2 = client2.transport.import_documents._session - assert session1 != session2 - session1 = client1.transport.purge_documents._session - session2 = client2.transport.purge_documents._session - assert session1 != session2 -def test_document_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DocumentServiceGrpcTransport( - 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_document_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.DocumentServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.DocumentServiceGrpcTransport, transports.DocumentServiceGrpcAsyncIOTransport]) -def test_document_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.DocumentServiceGrpcTransport, transports.DocumentServiceGrpcAsyncIOTransport]) -def test_document_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_document_service_grpc_lro_client(): - client = DocumentServiceClient( - 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_document_service_grpc_lro_async_client(): - client = DocumentServiceAsyncClient( - 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_branch_path(): - project = "squid" - location = "clam" - data_store = "whelk" - branch = "octopus" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}".format(project=project, location=location, data_store=data_store, branch=branch, ) - actual = DocumentServiceClient.branch_path(project, location, data_store, branch) - assert expected == actual - - -def test_parse_branch_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "data_store": "cuttlefish", - "branch": "mussel", - } - path = DocumentServiceClient.branch_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentServiceClient.parse_branch_path(path) - assert expected == actual - -def test_document_path(): - project = "winkle" - location = "nautilus" - data_store = "scallop" - branch = "abalone" - document = "squid" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) - actual = DocumentServiceClient.document_path(project, location, data_store, branch, document) - assert expected == actual - - -def test_parse_document_path(): - expected = { - "project": "clam", - "location": "whelk", - "data_store": "octopus", - "branch": "oyster", - "document": "nudibranch", - } - path = DocumentServiceClient.document_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentServiceClient.parse_document_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = DocumentServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = DocumentServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = DocumentServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = DocumentServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = DocumentServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = DocumentServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = DocumentServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = DocumentServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = DocumentServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = DocumentServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = DocumentServiceClient.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.DocumentServiceTransport, '_prep_wrapped_messages') as prep: - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.DocumentServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = DocumentServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_get_operation(transport: str = "grpc"): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = DocumentServiceClient( - 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 = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = DocumentServiceClient( - 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 = DocumentServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = DocumentServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = DocumentServiceClient( - 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", [ - (DocumentServiceClient, transports.DocumentServiceGrpcTransport), - (DocumentServiceAsyncClient, transports.DocumentServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_recommendation_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_recommendation_service.py deleted file mode 100644 index 82e0f7234c14..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_recommendation_service.py +++ /dev/null @@ -1,1952 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.discoveryengine_v1beta.services.recommendation_service import RecommendationServiceAsyncClient -from google.cloud.discoveryengine_v1beta.services.recommendation_service import RecommendationServiceClient -from google.cloud.discoveryengine_v1beta.services.recommendation_service import transports -from google.cloud.discoveryengine_v1beta.types import common -from google.cloud.discoveryengine_v1beta.types import recommendation_service -from google.cloud.discoveryengine_v1beta.types import user_event -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert RecommendationServiceClient._get_default_mtls_endpoint(None) is None - assert RecommendationServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert RecommendationServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert RecommendationServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert RecommendationServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert RecommendationServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (RecommendationServiceClient, "grpc"), - (RecommendationServiceAsyncClient, "grpc_asyncio"), - (RecommendationServiceClient, "rest"), -]) -def test_recommendation_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.RecommendationServiceGrpcTransport, "grpc"), - (transports.RecommendationServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.RecommendationServiceRestTransport, "rest"), -]) -def test_recommendation_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", [ - (RecommendationServiceClient, "grpc"), - (RecommendationServiceAsyncClient, "grpc_asyncio"), - (RecommendationServiceClient, "rest"), -]) -def test_recommendation_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -def test_recommendation_service_client_get_transport_class(): - transport = RecommendationServiceClient.get_transport_class() - available_transports = [ - transports.RecommendationServiceGrpcTransport, - transports.RecommendationServiceRestTransport, - ] - assert transport in available_transports - - transport = RecommendationServiceClient.get_transport_class("grpc") - assert transport == transports.RecommendationServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (RecommendationServiceClient, transports.RecommendationServiceGrpcTransport, "grpc"), - (RecommendationServiceAsyncClient, transports.RecommendationServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (RecommendationServiceClient, transports.RecommendationServiceRestTransport, "rest"), -]) -@mock.patch.object(RecommendationServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RecommendationServiceClient)) -@mock.patch.object(RecommendationServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RecommendationServiceAsyncClient)) -def test_recommendation_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(RecommendationServiceClient, '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(RecommendationServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (RecommendationServiceClient, transports.RecommendationServiceGrpcTransport, "grpc", "true"), - (RecommendationServiceAsyncClient, transports.RecommendationServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (RecommendationServiceClient, transports.RecommendationServiceGrpcTransport, "grpc", "false"), - (RecommendationServiceAsyncClient, transports.RecommendationServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (RecommendationServiceClient, transports.RecommendationServiceRestTransport, "rest", "true"), - (RecommendationServiceClient, transports.RecommendationServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(RecommendationServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RecommendationServiceClient)) -@mock.patch.object(RecommendationServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RecommendationServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_recommendation_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 - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - RecommendationServiceClient, RecommendationServiceAsyncClient -]) -@mock.patch.object(RecommendationServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RecommendationServiceClient)) -@mock.patch.object(RecommendationServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RecommendationServiceAsyncClient)) -def test_recommendation_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (RecommendationServiceClient, transports.RecommendationServiceGrpcTransport, "grpc"), - (RecommendationServiceAsyncClient, transports.RecommendationServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (RecommendationServiceClient, transports.RecommendationServiceRestTransport, "rest"), -]) -def test_recommendation_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, - 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", [ - (RecommendationServiceClient, transports.RecommendationServiceGrpcTransport, "grpc", grpc_helpers), - (RecommendationServiceAsyncClient, transports.RecommendationServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (RecommendationServiceClient, transports.RecommendationServiceRestTransport, "rest", None), -]) -def test_recommendation_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, - scopes=None, - client_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_recommendation_service_client_client_options_from_dict(): - with mock.patch('google.cloud.discoveryengine_v1beta.services.recommendation_service.transports.RecommendationServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = RecommendationServiceClient( - 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", [ - (RecommendationServiceClient, transports.RecommendationServiceGrpcTransport, "grpc", grpc_helpers), - (RecommendationServiceAsyncClient, transports.RecommendationServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_recommendation_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, - scopes=None, - client_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - recommendation_service.RecommendRequest, - dict, -]) -def test_recommend(request_type, transport: str = 'grpc'): - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.recommend), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = recommendation_service.RecommendResponse( - attribution_token='attribution_token_value', - missing_ids=['missing_ids_value'], - validate_only=True, - ) - response = client.recommend(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == recommendation_service.RecommendRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, recommendation_service.RecommendResponse) - assert response.attribution_token == 'attribution_token_value' - assert response.missing_ids == ['missing_ids_value'] - assert response.validate_only is True - - -def test_recommend_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.recommend), - '__call__') as call: - client.recommend() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == recommendation_service.RecommendRequest() - -@pytest.mark.asyncio -async def test_recommend_async(transport: str = 'grpc_asyncio', request_type=recommendation_service.RecommendRequest): - client = RecommendationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.recommend), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(recommendation_service.RecommendResponse( - attribution_token='attribution_token_value', - missing_ids=['missing_ids_value'], - validate_only=True, - )) - response = await client.recommend(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == recommendation_service.RecommendRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, recommendation_service.RecommendResponse) - assert response.attribution_token == 'attribution_token_value' - assert response.missing_ids == ['missing_ids_value'] - assert response.validate_only is True - - -@pytest.mark.asyncio -async def test_recommend_async_from_dict(): - await test_recommend_async(request_type=dict) - - -def test_recommend_field_headers(): - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = recommendation_service.RecommendRequest() - - request.serving_config = 'serving_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.recommend), - '__call__') as call: - call.return_value = recommendation_service.RecommendResponse() - client.recommend(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config=serving_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_recommend_field_headers_async(): - client = RecommendationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = recommendation_service.RecommendRequest() - - request.serving_config = 'serving_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.recommend), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(recommendation_service.RecommendResponse()) - await client.recommend(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config=serving_config_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - recommendation_service.RecommendRequest, - dict, -]) -def test_recommend_rest(request_type): - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'serving_config': 'projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/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 = recommendation_service.RecommendResponse( - attribution_token='attribution_token_value', - missing_ids=['missing_ids_value'], - validate_only=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = recommendation_service.RecommendResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.recommend(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, recommendation_service.RecommendResponse) - assert response.attribution_token == 'attribution_token_value' - assert response.missing_ids == ['missing_ids_value'] - assert response.validate_only is True - - -def test_recommend_rest_required_fields(request_type=recommendation_service.RecommendRequest): - transport_class = transports.RecommendationServiceRestTransport - - request_init = {} - request_init["serving_config"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).recommend._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["servingConfig"] = 'serving_config_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).recommend._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "servingConfig" in jsonified_request - assert jsonified_request["servingConfig"] == 'serving_config_value' - - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = recommendation_service.RecommendResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = recommendation_service.RecommendResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.recommend(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_recommend_rest_unset_required_fields(): - transport = transports.RecommendationServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.recommend._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("servingConfig", "userEvent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_recommend_rest_interceptors(null_interceptor): - transport = transports.RecommendationServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RecommendationServiceRestInterceptor(), - ) - client = RecommendationServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RecommendationServiceRestInterceptor, "post_recommend") as post, \ - mock.patch.object(transports.RecommendationServiceRestInterceptor, "pre_recommend") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = recommendation_service.RecommendRequest.pb(recommendation_service.RecommendRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = recommendation_service.RecommendResponse.to_json(recommendation_service.RecommendResponse()) - - request = recommendation_service.RecommendRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = recommendation_service.RecommendResponse() - - client.recommend(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_recommend_rest_bad_request(transport: str = 'rest', request_type=recommendation_service.RecommendRequest): - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'serving_config': 'projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.recommend(request) - - -def test_recommend_rest_error(): - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.RecommendationServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.RecommendationServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RecommendationServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.RecommendationServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = RecommendationServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = RecommendationServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.RecommendationServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RecommendationServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.RecommendationServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = RecommendationServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.RecommendationServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.RecommendationServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.RecommendationServiceGrpcTransport, - transports.RecommendationServiceGrpcAsyncIOTransport, - transports.RecommendationServiceRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = RecommendationServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.RecommendationServiceGrpcTransport, - ) - -def test_recommendation_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.RecommendationServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_recommendation_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.discoveryengine_v1beta.services.recommendation_service.transports.RecommendationServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.RecommendationServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'recommend', - 'get_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_recommendation_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.discoveryengine_v1beta.services.recommendation_service.transports.RecommendationServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RecommendationServiceTransport( - 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_recommendation_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.discoveryengine_v1beta.services.recommendation_service.transports.RecommendationServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RecommendationServiceTransport() - adc.assert_called_once() - - -def test_recommendation_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) - RecommendationServiceClient() - 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.RecommendationServiceGrpcTransport, - transports.RecommendationServiceGrpcAsyncIOTransport, - ], -) -def test_recommendation_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.RecommendationServiceGrpcTransport, - transports.RecommendationServiceGrpcAsyncIOTransport, - transports.RecommendationServiceRestTransport, - ], -) -def test_recommendation_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.RecommendationServiceGrpcTransport, grpc_helpers), - (transports.RecommendationServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_recommendation_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.RecommendationServiceGrpcTransport, transports.RecommendationServiceGrpcAsyncIOTransport]) -def test_recommendation_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_recommendation_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.RecommendationServiceRestTransport ( - 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_recommendation_service_host_no_port(transport_name): - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_recommendation_service_host_with_port(transport_name): - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_recommendation_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = RecommendationServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = RecommendationServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.recommend._session - session2 = client2.transport.recommend._session - assert session1 != session2 -def test_recommendation_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.RecommendationServiceGrpcTransport( - 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_recommendation_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.RecommendationServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.RecommendationServiceGrpcTransport, transports.RecommendationServiceGrpcAsyncIOTransport]) -def test_recommendation_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.RecommendationServiceGrpcTransport, transports.RecommendationServiceGrpcAsyncIOTransport]) -def test_recommendation_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_document_path(): - project = "squid" - location = "clam" - data_store = "whelk" - branch = "octopus" - document = "oyster" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) - actual = RecommendationServiceClient.document_path(project, location, data_store, branch, document) - assert expected == actual - - -def test_parse_document_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "data_store": "mussel", - "branch": "winkle", - "document": "nautilus", - } - path = RecommendationServiceClient.document_path(**expected) - - # Check that the path construction is reversible. - actual = RecommendationServiceClient.parse_document_path(path) - assert expected == actual - -def test_serving_config_path(): - project = "scallop" - location = "abalone" - data_store = "squid" - serving_config = "clam" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}/servingConfigs/{serving_config}".format(project=project, location=location, data_store=data_store, serving_config=serving_config, ) - actual = RecommendationServiceClient.serving_config_path(project, location, data_store, serving_config) - assert expected == actual - - -def test_parse_serving_config_path(): - expected = { - "project": "whelk", - "location": "octopus", - "data_store": "oyster", - "serving_config": "nudibranch", - } - path = RecommendationServiceClient.serving_config_path(**expected) - - # Check that the path construction is reversible. - actual = RecommendationServiceClient.parse_serving_config_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = RecommendationServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = RecommendationServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = RecommendationServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = RecommendationServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = RecommendationServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = RecommendationServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = RecommendationServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = RecommendationServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = RecommendationServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = RecommendationServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = RecommendationServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = RecommendationServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = RecommendationServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = RecommendationServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = RecommendationServiceClient.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.RecommendationServiceTransport, '_prep_wrapped_messages') as prep: - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.RecommendationServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = RecommendationServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = RecommendationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_get_operation(transport: str = "grpc"): - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = RecommendationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = RecommendationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = RecommendationServiceClient( - 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 = RecommendationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = RecommendationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = RecommendationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = RecommendationServiceClient( - 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 = RecommendationServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = RecommendationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = RecommendationServiceClient( - 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", [ - (RecommendationServiceClient, transports.RecommendationServiceGrpcTransport), - (RecommendationServiceAsyncClient, transports.RecommendationServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_schema_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_schema_service.py deleted file mode 100644 index 13021b222ce4..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_schema_service.py +++ /dev/null @@ -1,4265 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.discoveryengine_v1beta.services.schema_service import SchemaServiceAsyncClient -from google.cloud.discoveryengine_v1beta.services.schema_service import SchemaServiceClient -from google.cloud.discoveryengine_v1beta.services.schema_service import pagers -from google.cloud.discoveryengine_v1beta.services.schema_service import transports -from google.cloud.discoveryengine_v1beta.types import schema -from google.cloud.discoveryengine_v1beta.types import schema as gcd_schema -from google.cloud.discoveryengine_v1beta.types import schema_service -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert SchemaServiceClient._get_default_mtls_endpoint(None) is None - assert SchemaServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SchemaServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SchemaServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SchemaServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SchemaServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (SchemaServiceClient, "grpc"), - (SchemaServiceAsyncClient, "grpc_asyncio"), - (SchemaServiceClient, "rest"), -]) -def test_schema_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.SchemaServiceGrpcTransport, "grpc"), - (transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.SchemaServiceRestTransport, "rest"), -]) -def test_schema_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", [ - (SchemaServiceClient, "grpc"), - (SchemaServiceAsyncClient, "grpc_asyncio"), - (SchemaServiceClient, "rest"), -]) -def test_schema_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -def test_schema_service_client_get_transport_class(): - transport = SchemaServiceClient.get_transport_class() - available_transports = [ - transports.SchemaServiceGrpcTransport, - transports.SchemaServiceRestTransport, - ] - assert transport in available_transports - - transport = SchemaServiceClient.get_transport_class("grpc") - assert transport == transports.SchemaServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc"), - (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (SchemaServiceClient, transports.SchemaServiceRestTransport, "rest"), -]) -@mock.patch.object(SchemaServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceClient)) -@mock.patch.object(SchemaServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceAsyncClient)) -def test_schema_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(SchemaServiceClient, '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(SchemaServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc", "true"), - (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc", "false"), - (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (SchemaServiceClient, transports.SchemaServiceRestTransport, "rest", "true"), - (SchemaServiceClient, transports.SchemaServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(SchemaServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceClient)) -@mock.patch.object(SchemaServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_schema_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 - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - SchemaServiceClient, SchemaServiceAsyncClient -]) -@mock.patch.object(SchemaServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceClient)) -@mock.patch.object(SchemaServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SchemaServiceAsyncClient)) -def test_schema_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc"), - (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (SchemaServiceClient, transports.SchemaServiceRestTransport, "rest"), -]) -def test_schema_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, - 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", [ - (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc", grpc_helpers), - (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (SchemaServiceClient, transports.SchemaServiceRestTransport, "rest", None), -]) -def test_schema_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, - scopes=None, - client_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_schema_service_client_client_options_from_dict(): - with mock.patch('google.cloud.discoveryengine_v1beta.services.schema_service.transports.SchemaServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SchemaServiceClient( - 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", [ - (SchemaServiceClient, transports.SchemaServiceGrpcTransport, "grpc", grpc_helpers), - (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_schema_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, - scopes=None, - client_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - schema_service.GetSchemaRequest, - dict, -]) -def test_get_schema(request_type, transport: str = 'grpc'): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema.Schema( - name='name_value', - json_schema='json_schema_value', - ) - response = client.get_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.GetSchemaRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, schema.Schema) - assert response.name == 'name_value' - - -def test_get_schema_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_schema), - '__call__') as call: - client.get_schema() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.GetSchemaRequest() - -@pytest.mark.asyncio -async def test_get_schema_async(transport: str = 'grpc_asyncio', request_type=schema_service.GetSchemaRequest): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(schema.Schema( - name='name_value', - )) - response = await client.get_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.GetSchemaRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, schema.Schema) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_schema_async_from_dict(): - await test_get_schema_async(request_type=dict) - - -def test_get_schema_field_headers(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema_service.GetSchemaRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_schema), - '__call__') as call: - call.return_value = schema.Schema() - client.get_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_schema_field_headers_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema_service.GetSchemaRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_schema), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.Schema()) - await client.get_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_schema_flattened(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema.Schema() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_schema( - 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_schema_flattened_error(): - client = SchemaServiceClient( - credentials=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_schema( - schema_service.GetSchemaRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_schema_flattened_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema.Schema() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema.Schema()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_schema( - 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_schema_flattened_error_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_schema( - schema_service.GetSchemaRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - schema_service.ListSchemasRequest, - dict, -]) -def test_list_schemas(request_type, transport: str = 'grpc'): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_schemas), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema_service.ListSchemasResponse( - next_page_token='next_page_token_value', - ) - response = client.list_schemas(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.ListSchemasRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSchemasPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_schemas_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__') as call: - client.list_schemas() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.ListSchemasRequest() - -@pytest.mark.asyncio -async def test_list_schemas_async(transport: str = 'grpc_asyncio', request_type=schema_service.ListSchemasRequest): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_schemas), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(schema_service.ListSchemasResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_schemas(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.ListSchemasRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSchemasAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_schemas_async_from_dict(): - await test_list_schemas_async(request_type=dict) - - -def test_list_schemas_field_headers(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema_service.ListSchemasRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__') as call: - call.return_value = schema_service.ListSchemasResponse() - client.list_schemas(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_schemas_field_headers_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema_service.ListSchemasRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema_service.ListSchemasResponse()) - await client.list_schemas(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_schemas_flattened(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema_service.ListSchemasResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_schemas( - 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_schemas_flattened_error(): - client = SchemaServiceClient( - credentials=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_schemas( - schema_service.ListSchemasRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_schemas_flattened_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = schema_service.ListSchemasResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(schema_service.ListSchemasResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_schemas( - 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_schemas_flattened_error_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_schemas( - schema_service.ListSchemasRequest(), - parent='parent_value', - ) - - -def test_list_schemas_pager(transport_name: str = "grpc"): - client = SchemaServiceClient( - 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_schemas), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - schema.Schema(), - ], - next_page_token='abc', - ), - schema_service.ListSchemasResponse( - schemas=[], - next_page_token='def', - ), - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - ], - next_page_token='ghi', - ), - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_schemas(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, schema.Schema) - for i in results) -def test_list_schemas_pages(transport_name: str = "grpc"): - client = SchemaServiceClient( - 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_schemas), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - schema.Schema(), - ], - next_page_token='abc', - ), - schema_service.ListSchemasResponse( - schemas=[], - next_page_token='def', - ), - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - ], - next_page_token='ghi', - ), - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - ], - ), - RuntimeError, - ) - pages = list(client.list_schemas(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_schemas_async_pager(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - schema.Schema(), - ], - next_page_token='abc', - ), - schema_service.ListSchemasResponse( - schemas=[], - next_page_token='def', - ), - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - ], - next_page_token='ghi', - ), - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_schemas(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, schema.Schema) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_schemas_async_pages(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_schemas), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - schema.Schema(), - ], - next_page_token='abc', - ), - schema_service.ListSchemasResponse( - schemas=[], - next_page_token='def', - ), - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - ], - next_page_token='ghi', - ), - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_schemas(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", [ - schema_service.CreateSchemaRequest, - dict, -]) -def test_create_schema(request_type, transport: str = 'grpc'): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.CreateSchemaRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_schema_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_schema), - '__call__') as call: - client.create_schema() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.CreateSchemaRequest() - -@pytest.mark.asyncio -async def test_create_schema_async(transport: str = 'grpc_asyncio', request_type=schema_service.CreateSchemaRequest): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_schema), - '__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_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.CreateSchemaRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_schema_async_from_dict(): - await test_create_schema_async(request_type=dict) - - -def test_create_schema_field_headers(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema_service.CreateSchemaRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_schema), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_schema_field_headers_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema_service.CreateSchemaRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_schema), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_schema_flattened(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_schema), - '__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_schema( - parent='parent_value', - schema=gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), - schema_id='schema_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].schema - mock_val = gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})) - assert arg == mock_val - arg = args[0].schema_id - mock_val = 'schema_id_value' - assert arg == mock_val - - -def test_create_schema_flattened_error(): - client = SchemaServiceClient( - credentials=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_schema( - schema_service.CreateSchemaRequest(), - parent='parent_value', - schema=gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), - schema_id='schema_id_value', - ) - -@pytest.mark.asyncio -async def test_create_schema_flattened_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_schema), - '__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_schema( - parent='parent_value', - schema=gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), - schema_id='schema_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].schema - mock_val = gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})) - assert arg == mock_val - arg = args[0].schema_id - mock_val = 'schema_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_schema_flattened_error_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_schema( - schema_service.CreateSchemaRequest(), - parent='parent_value', - schema=gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), - schema_id='schema_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - schema_service.UpdateSchemaRequest, - dict, -]) -def test_update_schema(request_type, transport: str = 'grpc'): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.UpdateSchemaRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_schema_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_schema), - '__call__') as call: - client.update_schema() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.UpdateSchemaRequest() - -@pytest.mark.asyncio -async def test_update_schema_async(transport: str = 'grpc_asyncio', request_type=schema_service.UpdateSchemaRequest): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_schema), - '__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_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.UpdateSchemaRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_schema_async_from_dict(): - await test_update_schema_async(request_type=dict) - - -def test_update_schema_field_headers(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema_service.UpdateSchemaRequest() - - request.schema.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_schema), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'schema.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_schema_field_headers_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema_service.UpdateSchemaRequest() - - request.schema.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_schema), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'schema.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - schema_service.DeleteSchemaRequest, - dict, -]) -def test_delete_schema(request_type, transport: str = 'grpc'): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_schema), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.DeleteSchemaRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_schema_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_schema), - '__call__') as call: - client.delete_schema() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.DeleteSchemaRequest() - -@pytest.mark.asyncio -async def test_delete_schema_async(transport: str = 'grpc_asyncio', request_type=schema_service.DeleteSchemaRequest): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_schema), - '__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_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == schema_service.DeleteSchemaRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_schema_async_from_dict(): - await test_delete_schema_async(request_type=dict) - - -def test_delete_schema_field_headers(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema_service.DeleteSchemaRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_schema), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_schema_field_headers_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = schema_service.DeleteSchemaRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_schema), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_schema(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_schema_flattened(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_schema), - '__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_schema( - 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_schema_flattened_error(): - client = SchemaServiceClient( - credentials=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_schema( - schema_service.DeleteSchemaRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_schema_flattened_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_schema), - '__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_schema( - 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_schema_flattened_error_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_schema( - schema_service.DeleteSchemaRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - schema_service.GetSchemaRequest, - dict, -]) -def test_get_schema_rest(request_type): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/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 = schema.Schema( - name='name_value', - json_schema='json_schema_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 = schema.Schema.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_schema(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, schema.Schema) - assert response.name == 'name_value' - - -def test_get_schema_rest_required_fields(request_type=schema_service.GetSchemaRequest): - transport_class = transports.SchemaServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_schema._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_schema._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = schema.Schema() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = schema.Schema.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_schema(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_schema_rest_unset_required_fields(): - transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_schema._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_schema_rest_interceptors(null_interceptor): - transport = transports.SchemaServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), - ) - client = SchemaServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SchemaServiceRestInterceptor, "post_get_schema") as post, \ - mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_get_schema") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = schema_service.GetSchemaRequest.pb(schema_service.GetSchemaRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = schema.Schema.to_json(schema.Schema()) - - request = schema_service.GetSchemaRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = schema.Schema() - - client.get_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_schema_rest_bad_request(transport: str = 'rest', request_type=schema_service.GetSchemaRequest): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_schema(request) - - -def test_get_schema_rest_flattened(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = schema.Schema() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/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 = schema.Schema.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_schema(**mock_args) - - # Establish that the underlying call 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/*/dataStores/*/schemas/*}" % client.transport._host, args[1]) - - -def test_get_schema_rest_flattened_error(transport: str = 'rest'): - client = SchemaServiceClient( - credentials=ga_credentials.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_schema( - schema_service.GetSchemaRequest(), - name='name_value', - ) - - -def test_get_schema_rest_error(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - schema_service.ListSchemasRequest, - dict, -]) -def test_list_schemas_rest(request_type): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/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 = schema_service.ListSchemasResponse( - next_page_token='next_page_token_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 = schema_service.ListSchemasResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_schemas(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSchemasPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_schemas_rest_required_fields(request_type=schema_service.ListSchemasRequest): - transport_class = transports.SchemaServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_schemas._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_schemas._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = schema_service.ListSchemasResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = schema_service.ListSchemasResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_schemas(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_schemas_rest_unset_required_fields(): - transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_schemas._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_schemas_rest_interceptors(null_interceptor): - transport = transports.SchemaServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), - ) - client = SchemaServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SchemaServiceRestInterceptor, "post_list_schemas") as post, \ - mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_list_schemas") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = schema_service.ListSchemasRequest.pb(schema_service.ListSchemasRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = schema_service.ListSchemasResponse.to_json(schema_service.ListSchemasResponse()) - - request = schema_service.ListSchemasRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = schema_service.ListSchemasResponse() - - client.list_schemas(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_schemas_rest_bad_request(transport: str = 'rest', request_type=schema_service.ListSchemasRequest): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_schemas(request) - - -def test_list_schemas_rest_flattened(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = schema_service.ListSchemasResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/dataStores/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 = schema_service.ListSchemasResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_schemas(**mock_args) - - # Establish that the underlying call 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/*/dataStores/*}/schemas" % client.transport._host, args[1]) - - -def test_list_schemas_rest_flattened_error(transport: str = 'rest'): - client = SchemaServiceClient( - credentials=ga_credentials.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_schemas( - schema_service.ListSchemasRequest(), - parent='parent_value', - ) - - -def test_list_schemas_rest_pager(transport: str = 'rest'): - client = SchemaServiceClient( - 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 = ( - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - schema.Schema(), - ], - next_page_token='abc', - ), - schema_service.ListSchemasResponse( - schemas=[], - next_page_token='def', - ), - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - ], - next_page_token='ghi', - ), - schema_service.ListSchemasResponse( - schemas=[ - schema.Schema(), - schema.Schema(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(schema_service.ListSchemasResponse.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/dataStores/sample3'} - - pager = client.list_schemas(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, schema.Schema) - for i in results) - - pages = list(client.list_schemas(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - schema_service.CreateSchemaRequest, - dict, -]) -def test_create_schema_rest(request_type): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - request_init["schema"] = {'struct_schema': {'fields': {}}, 'json_schema': 'json_schema_value', 'name': 'name_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 = schema_service.CreateSchemaRequest.meta.fields["schema"] - - 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["schema"].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["schema"][field])): - del request_init["schema"][field][i][subfield] - else: - del request_init["schema"][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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_schema(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_create_schema_rest_required_fields(request_type=schema_service.CreateSchemaRequest): - transport_class = transports.SchemaServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["schema_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "schemaId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_schema._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "schemaId" in jsonified_request - assert jsonified_request["schemaId"] == request_init["schema_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["schemaId"] = 'schema_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_schema._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("schema_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "schemaId" in jsonified_request - assert jsonified_request["schemaId"] == 'schema_id_value' - - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_schema(request) - - expected_params = [ - ( - "schemaId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_schema_rest_unset_required_fields(): - transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_schema._get_unset_required_fields({}) - assert set(unset_fields) == (set(("schemaId", )) & set(("parent", "schema", "schemaId", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_schema_rest_interceptors(null_interceptor): - transport = transports.SchemaServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), - ) - client = SchemaServiceClient(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.SchemaServiceRestInterceptor, "post_create_schema") as post, \ - mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_create_schema") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = schema_service.CreateSchemaRequest.pb(schema_service.CreateSchemaRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = schema_service.CreateSchemaRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_schema_rest_bad_request(transport: str = 'rest', request_type=schema_service.CreateSchemaRequest): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_schema(request) - - -def test_create_schema_rest_flattened(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.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/dataStores/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - schema=gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), - schema_id='schema_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_schema(**mock_args) - - # Establish that the underlying call 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/*/dataStores/*}/schemas" % client.transport._host, args[1]) - - -def test_create_schema_rest_flattened_error(transport: str = 'rest'): - client = SchemaServiceClient( - credentials=ga_credentials.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_schema( - schema_service.CreateSchemaRequest(), - parent='parent_value', - schema=gcd_schema.Schema(struct_schema=struct_pb2.Struct(fields={'key_value': struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)})), - schema_id='schema_id_value', - ) - - -def test_create_schema_rest_error(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - schema_service.UpdateSchemaRequest, - dict, -]) -def test_update_schema_rest(request_type): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'schema': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/sample4'}} - request_init["schema"] = {'struct_schema': {'fields': {}}, 'json_schema': 'json_schema_value', 'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/sample4'} - # 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 = schema_service.UpdateSchemaRequest.meta.fields["schema"] - - 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["schema"].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["schema"][field])): - del request_init["schema"][field][i][subfield] - else: - del request_init["schema"][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 = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_schema(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_update_schema_rest_required_fields(request_type=schema_service.UpdateSchemaRequest): - transport_class = transports.SchemaServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_schema._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_schema._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_missing", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_schema(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_schema_rest_unset_required_fields(): - transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_schema._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowMissing", )) & set(("schema", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_schema_rest_interceptors(null_interceptor): - transport = transports.SchemaServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), - ) - client = SchemaServiceClient(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.SchemaServiceRestInterceptor, "post_update_schema") as post, \ - mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_update_schema") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = schema_service.UpdateSchemaRequest.pb(schema_service.UpdateSchemaRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = schema_service.UpdateSchemaRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_schema_rest_bad_request(transport: str = 'rest', request_type=schema_service.UpdateSchemaRequest): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'schema': {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/sample4'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_schema(request) - - -def test_update_schema_rest_error(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - schema_service.DeleteSchemaRequest, - dict, -]) -def test_delete_schema_rest(request_type): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_schema(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_delete_schema_rest_required_fields(request_type=schema_service.DeleteSchemaRequest): - transport_class = transports.SchemaServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_schema._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_schema._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_schema(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_schema_rest_unset_required_fields(): - transport = transports.SchemaServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_schema._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_schema_rest_interceptors(null_interceptor): - transport = transports.SchemaServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SchemaServiceRestInterceptor(), - ) - client = SchemaServiceClient(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.SchemaServiceRestInterceptor, "post_delete_schema") as post, \ - mock.patch.object(transports.SchemaServiceRestInterceptor, "pre_delete_schema") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = schema_service.DeleteSchemaRequest.pb(schema_service.DeleteSchemaRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = schema_service.DeleteSchemaRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_schema_rest_bad_request(transport: str = 'rest', request_type=schema_service.DeleteSchemaRequest): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3/schemas/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_schema(request) - - -def test_delete_schema_rest_flattened(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.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/dataStores/sample3/schemas/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_schema(**mock_args) - - # Establish that the underlying call 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/*/dataStores/*/schemas/*}" % client.transport._host, args[1]) - - -def test_delete_schema_rest_flattened_error(transport: str = 'rest'): - client = SchemaServiceClient( - credentials=ga_credentials.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_schema( - schema_service.DeleteSchemaRequest(), - name='name_value', - ) - - -def test_delete_schema_rest_error(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.SchemaServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SchemaServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SchemaServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.SchemaServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SchemaServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SchemaServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SchemaServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SchemaServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SchemaServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SchemaServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SchemaServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SchemaServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.SchemaServiceGrpcTransport, - transports.SchemaServiceGrpcAsyncIOTransport, - transports.SchemaServiceRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = SchemaServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.SchemaServiceGrpcTransport, - ) - -def test_schema_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.SchemaServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_schema_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.discoveryengine_v1beta.services.schema_service.transports.SchemaServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SchemaServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'get_schema', - 'list_schemas', - 'create_schema', - 'update_schema', - 'delete_schema', - 'get_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_schema_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.discoveryengine_v1beta.services.schema_service.transports.SchemaServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SchemaServiceTransport( - 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_schema_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.discoveryengine_v1beta.services.schema_service.transports.SchemaServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SchemaServiceTransport() - adc.assert_called_once() - - -def test_schema_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) - SchemaServiceClient() - 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.SchemaServiceGrpcTransport, - transports.SchemaServiceGrpcAsyncIOTransport, - ], -) -def test_schema_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.SchemaServiceGrpcTransport, - transports.SchemaServiceGrpcAsyncIOTransport, - transports.SchemaServiceRestTransport, - ], -) -def test_schema_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.SchemaServiceGrpcTransport, grpc_helpers), - (transports.SchemaServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_schema_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.SchemaServiceGrpcTransport, transports.SchemaServiceGrpcAsyncIOTransport]) -def test_schema_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_schema_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.SchemaServiceRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_schema_service_rest_lro_client(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_schema_service_host_no_port(transport_name): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_schema_service_host_with_port(transport_name): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_schema_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = SchemaServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = SchemaServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.get_schema._session - session2 = client2.transport.get_schema._session - assert session1 != session2 - session1 = client1.transport.list_schemas._session - session2 = client2.transport.list_schemas._session - assert session1 != session2 - session1 = client1.transport.create_schema._session - session2 = client2.transport.create_schema._session - assert session1 != session2 - session1 = client1.transport.update_schema._session - session2 = client2.transport.update_schema._session - assert session1 != session2 - session1 = client1.transport.delete_schema._session - session2 = client2.transport.delete_schema._session - assert session1 != session2 -def test_schema_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SchemaServiceGrpcTransport( - 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_schema_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SchemaServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.SchemaServiceGrpcTransport, transports.SchemaServiceGrpcAsyncIOTransport]) -def test_schema_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.SchemaServiceGrpcTransport, transports.SchemaServiceGrpcAsyncIOTransport]) -def test_schema_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_schema_service_grpc_lro_client(): - client = SchemaServiceClient( - 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_schema_service_grpc_lro_async_client(): - client = SchemaServiceAsyncClient( - 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_data_store_path(): - project = "squid" - location = "clam" - data_store = "whelk" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) - actual = SchemaServiceClient.data_store_path(project, location, data_store) - assert expected == actual - - -def test_parse_data_store_path(): - expected = { - "project": "octopus", - "location": "oyster", - "data_store": "nudibranch", - } - path = SchemaServiceClient.data_store_path(**expected) - - # Check that the path construction is reversible. - actual = SchemaServiceClient.parse_data_store_path(path) - assert expected == actual - -def test_schema_path(): - project = "cuttlefish" - location = "mussel" - data_store = "winkle" - schema = "nautilus" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}/schemas/{schema}".format(project=project, location=location, data_store=data_store, schema=schema, ) - actual = SchemaServiceClient.schema_path(project, location, data_store, schema) - assert expected == actual - - -def test_parse_schema_path(): - expected = { - "project": "scallop", - "location": "abalone", - "data_store": "squid", - "schema": "clam", - } - path = SchemaServiceClient.schema_path(**expected) - - # Check that the path construction is reversible. - actual = SchemaServiceClient.parse_schema_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SchemaServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = SchemaServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SchemaServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = SchemaServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = SchemaServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SchemaServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SchemaServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = SchemaServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SchemaServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = SchemaServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = SchemaServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SchemaServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "scallop" - location = "abalone" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = SchemaServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = SchemaServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SchemaServiceClient.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.SchemaServiceTransport, '_prep_wrapped_messages') as prep: - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SchemaServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = SchemaServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_get_operation(transport: str = "grpc"): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SchemaServiceClient( - 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 = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SchemaServiceClient( - 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 = SchemaServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = SchemaServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = SchemaServiceClient( - 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", [ - (SchemaServiceClient, transports.SchemaServiceGrpcTransport), - (SchemaServiceAsyncClient, transports.SchemaServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_search_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_search_service.py deleted file mode 100644 index 7e11d808f030..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_search_service.py +++ /dev/null @@ -1,2239 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.discoveryengine_v1beta.services.search_service import SearchServiceAsyncClient -from google.cloud.discoveryengine_v1beta.services.search_service import SearchServiceClient -from google.cloud.discoveryengine_v1beta.services.search_service import pagers -from google.cloud.discoveryengine_v1beta.services.search_service import transports -from google.cloud.discoveryengine_v1beta.types import common -from google.cloud.discoveryengine_v1beta.types import search_service -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import struct_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert SearchServiceClient._get_default_mtls_endpoint(None) is None - assert SearchServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert SearchServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (SearchServiceClient, "grpc"), - (SearchServiceAsyncClient, "grpc_asyncio"), - (SearchServiceClient, "rest"), -]) -def test_search_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.SearchServiceGrpcTransport, "grpc"), - (transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.SearchServiceRestTransport, "rest"), -]) -def test_search_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", [ - (SearchServiceClient, "grpc"), - (SearchServiceAsyncClient, "grpc_asyncio"), - (SearchServiceClient, "rest"), -]) -def test_search_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -def test_search_service_client_get_transport_class(): - transport = SearchServiceClient.get_transport_class() - available_transports = [ - transports.SearchServiceGrpcTransport, - transports.SearchServiceRestTransport, - ] - assert transport in available_transports - - transport = SearchServiceClient.get_transport_class("grpc") - assert transport == transports.SearchServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (SearchServiceClient, transports.SearchServiceRestTransport, "rest"), -]) -@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) -@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) -def test_search_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(SearchServiceClient, '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(SearchServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "true"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", "false"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (SearchServiceClient, transports.SearchServiceRestTransport, "rest", "true"), - (SearchServiceClient, transports.SearchServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) -@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_search_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 - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - SearchServiceClient, SearchServiceAsyncClient -]) -@mock.patch.object(SearchServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceClient)) -@mock.patch.object(SearchServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SearchServiceAsyncClient)) -def test_search_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc"), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (SearchServiceClient, transports.SearchServiceRestTransport, "rest"), -]) -def test_search_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, - 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", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (SearchServiceClient, transports.SearchServiceRestTransport, "rest", None), -]) -def test_search_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, - scopes=None, - client_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_search_service_client_client_options_from_dict(): - with mock.patch('google.cloud.discoveryengine_v1beta.services.search_service.transports.SearchServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = SearchServiceClient( - 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", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport, "grpc", grpc_helpers), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_search_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, - scopes=None, - client_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - search_service.SearchRequest, - dict, -]) -def test_search(request_type, transport: str = 'grpc'): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = search_service.SearchResponse( - total_size=1086, - attribution_token='attribution_token_value', - redirect_uri='redirect_uri_value', - next_page_token='next_page_token_value', - corrected_query='corrected_query_value', - applied_controls=['applied_controls_value'], - ) - response = client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchPager) - assert response.total_size == 1086 - assert response.attribution_token == 'attribution_token_value' - assert response.redirect_uri == 'redirect_uri_value' - assert response.next_page_token == 'next_page_token_value' - assert response.corrected_query == 'corrected_query_value' - assert response.applied_controls == ['applied_controls_value'] - - -def test_search_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - client.search() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - -@pytest.mark.asyncio -async def test_search_async(transport: str = 'grpc_asyncio', request_type=search_service.SearchRequest): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse( - total_size=1086, - attribution_token='attribution_token_value', - redirect_uri='redirect_uri_value', - next_page_token='next_page_token_value', - corrected_query='corrected_query_value', - applied_controls=['applied_controls_value'], - )) - response = await client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == search_service.SearchRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchAsyncPager) - assert response.total_size == 1086 - assert response.attribution_token == 'attribution_token_value' - assert response.redirect_uri == 'redirect_uri_value' - assert response.next_page_token == 'next_page_token_value' - assert response.corrected_query == 'corrected_query_value' - assert response.applied_controls == ['applied_controls_value'] - - -@pytest.mark.asyncio -async def test_search_async_from_dict(): - await test_search_async(request_type=dict) - - -def test_search_field_headers(): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = search_service.SearchRequest() - - request.serving_config = 'serving_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - call.return_value = search_service.SearchResponse() - client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config=serving_config_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_search_field_headers_async(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = search_service.SearchRequest() - - request.serving_config = 'serving_config_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(search_service.SearchResponse()) - await client.search(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'serving_config=serving_config_value', - ) in kw['metadata'] - - -def test_search_pager(transport_name: str = "grpc"): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('serving_config', ''), - )), - ) - pager = client.search(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, search_service.SearchResponse.SearchResult) - for i in results) -def test_search_pages(transport_name: str = "grpc"): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - pages = list(client.search(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_search_async_pager(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.search(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, search_service.SearchResponse.SearchResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_search_async_pages(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.search(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", [ - search_service.SearchRequest, - dict, -]) -def test_search_rest(request_type): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'serving_config': 'projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/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 = search_service.SearchResponse( - total_size=1086, - attribution_token='attribution_token_value', - redirect_uri='redirect_uri_value', - next_page_token='next_page_token_value', - corrected_query='corrected_query_value', - applied_controls=['applied_controls_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 = search_service.SearchResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.search(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchPager) - assert response.total_size == 1086 - assert response.attribution_token == 'attribution_token_value' - assert response.redirect_uri == 'redirect_uri_value' - assert response.next_page_token == 'next_page_token_value' - assert response.corrected_query == 'corrected_query_value' - assert response.applied_controls == ['applied_controls_value'] - - -def test_search_rest_required_fields(request_type=search_service.SearchRequest): - transport_class = transports.SearchServiceRestTransport - - request_init = {} - request_init["serving_config"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["servingConfig"] = 'serving_config_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "servingConfig" in jsonified_request - assert jsonified_request["servingConfig"] == 'serving_config_value' - - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = search_service.SearchResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = search_service.SearchResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.search(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_search_rest_unset_required_fields(): - transport = transports.SearchServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.search._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("servingConfig", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_search_rest_interceptors(null_interceptor): - transport = transports.SearchServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.SearchServiceRestInterceptor(), - ) - client = SearchServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.SearchServiceRestInterceptor, "post_search") as post, \ - mock.patch.object(transports.SearchServiceRestInterceptor, "pre_search") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = search_service.SearchRequest.pb(search_service.SearchRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = search_service.SearchResponse.to_json(search_service.SearchResponse()) - - request = search_service.SearchRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = search_service.SearchResponse() - - client.search(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_search_rest_bad_request(transport: str = 'rest', request_type=search_service.SearchRequest): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'serving_config': 'projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.search(request) - - -def test_search_rest_pager(transport: str = 'rest'): - client = SearchServiceClient( - 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 = ( - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - next_page_token='abc', - ), - search_service.SearchResponse( - results=[], - next_page_token='def', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - ], - next_page_token='ghi', - ), - search_service.SearchResponse( - results=[ - search_service.SearchResponse.SearchResult(), - search_service.SearchResponse.SearchResult(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(search_service.SearchResponse.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 = {'serving_config': 'projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/sample4'} - - pager = client.search(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, search_service.SearchResponse.SearchResult) - for i in results) - - pages = list(client.search(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.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = SearchServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = SearchServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.SearchServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.SearchServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.SearchServiceGrpcTransport, - transports.SearchServiceGrpcAsyncIOTransport, - transports.SearchServiceRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = SearchServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.SearchServiceGrpcTransport, - ) - -def test_search_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.SearchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_search_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.discoveryengine_v1beta.services.search_service.transports.SearchServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.SearchServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'search', - 'get_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_search_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.discoveryengine_v1beta.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SearchServiceTransport( - 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_search_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.discoveryengine_v1beta.services.search_service.transports.SearchServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.SearchServiceTransport() - adc.assert_called_once() - - -def test_search_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) - SearchServiceClient() - 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.SearchServiceGrpcTransport, - transports.SearchServiceGrpcAsyncIOTransport, - ], -) -def test_search_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.SearchServiceGrpcTransport, - transports.SearchServiceGrpcAsyncIOTransport, - transports.SearchServiceRestTransport, - ], -) -def test_search_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.SearchServiceGrpcTransport, grpc_helpers), - (transports.SearchServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_search_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) -def test_search_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_search_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.SearchServiceRestTransport ( - 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_search_service_host_no_port(transport_name): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_search_service_host_with_port(transport_name): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_search_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = SearchServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = SearchServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.search._session - session2 = client2.transport.search._session - assert session1 != session2 -def test_search_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SearchServiceGrpcTransport( - 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_search_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.SearchServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) -def test_search_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.SearchServiceGrpcTransport, transports.SearchServiceGrpcAsyncIOTransport]) -def test_search_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_branch_path(): - project = "squid" - location = "clam" - data_store = "whelk" - branch = "octopus" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}".format(project=project, location=location, data_store=data_store, branch=branch, ) - actual = SearchServiceClient.branch_path(project, location, data_store, branch) - assert expected == actual - - -def test_parse_branch_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "data_store": "cuttlefish", - "branch": "mussel", - } - path = SearchServiceClient.branch_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_branch_path(path) - assert expected == actual - -def test_document_path(): - project = "winkle" - location = "nautilus" - data_store = "scallop" - branch = "abalone" - document = "squid" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) - actual = SearchServiceClient.document_path(project, location, data_store, branch, document) - assert expected == actual - - -def test_parse_document_path(): - expected = { - "project": "clam", - "location": "whelk", - "data_store": "octopus", - "branch": "oyster", - "document": "nudibranch", - } - path = SearchServiceClient.document_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_document_path(path) - assert expected == actual - -def test_serving_config_path(): - project = "cuttlefish" - location = "mussel" - data_store = "winkle" - serving_config = "nautilus" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}/servingConfigs/{serving_config}".format(project=project, location=location, data_store=data_store, serving_config=serving_config, ) - actual = SearchServiceClient.serving_config_path(project, location, data_store, serving_config) - assert expected == actual - - -def test_parse_serving_config_path(): - expected = { - "project": "scallop", - "location": "abalone", - "data_store": "squid", - "serving_config": "clam", - } - path = SearchServiceClient.serving_config_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_serving_config_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = SearchServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = SearchServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = SearchServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = SearchServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = SearchServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = SearchServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = SearchServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = SearchServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "scallop" - location = "abalone" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = SearchServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = SearchServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = SearchServiceClient.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.SearchServiceTransport, '_prep_wrapped_messages') as prep: - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.SearchServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = SearchServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_get_operation(transport: str = "grpc"): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SearchServiceClient( - 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 = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = SearchServiceClient( - 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 = SearchServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = SearchServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = SearchServiceClient( - 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", [ - (SearchServiceClient, transports.SearchServiceGrpcTransport), - (SearchServiceAsyncClient, transports.SearchServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_user_event_service.py b/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_user_event_service.py deleted file mode 100644 index 3f0f8f4975d6..000000000000 --- a/owl-bot-staging/google-cloud-discoveryengine/v1beta/tests/unit/gapic/discoveryengine_v1beta/test_user_event_service.py +++ /dev/null @@ -1,2786 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.discoveryengine_v1beta.services.user_event_service import UserEventServiceAsyncClient -from google.cloud.discoveryengine_v1beta.services.user_event_service import UserEventServiceClient -from google.cloud.discoveryengine_v1beta.services.user_event_service import transports -from google.cloud.discoveryengine_v1beta.types import common -from google.cloud.discoveryengine_v1beta.types import import_config -from google.cloud.discoveryengine_v1beta.types import user_event -from google.cloud.discoveryengine_v1beta.types import user_event_service -from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.type import date_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert UserEventServiceClient._get_default_mtls_endpoint(None) is None - assert UserEventServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert UserEventServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (UserEventServiceClient, "grpc"), - (UserEventServiceAsyncClient, "grpc_asyncio"), - (UserEventServiceClient, "rest"), -]) -def test_user_event_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.UserEventServiceGrpcTransport, "grpc"), - (transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.UserEventServiceRestTransport, "rest"), -]) -def test_user_event_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", [ - (UserEventServiceClient, "grpc"), - (UserEventServiceAsyncClient, "grpc_asyncio"), - (UserEventServiceClient, "rest"), -]) -def test_user_event_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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' - ) - - -def test_user_event_service_client_get_transport_class(): - transport = UserEventServiceClient.get_transport_class() - available_transports = [ - transports.UserEventServiceGrpcTransport, - transports.UserEventServiceRestTransport, - ] - assert transport in available_transports - - transport = UserEventServiceClient.get_transport_class("grpc") - assert transport == transports.UserEventServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (UserEventServiceClient, transports.UserEventServiceRestTransport, "rest"), -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -def test_user_event_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(UserEventServiceClient, '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(UserEventServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "true"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", "false"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (UserEventServiceClient, transports.UserEventServiceRestTransport, "rest", "true"), - (UserEventServiceClient, transports.UserEventServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_user_event_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 - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - UserEventServiceClient, UserEventServiceAsyncClient -]) -@mock.patch.object(UserEventServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceClient)) -@mock.patch.object(UserEventServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(UserEventServiceAsyncClient)) -def test_user_event_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc"), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (UserEventServiceClient, transports.UserEventServiceRestTransport, "rest"), -]) -def test_user_event_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, - 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", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (UserEventServiceClient, transports.UserEventServiceRestTransport, "rest", None), -]) -def test_user_event_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, - scopes=None, - client_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_user_event_service_client_client_options_from_dict(): - with mock.patch('google.cloud.discoveryengine_v1beta.services.user_event_service.transports.UserEventServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = UserEventServiceClient( - 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", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport, "grpc", grpc_helpers), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_user_event_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, - scopes=None, - client_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - user_event_service.WriteUserEventRequest, - dict, -]) -def test_write_user_event(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = user_event.UserEvent( - event_type='event_type_value', - user_pseudo_id='user_pseudo_id_value', - direct_user_request=True, - session_id='session_id_value', - attribution_token='attribution_token_value', - filter='filter_value', - tag_ids=['tag_ids_value'], - promotion_ids=['promotion_ids_value'], - ) - response = client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, user_event.UserEvent) - assert response.event_type == 'event_type_value' - assert response.user_pseudo_id == 'user_pseudo_id_value' - assert response.direct_user_request is True - assert response.session_id == 'session_id_value' - assert response.attribution_token == 'attribution_token_value' - assert response.filter == 'filter_value' - assert response.tag_ids == ['tag_ids_value'] - assert response.promotion_ids == ['promotion_ids_value'] - - -def test_write_user_event_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - client.write_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - -@pytest.mark.asyncio -async def test_write_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.WriteUserEventRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent( - event_type='event_type_value', - user_pseudo_id='user_pseudo_id_value', - direct_user_request=True, - session_id='session_id_value', - attribution_token='attribution_token_value', - filter='filter_value', - tag_ids=['tag_ids_value'], - promotion_ids=['promotion_ids_value'], - )) - response = await client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.WriteUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, user_event.UserEvent) - assert response.event_type == 'event_type_value' - assert response.user_pseudo_id == 'user_pseudo_id_value' - assert response.direct_user_request is True - assert response.session_id == 'session_id_value' - assert response.attribution_token == 'attribution_token_value' - assert response.filter == 'filter_value' - assert response.tag_ids == ['tag_ids_value'] - assert response.promotion_ids == ['promotion_ids_value'] - - -@pytest.mark.asyncio -async def test_write_user_event_async_from_dict(): - await test_write_user_event_async(request_type=dict) - - -def test_write_user_event_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.WriteUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - call.return_value = user_event.UserEvent() - client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_write_user_event_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.WriteUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.write_user_event), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(user_event.UserEvent()) - await client.write_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - user_event_service.CollectUserEventRequest, - dict, -]) -def test_collect_user_event(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - ) - response = client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -def test_collect_user_event_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - client.collect_user_event() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - -@pytest.mark.asyncio -async def test_collect_user_event_async(transport: str = 'grpc_asyncio', request_type=user_event_service.CollectUserEventRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - )) - response = await client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == user_event_service.CollectUserEventRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -@pytest.mark.asyncio -async def test_collect_user_event_async_from_dict(): - await test_collect_user_event_async(request_type=dict) - - -def test_collect_user_event_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.CollectUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - call.return_value = httpbody_pb2.HttpBody() - client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_collect_user_event_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = user_event_service.CollectUserEventRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.collect_user_event), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody()) - await client.collect_user_event(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportUserEventsRequest, - dict, -]) -def test_import_user_events(request_type, transport: str = 'grpc'): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_import_user_events_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - client.import_user_events() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - -@pytest.mark.asyncio -async def test_import_user_events_async(transport: str = 'grpc_asyncio', request_type=import_config.ImportUserEventsRequest): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__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_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == import_config.ImportUserEventsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_import_user_events_async_from_dict(): - await test_import_user_events_async(request_type=dict) - - -def test_import_user_events_field_headers(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_import_user_events_field_headers_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = import_config.ImportUserEventsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_user_events), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.import_user_events(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - user_event_service.WriteUserEventRequest, - dict, -]) -def test_write_user_event_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - request_init["user_event"] = {'event_type': 'event_type_value', 'user_pseudo_id': 'user_pseudo_id_value', 'event_time': {'seconds': 751, 'nanos': 543}, 'user_info': {'user_id': 'user_id_value', 'user_agent': 'user_agent_value'}, 'direct_user_request': True, 'session_id': 'session_id_value', 'page_info': {'pageview_id': 'pageview_id_value', 'page_category': 'page_category_value', 'uri': 'uri_value', 'referrer_uri': 'referrer_uri_value'}, 'attribution_token': 'attribution_token_value', 'filter': 'filter_value', 'documents': [{'id': 'id_value', 'name': 'name_value', 'uri': 'uri_value', 'quantity': 895, 'promotion_ids': ['promotion_ids_value1', 'promotion_ids_value2']}], 'panel': {'panel_id': 'panel_id_value', 'display_name': 'display_name_value', 'panel_position': 1508, 'total_panels': 1286}, 'search_info': {'search_query': 'search_query_value', 'order_by': 'order_by_value', 'offset': 647}, 'completion_info': {'selected_suggestion': 'selected_suggestion_value', 'selected_position': 1821}, 'transaction_info': {'value': 0.541, 'currency': 'currency_value', 'transaction_id': 'transaction_id_value', 'tax': 0.333, 'cost': 0.441, 'discount_value': 0.1509}, 'tag_ids': ['tag_ids_value1', 'tag_ids_value2'], 'promotion_ids': ['promotion_ids_value1', 'promotion_ids_value2'], 'attributes': {}, 'media_info': {'media_progress_duration': {'seconds': 751, 'nanos': 543}, 'media_progress_percentage': 0.2641}} - # 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 = user_event_service.WriteUserEventRequest.meta.fields["user_event"] - - 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_event"].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_event"][field])): - del request_init["user_event"][field][i][subfield] - else: - del request_init["user_event"][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 = user_event.UserEvent( - event_type='event_type_value', - user_pseudo_id='user_pseudo_id_value', - direct_user_request=True, - session_id='session_id_value', - attribution_token='attribution_token_value', - filter='filter_value', - tag_ids=['tag_ids_value'], - promotion_ids=['promotion_ids_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 = user_event.UserEvent.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.write_user_event(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, user_event.UserEvent) - assert response.event_type == 'event_type_value' - assert response.user_pseudo_id == 'user_pseudo_id_value' - assert response.direct_user_request is True - assert response.session_id == 'session_id_value' - assert response.attribution_token == 'attribution_token_value' - assert response.filter == 'filter_value' - assert response.tag_ids == ['tag_ids_value'] - assert response.promotion_ids == ['promotion_ids_value'] - - -def test_write_user_event_rest_required_fields(request_type=user_event_service.WriteUserEventRequest): - transport_class = transports.UserEventServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).write_user_event._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).write_user_event._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = user_event.UserEvent() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 = user_event.UserEvent.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.write_user_event(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_write_user_event_rest_unset_required_fields(): - transport = transports.UserEventServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.write_user_event._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "userEvent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_write_user_event_rest_interceptors(null_interceptor): - transport = transports.UserEventServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.UserEventServiceRestInterceptor(), - ) - client = UserEventServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.UserEventServiceRestInterceptor, "post_write_user_event") as post, \ - mock.patch.object(transports.UserEventServiceRestInterceptor, "pre_write_user_event") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = user_event_service.WriteUserEventRequest.pb(user_event_service.WriteUserEventRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = user_event.UserEvent.to_json(user_event.UserEvent()) - - request = user_event_service.WriteUserEventRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = user_event.UserEvent() - - client.write_user_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_write_user_event_rest_bad_request(transport: str = 'rest', request_type=user_event_service.WriteUserEventRequest): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.write_user_event(request) - - -def test_write_user_event_rest_error(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - user_event_service.CollectUserEventRequest, - dict, -]) -def test_collect_user_event_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/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 = httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.collect_user_event(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -def test_collect_user_event_rest_required_fields(request_type=user_event_service.CollectUserEventRequest): - transport_class = transports.UserEventServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["user_event"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "userEvent" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).collect_user_event._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "userEvent" in jsonified_request - assert jsonified_request["userEvent"] == request_init["user_event"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["userEvent"] = 'user_event_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).collect_user_event._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("ets", "uri", "user_event", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "userEvent" in jsonified_request - assert jsonified_request["userEvent"] == 'user_event_value' - - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = httpbody_pb2.HttpBody() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force 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 - - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.collect_user_event(request) - - expected_params = [ - ( - "userEvent", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_collect_user_event_rest_unset_required_fields(): - transport = transports.UserEventServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.collect_user_event._get_unset_required_fields({}) - assert set(unset_fields) == (set(("ets", "uri", "userEvent", )) & set(("parent", "userEvent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_collect_user_event_rest_interceptors(null_interceptor): - transport = transports.UserEventServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.UserEventServiceRestInterceptor(), - ) - client = UserEventServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.UserEventServiceRestInterceptor, "post_collect_user_event") as post, \ - mock.patch.object(transports.UserEventServiceRestInterceptor, "pre_collect_user_event") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = user_event_service.CollectUserEventRequest.pb(user_event_service.CollectUserEventRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(httpbody_pb2.HttpBody()) - - request = user_event_service.CollectUserEventRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = httpbody_pb2.HttpBody() - - client.collect_user_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_collect_user_event_rest_bad_request(transport: str = 'rest', request_type=user_event_service.CollectUserEventRequest): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.collect_user_event(request) - - -def test_collect_user_event_rest_error(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - import_config.ImportUserEventsRequest, - dict, -]) -def test_import_user_events_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.import_user_events(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_import_user_events_rest_required_fields(request_type=import_config.ImportUserEventsRequest): - transport_class = transports.UserEventServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_user_events._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_user_events._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.import_user_events(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_import_user_events_rest_unset_required_fields(): - transport = transports.UserEventServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.import_user_events._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_import_user_events_rest_interceptors(null_interceptor): - transport = transports.UserEventServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.UserEventServiceRestInterceptor(), - ) - client = UserEventServiceClient(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.UserEventServiceRestInterceptor, "post_import_user_events") as post, \ - mock.patch.object(transports.UserEventServiceRestInterceptor, "pre_import_user_events") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = import_config.ImportUserEventsRequest.pb(import_config.ImportUserEventsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = import_config.ImportUserEventsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.import_user_events(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_import_user_events_rest_bad_request(transport: str = 'rest', request_type=import_config.ImportUserEventsRequest): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/dataStores/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.import_user_events(request) - - -def test_import_user_events_rest_error(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = UserEventServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = UserEventServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.UserEventServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.UserEventServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, - transports.UserEventServiceRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = UserEventServiceClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.UserEventServiceGrpcTransport, - ) - -def test_user_event_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.UserEventServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_user_event_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.discoveryengine_v1beta.services.user_event_service.transports.UserEventServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.UserEventServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'write_user_event', - 'collect_user_event', - 'import_user_events', - 'get_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_user_event_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.discoveryengine_v1beta.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.UserEventServiceTransport( - 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_user_event_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.discoveryengine_v1beta.services.user_event_service.transports.UserEventServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.UserEventServiceTransport() - adc.assert_called_once() - - -def test_user_event_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) - UserEventServiceClient() - 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.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, - ], -) -def test_user_event_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.UserEventServiceGrpcTransport, - transports.UserEventServiceGrpcAsyncIOTransport, - transports.UserEventServiceRestTransport, - ], -) -def test_user_event_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.UserEventServiceGrpcTransport, grpc_helpers), - (transports.UserEventServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_user_event_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( - "discoveryengine.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="discoveryengine.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_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_user_event_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.UserEventServiceRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_user_event_service_rest_lro_client(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_user_event_service_host_no_port(transport_name): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_user_event_service_host_with_port(transport_name): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'discoveryengine.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_user_event_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = UserEventServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = UserEventServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.write_user_event._session - session2 = client2.transport.write_user_event._session - assert session1 != session2 - session1 = client1.transport.collect_user_event._session - session2 = client2.transport.collect_user_event._session - assert session1 != session2 - session1 = client1.transport.import_user_events._session - session2 = client2.transport.import_user_events._session - assert session1 != session2 -def test_user_event_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.UserEventServiceGrpcTransport( - 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_user_event_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.UserEventServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_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.UserEventServiceGrpcTransport, transports.UserEventServiceGrpcAsyncIOTransport]) -def test_user_event_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_user_event_service_grpc_lro_client(): - client = UserEventServiceClient( - 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_user_event_service_grpc_lro_async_client(): - client = UserEventServiceAsyncClient( - 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_data_store_path(): - project = "squid" - location = "clam" - data_store = "whelk" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) - actual = UserEventServiceClient.data_store_path(project, location, data_store) - assert expected == actual - - -def test_parse_data_store_path(): - expected = { - "project": "octopus", - "location": "oyster", - "data_store": "nudibranch", - } - path = UserEventServiceClient.data_store_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_data_store_path(path) - assert expected == actual - -def test_document_path(): - project = "cuttlefish" - location = "mussel" - data_store = "winkle" - branch = "nautilus" - document = "scallop" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(project=project, location=location, data_store=data_store, branch=branch, document=document, ) - actual = UserEventServiceClient.document_path(project, location, data_store, branch, document) - assert expected == actual - - -def test_parse_document_path(): - expected = { - "project": "abalone", - "location": "squid", - "data_store": "clam", - "branch": "whelk", - "document": "octopus", - } - path = UserEventServiceClient.document_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_document_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = UserEventServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = UserEventServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = UserEventServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = UserEventServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = UserEventServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = UserEventServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = UserEventServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = UserEventServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "squid" - location = "clam" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = UserEventServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = UserEventServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = UserEventServiceClient.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.UserEventServiceTransport, '_prep_wrapped_messages') as prep: - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.UserEventServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = UserEventServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_get_operation(transport: str = "grpc"): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc"): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = UserEventServiceClient( - 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 = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.ListOperationsResponse() - response = client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) -@pytest.mark.asyncio -async def test_list_operations_async(transport: str = "grpc"): - client = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = UserEventServiceClient( - 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 = UserEventServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = UserEventServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = UserEventServiceClient( - 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", [ - (UserEventServiceClient, transports.UserEventServiceGrpcTransport), - (UserEventServiceAsyncClient, transports.UserEventServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/data_store_service.rst b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1alpha/data_store_service.rst similarity index 100% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/data_store_service.rst rename to packages/google-cloud-discoveryengine/docs/discoveryengine_v1alpha/data_store_service.rst diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/engine_service.rst b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1alpha/engine_service.rst similarity index 100% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/docs/discoveryengine_v1alpha/engine_service.rst rename to packages/google-cloud-discoveryengine/docs/discoveryengine_v1alpha/engine_service.rst diff --git a/packages/google-cloud-discoveryengine/docs/discoveryengine_v1alpha/services_.rst b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1alpha/services_.rst index d2067692b199..0177e984c5cc 100644 --- a/packages/google-cloud-discoveryengine/docs/discoveryengine_v1alpha/services_.rst +++ b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1alpha/services_.rst @@ -5,7 +5,9 @@ Services for Google Cloud Discoveryengine v1alpha API completion_service conversational_search_service + data_store_service document_service + engine_service recommendation_service schema_service search_service diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/__init__.py index fc49b0fd0899..ce8cddfd715b 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/__init__.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/__init__.py @@ -26,7 +26,12 @@ ConversationalSearchServiceAsyncClient, ConversationalSearchServiceClient, ) +from .services.data_store_service import ( + DataStoreServiceAsyncClient, + DataStoreServiceClient, +) from .services.document_service import DocumentServiceAsyncClient, DocumentServiceClient +from .services.engine_service import EngineServiceAsyncClient, EngineServiceClient from .services.recommendation_service import ( RecommendationServiceAsyncClient, RecommendationServiceClient, @@ -41,7 +46,16 @@ UserEventServiceAsyncClient, UserEventServiceClient, ) -from .types.common import CustomAttribute, DoubleList, Interval, SolutionType, UserInfo +from .types.common import ( + CustomAttribute, + DoubleList, + IndustryVertical, + Interval, + SearchAddOn, + SearchTier, + SolutionType, + UserInfo, +) from .types.completion_service import CompleteQueryRequest, CompleteQueryResponse from .types.conversation import ( Conversation, @@ -60,6 +74,17 @@ ListConversationsResponse, UpdateConversationRequest, ) +from .types.data_store import DataStore +from .types.data_store_service import ( + CreateDataStoreMetadata, + CreateDataStoreRequest, + DeleteDataStoreMetadata, + DeleteDataStoreRequest, + GetDataStoreRequest, + ListDataStoresRequest, + ListDataStoresResponse, + UpdateDataStoreRequest, +) from .types.document import Document from .types.document_service import ( CreateDocumentRequest, @@ -69,6 +94,22 @@ ListDocumentsResponse, UpdateDocumentRequest, ) +from .types.engine import Engine +from .types.engine_service import ( + CreateEngineMetadata, + CreateEngineRequest, + DeleteEngineMetadata, + DeleteEngineRequest, + GetEngineRequest, + ListEnginesRequest, + ListEnginesResponse, + PauseEngineRequest, + ResumeEngineRequest, + TuneEngineMetadata, + TuneEngineRequest, + TuneEngineResponse, + UpdateEngineRequest, +) from .types.import_config import ( BigQuerySource, GcsSource, @@ -122,7 +163,9 @@ __all__ = ( "CompletionServiceAsyncClient", "ConversationalSearchServiceAsyncClient", + "DataStoreServiceAsyncClient", "DocumentServiceAsyncClient", + "EngineServiceAsyncClient", "RecommendationServiceAsyncClient", "SchemaServiceAsyncClient", "SearchServiceAsyncClient", @@ -141,22 +184,36 @@ "ConverseConversationRequest", "ConverseConversationResponse", "CreateConversationRequest", + "CreateDataStoreMetadata", + "CreateDataStoreRequest", "CreateDocumentRequest", + "CreateEngineMetadata", + "CreateEngineRequest", "CreateSchemaMetadata", "CreateSchemaRequest", "CustomAttribute", + "DataStore", + "DataStoreServiceClient", "DeleteConversationRequest", + "DeleteDataStoreMetadata", + "DeleteDataStoreRequest", "DeleteDocumentRequest", + "DeleteEngineMetadata", + "DeleteEngineRequest", "DeleteSchemaMetadata", "DeleteSchemaRequest", "Document", "DocumentInfo", "DocumentServiceClient", "DoubleList", + "Engine", + "EngineServiceClient", "FieldConfig", "GcsSource", "GetConversationRequest", + "GetDataStoreRequest", "GetDocumentRequest", + "GetEngineRequest", "GetSchemaRequest", "ImportDocumentsMetadata", "ImportDocumentsRequest", @@ -165,16 +222,22 @@ "ImportUserEventsMetadata", "ImportUserEventsRequest", "ImportUserEventsResponse", + "IndustryVertical", "Interval", "ListConversationsRequest", "ListConversationsResponse", + "ListDataStoresRequest", + "ListDataStoresResponse", "ListDocumentsRequest", "ListDocumentsResponse", + "ListEnginesRequest", + "ListEnginesResponse", "ListSchemasRequest", "ListSchemasResponse", "MediaInfo", "PageInfo", "PanelInfo", + "PauseEngineRequest", "PurgeDocumentsMetadata", "PurgeDocumentsRequest", "PurgeDocumentsResponse", @@ -188,18 +251,26 @@ "RecrawlUrisRequest", "RecrawlUrisResponse", "Reply", + "ResumeEngineRequest", "Schema", "SchemaServiceClient", + "SearchAddOn", "SearchInfo", "SearchRequest", "SearchResponse", "SearchServiceClient", + "SearchTier", "SiteSearchEngineServiceClient", "SolutionType", "TextInput", "TransactionInfo", + "TuneEngineMetadata", + "TuneEngineRequest", + "TuneEngineResponse", "UpdateConversationRequest", + "UpdateDataStoreRequest", "UpdateDocumentRequest", + "UpdateEngineRequest", "UpdateSchemaMetadata", "UpdateSchemaRequest", "UserEvent", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/gapic_metadata.json b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/gapic_metadata.json index bb1a5785b349..6d78899820ae 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/gapic_metadata.json +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/gapic_metadata.json @@ -148,6 +148,100 @@ } } }, + "DataStoreService": { + "clients": { + "grpc": { + "libraryClient": "DataStoreServiceClient", + "rpcs": { + "CreateDataStore": { + "methods": [ + "create_data_store" + ] + }, + "DeleteDataStore": { + "methods": [ + "delete_data_store" + ] + }, + "GetDataStore": { + "methods": [ + "get_data_store" + ] + }, + "ListDataStores": { + "methods": [ + "list_data_stores" + ] + }, + "UpdateDataStore": { + "methods": [ + "update_data_store" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DataStoreServiceAsyncClient", + "rpcs": { + "CreateDataStore": { + "methods": [ + "create_data_store" + ] + }, + "DeleteDataStore": { + "methods": [ + "delete_data_store" + ] + }, + "GetDataStore": { + "methods": [ + "get_data_store" + ] + }, + "ListDataStores": { + "methods": [ + "list_data_stores" + ] + }, + "UpdateDataStore": { + "methods": [ + "update_data_store" + ] + } + } + }, + "rest": { + "libraryClient": "DataStoreServiceClient", + "rpcs": { + "CreateDataStore": { + "methods": [ + "create_data_store" + ] + }, + "DeleteDataStore": { + "methods": [ + "delete_data_store" + ] + }, + "GetDataStore": { + "methods": [ + "get_data_store" + ] + }, + "ListDataStores": { + "methods": [ + "list_data_stores" + ] + }, + "UpdateDataStore": { + "methods": [ + "update_data_store" + ] + } + } + } + } + }, "DocumentService": { "clients": { "grpc": { @@ -272,6 +366,145 @@ } } }, + "EngineService": { + "clients": { + "grpc": { + "libraryClient": "EngineServiceClient", + "rpcs": { + "CreateEngine": { + "methods": [ + "create_engine" + ] + }, + "DeleteEngine": { + "methods": [ + "delete_engine" + ] + }, + "GetEngine": { + "methods": [ + "get_engine" + ] + }, + "ListEngines": { + "methods": [ + "list_engines" + ] + }, + "PauseEngine": { + "methods": [ + "pause_engine" + ] + }, + "ResumeEngine": { + "methods": [ + "resume_engine" + ] + }, + "TuneEngine": { + "methods": [ + "tune_engine" + ] + }, + "UpdateEngine": { + "methods": [ + "update_engine" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EngineServiceAsyncClient", + "rpcs": { + "CreateEngine": { + "methods": [ + "create_engine" + ] + }, + "DeleteEngine": { + "methods": [ + "delete_engine" + ] + }, + "GetEngine": { + "methods": [ + "get_engine" + ] + }, + "ListEngines": { + "methods": [ + "list_engines" + ] + }, + "PauseEngine": { + "methods": [ + "pause_engine" + ] + }, + "ResumeEngine": { + "methods": [ + "resume_engine" + ] + }, + "TuneEngine": { + "methods": [ + "tune_engine" + ] + }, + "UpdateEngine": { + "methods": [ + "update_engine" + ] + } + } + }, + "rest": { + "libraryClient": "EngineServiceClient", + "rpcs": { + "CreateEngine": { + "methods": [ + "create_engine" + ] + }, + "DeleteEngine": { + "methods": [ + "delete_engine" + ] + }, + "GetEngine": { + "methods": [ + "get_engine" + ] + }, + "ListEngines": { + "methods": [ + "list_engines" + ] + }, + "PauseEngine": { + "methods": [ + "pause_engine" + ] + }, + "ResumeEngine": { + "methods": [ + "resume_engine" + ] + }, + "TuneEngine": { + "methods": [ + "tune_engine" + ] + }, + "UpdateEngine": { + "methods": [ + "update_engine" + ] + } + } + } + } + }, "RecommendationService": { "clients": { "grpc": { diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/data_store_service/__init__.py similarity index 91% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/__init__.py rename to packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/data_store_service/__init__.py index 0411e2029431..ff4ce7fbfad6 100644 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/__init__.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/data_store_service/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .client import DataStoreServiceClient from .async_client import DataStoreServiceAsyncClient +from .client import DataStoreServiceClient __all__ = ( - 'DataStoreServiceClient', - 'DataStoreServiceAsyncClient', + "DataStoreServiceClient", + "DataStoreServiceAsyncClient", ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/data_store_service/async_client.py similarity index 86% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/async_client.py rename to packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/data_store_service/async_client.py index 6bc8835ec9a9..4609db010a31 100644 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/async_client.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/data_store_service/async_client.py @@ -16,16 +16,26 @@ from collections import OrderedDict import functools import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.discoveryengine_v1alpha import gapic_version as package_version +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) -from google.api_core.client_options import ClientOptions from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +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.discoveryengine_v1alpha import gapic_version as package_version try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] @@ -34,19 +44,21 @@ from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + from google.cloud.discoveryengine_v1alpha.services.data_store_service import pagers +from google.cloud.discoveryengine_v1alpha.types import data_store as gcd_data_store from google.cloud.discoveryengine_v1alpha.types import common from google.cloud.discoveryengine_v1alpha.types import data_store -from google.cloud.discoveryengine_v1alpha.types import data_store as gcd_data_store from google.cloud.discoveryengine_v1alpha.types import data_store_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import DataStoreServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import DataStoreServiceGrpcAsyncIOTransport + from .client import DataStoreServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, DataStoreServiceTransport +from .transports.grpc_asyncio import DataStoreServiceGrpcAsyncIOTransport class DataStoreServiceAsyncClient: @@ -64,16 +76,30 @@ class DataStoreServiceAsyncClient: parse_collection_path = staticmethod(DataStoreServiceClient.parse_collection_path) data_store_path = staticmethod(DataStoreServiceClient.data_store_path) parse_data_store_path = staticmethod(DataStoreServiceClient.parse_data_store_path) - common_billing_account_path = staticmethod(DataStoreServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(DataStoreServiceClient.parse_common_billing_account_path) + common_billing_account_path = staticmethod( + DataStoreServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + DataStoreServiceClient.parse_common_billing_account_path + ) common_folder_path = staticmethod(DataStoreServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(DataStoreServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(DataStoreServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(DataStoreServiceClient.parse_common_organization_path) + parse_common_folder_path = staticmethod( + DataStoreServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + DataStoreServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + DataStoreServiceClient.parse_common_organization_path + ) common_project_path = staticmethod(DataStoreServiceClient.common_project_path) - parse_common_project_path = staticmethod(DataStoreServiceClient.parse_common_project_path) + parse_common_project_path = staticmethod( + DataStoreServiceClient.parse_common_project_path + ) common_location_path = staticmethod(DataStoreServiceClient.common_location_path) - parse_common_location_path = staticmethod(DataStoreServiceClient.parse_common_location_path) + parse_common_location_path = staticmethod( + DataStoreServiceClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -109,7 +135,9 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + 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: @@ -151,14 +179,18 @@ def transport(self) -> DataStoreServiceTransport: """ return self._client.transport - get_transport_class = functools.partial(type(DataStoreServiceClient).get_transport_class, type(DataStoreServiceClient)) + get_transport_class = functools.partial( + type(DataStoreServiceClient).get_transport_class, type(DataStoreServiceClient) + ) - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, DataStoreServiceTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, DataStoreServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the data store service client. Args: @@ -196,19 +228,21 @@ def __init__(self, *, transport=transport, client_options=client_options, client_info=client_info, - ) - async def create_data_store(self, - request: Optional[Union[data_store_service.CreateDataStoreRequest, dict]] = None, - *, - parent: Optional[str] = None, - data_store: Optional[gcd_data_store.DataStore] = None, - data_store_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: + async def create_data_store( + self, + request: Optional[ + Union[data_store_service.CreateDataStoreRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + data_store: Optional[gcd_data_store.DataStore] = None, + data_store_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: r"""Creates a [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]. @@ -309,8 +343,10 @@ async def sample_create_data_store(): # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, data_store, data_store_id]) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = data_store_service.CreateDataStoreRequest(request) @@ -334,9 +370,7 @@ async def sample_create_data_store(): # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Send the request. @@ -358,14 +392,15 @@ async def sample_create_data_store(): # Done; return the response. return response - async def get_data_store(self, - request: Optional[Union[data_store_service.GetDataStoreRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> data_store.DataStore: + async def get_data_store( + self, + request: Optional[Union[data_store_service.GetDataStoreRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> data_store.DataStore: r"""Gets a [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]. @@ -435,8 +470,10 @@ async def sample_get_data_store(): # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = data_store_service.GetDataStoreRequest(request) @@ -456,9 +493,7 @@ async def sample_get_data_store(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. @@ -472,14 +507,15 @@ async def sample_get_data_store(): # Done; return the response. return response - async def list_data_stores(self, - request: Optional[Union[data_store_service.ListDataStoresRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDataStoresAsyncPager: + async def list_data_stores( + self, + request: Optional[Union[data_store_service.ListDataStoresRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDataStoresAsyncPager: r"""Lists all the [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]s associated with the project. @@ -549,8 +585,10 @@ async def sample_list_data_stores(): # gotten any keyword arguments that map to the request. has_flattened_params = any([parent]) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = data_store_service.ListDataStoresRequest(request) @@ -570,9 +608,7 @@ async def sample_list_data_stores(): # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Send the request. @@ -595,14 +631,17 @@ async def sample_list_data_stores(): # Done; return the response. return response - async def delete_data_store(self, - request: Optional[Union[data_store_service.DeleteDataStoreRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: + async def delete_data_store( + self, + request: Optional[ + Union[data_store_service.DeleteDataStoreRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: r"""Deletes a [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]. @@ -686,8 +725,10 @@ async def sample_delete_data_store(): # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = data_store_service.DeleteDataStoreRequest(request) @@ -707,9 +748,7 @@ async def sample_delete_data_store(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. @@ -731,15 +770,18 @@ async def sample_delete_data_store(): # Done; return the response. return response - async def update_data_store(self, - request: Optional[Union[data_store_service.UpdateDataStoreRequest, dict]] = None, - *, - data_store: Optional[gcd_data_store.DataStore] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_data_store.DataStore: + async def update_data_store( + self, + request: Optional[ + Union[data_store_service.UpdateDataStoreRequest, dict] + ] = None, + *, + data_store: Optional[gcd_data_store.DataStore] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_data_store.DataStore: r"""Updates a [DataStore][google.cloud.discoveryengine.v1alpha.DataStore] @@ -822,8 +864,10 @@ async def sample_update_data_store(): # gotten any keyword arguments that map to the request. has_flattened_params = any([data_store, update_mask]) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = data_store_service.UpdateDataStoreRequest(request) @@ -845,9 +889,9 @@ async def sample_update_data_store(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("data_store.name", request.data_store.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("data_store.name", request.data_store.name),) + ), ) # Send the request. @@ -901,13 +945,16 @@ async def 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.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -952,13 +999,16 @@ async def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -969,9 +1019,10 @@ async def __aenter__(self) -> "DataStoreServiceAsyncClient": async def __aexit__(self, exc_type, exc, tb): await self.transport.close() -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - -__all__ = ( - "DataStoreServiceAsyncClient", +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ ) + + +__all__ = ("DataStoreServiceAsyncClient",) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/data_store_service/client.py similarity index 83% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/client.py rename to packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/data_store_service/client.py index f400ac0a667d..449f463d2755 100644 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/client.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/data_store_service/client.py @@ -16,19 +16,30 @@ from collections import OrderedDict import os import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.discoveryengine_v1alpha import gapic_version as package_version +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore +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.discoveryengine_v1alpha import gapic_version as package_version try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] @@ -37,17 +48,19 @@ from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + from google.cloud.discoveryengine_v1alpha.services.data_store_service import pagers +from google.cloud.discoveryengine_v1alpha.types import data_store as gcd_data_store from google.cloud.discoveryengine_v1alpha.types import common from google.cloud.discoveryengine_v1alpha.types import data_store -from google.cloud.discoveryengine_v1alpha.types import data_store as gcd_data_store from google.cloud.discoveryengine_v1alpha.types import data_store_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import DataStoreServiceTransport, DEFAULT_CLIENT_INFO + +from .transports.base import DEFAULT_CLIENT_INFO, DataStoreServiceTransport from .transports.grpc import DataStoreServiceGrpcTransport from .transports.grpc_asyncio import DataStoreServiceGrpcAsyncIOTransport from .transports.rest import DataStoreServiceRestTransport @@ -60,14 +73,18 @@ class DataStoreServiceClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ - _transport_registry = OrderedDict() # type: Dict[str, Type[DataStoreServiceTransport]] + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[DataStoreServiceTransport]] _transport_registry["grpc"] = DataStoreServiceGrpcTransport _transport_registry["grpc_asyncio"] = DataStoreServiceGrpcAsyncIOTransport _transport_registry["rest"] = DataStoreServiceRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[DataStoreServiceTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[DataStoreServiceTransport]: """Returns an appropriate transport class. Args: @@ -158,8 +175,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: DataStoreServiceClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file( - filename) + credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -176,84 +192,132 @@ def transport(self) -> DataStoreServiceTransport: return self._transport @staticmethod - def collection_path(project: str,location: str,collection: str,) -> str: + def collection_path( + project: str, + location: str, + collection: str, + ) -> str: """Returns a fully-qualified collection string.""" - return "projects/{project}/locations/{location}/collections/{collection}".format(project=project, location=location, collection=collection, ) + return ( + "projects/{project}/locations/{location}/collections/{collection}".format( + project=project, + location=location, + collection=collection, + ) + ) @staticmethod - def parse_collection_path(path: str) -> Dict[str,str]: + def parse_collection_path(path: str) -> Dict[str, str]: """Parses a collection path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/collections/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/collections/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def data_store_path(project: str,location: str,data_store: str,) -> str: + def data_store_path( + project: str, + location: str, + data_store: str, + ) -> str: """Returns a fully-qualified data_store string.""" - return "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) + return "projects/{project}/locations/{location}/dataStores/{data_store}".format( + project=project, + location=location, + data_store=data_store, + ) @staticmethod - def parse_data_store_path(path: str) -> Dict[str,str]: + def parse_data_store_path(path: str) -> Dict[str, str]: """Parses a data_store path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: + 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, ) + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: + 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: + def common_folder_path( + folder: str, + ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) + return "folders/{folder}".format( + folder=folder, + ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: + 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: + def common_organization_path( + organization: str, + ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) + return "organizations/{organization}".format( + organization=organization, + ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: + 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: + def common_project_path( + project: str, + ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) + return "projects/{project}".format( + project=project, + ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: + 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: + 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, ) + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: + 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): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): """Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -289,9 +353,13 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + 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 @@ -304,19 +372,23 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # 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): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): api_endpoint = cls.DEFAULT_MTLS_ENDPOINT else: api_endpoint = cls.DEFAULT_ENDPOINT return api_endpoint, client_cert_source - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, DataStoreServiceTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, DataStoreServiceTransport]] = 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 store service client. Args: @@ -360,11 +432,15 @@ def __init__(self, *, client_options = client_options_lib.ClientOptions() client_options = cast(client_options_lib.ClientOptions, client_options) - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( + client_options + ) api_key_value = getattr(client_options, "api_key", None) if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") + 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 @@ -372,8 +448,10 @@ def __init__(self, *, if isinstance(transport, DataStoreServiceTransport): # transport is a DataStoreServiceTransport instance. if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) if client_options.scopes: raise ValueError( "When providing a transport instance, provide its scopes " @@ -383,8 +461,12 @@ def __init__(self, *, else: import google.auth._default # type: ignore - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) Transport = type(self).get_transport_class(transport) self._transport = Transport( @@ -399,16 +481,19 @@ def __init__(self, *, api_audience=client_options.api_audience, ) - def create_data_store(self, - request: Optional[Union[data_store_service.CreateDataStoreRequest, dict]] = None, - *, - parent: Optional[str] = None, - data_store: Optional[gcd_data_store.DataStore] = None, - data_store_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: + def create_data_store( + self, + request: Optional[ + Union[data_store_service.CreateDataStoreRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + data_store: Optional[gcd_data_store.DataStore] = None, + data_store_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: r"""Creates a [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]. @@ -509,8 +594,10 @@ def sample_create_data_store(): # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, data_store, data_store_id]) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # Minor optimization to avoid making a copy if the user passes # in a data_store_service.CreateDataStoreRequest. @@ -531,12 +618,10 @@ def sample_create_data_store(): # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.create_data_store] - # Certain fields should be provided within the metadata header; + # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Send the request. @@ -558,14 +643,15 @@ def sample_create_data_store(): # Done; return the response. return response - def get_data_store(self, - request: Optional[Union[data_store_service.GetDataStoreRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> data_store.DataStore: + def get_data_store( + self, + request: Optional[Union[data_store_service.GetDataStoreRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> data_store.DataStore: r"""Gets a [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]. @@ -635,8 +721,10 @@ def sample_get_data_store(): # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # Minor optimization to avoid making a copy if the user passes # in a data_store_service.GetDataStoreRequest. @@ -653,12 +741,10 @@ def sample_get_data_store(): # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.get_data_store] - # Certain fields should be provided within the metadata header; + # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. @@ -672,14 +758,15 @@ def sample_get_data_store(): # Done; return the response. return response - def list_data_stores(self, - request: Optional[Union[data_store_service.ListDataStoresRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListDataStoresPager: + def list_data_stores( + self, + request: Optional[Union[data_store_service.ListDataStoresRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListDataStoresPager: r"""Lists all the [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]s associated with the project. @@ -749,8 +836,10 @@ def sample_list_data_stores(): # gotten any keyword arguments that map to the request. has_flattened_params = any([parent]) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # Minor optimization to avoid making a copy if the user passes # in a data_store_service.ListDataStoresRequest. @@ -767,12 +856,10 @@ def sample_list_data_stores(): # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.list_data_stores] - # Certain fields should be provided within the metadata header; + # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Send the request. @@ -795,14 +882,17 @@ def sample_list_data_stores(): # Done; return the response. return response - def delete_data_store(self, - request: Optional[Union[data_store_service.DeleteDataStoreRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: + def delete_data_store( + self, + request: Optional[ + Union[data_store_service.DeleteDataStoreRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: r"""Deletes a [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]. @@ -886,8 +976,10 @@ def sample_delete_data_store(): # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # Minor optimization to avoid making a copy if the user passes # in a data_store_service.DeleteDataStoreRequest. @@ -904,12 +996,10 @@ def sample_delete_data_store(): # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.delete_data_store] - # Certain fields should be provided within the metadata header; + # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. @@ -931,15 +1021,18 @@ def sample_delete_data_store(): # Done; return the response. return response - def update_data_store(self, - request: Optional[Union[data_store_service.UpdateDataStoreRequest, dict]] = None, - *, - data_store: Optional[gcd_data_store.DataStore] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_data_store.DataStore: + def update_data_store( + self, + request: Optional[ + Union[data_store_service.UpdateDataStoreRequest, dict] + ] = None, + *, + data_store: Optional[gcd_data_store.DataStore] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_data_store.DataStore: r"""Updates a [DataStore][google.cloud.discoveryengine.v1alpha.DataStore] @@ -1022,8 +1115,10 @@ def sample_update_data_store(): # gotten any keyword arguments that map to the request. has_flattened_params = any([data_store, update_mask]) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # Minor optimization to avoid making a copy if the user passes # in a data_store_service.UpdateDataStoreRequest. @@ -1042,12 +1137,12 @@ def sample_update_data_store(): # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.update_data_store] - # Certain fields should be provided within the metadata header; + # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("data_store.name", request.data_store.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("data_store.name", request.data_store.name),) + ), ) # Send the request. @@ -1114,13 +1209,16 @@ def 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.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1165,29 +1263,24 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "DataStoreServiceClient", -) +__all__ = ("DataStoreServiceClient",) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/pagers.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/data_store_service/pagers.py similarity index 84% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/pagers.py rename to packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/data_store_service/pagers.py index e13cd9efb8de..e86bcc24425f 100644 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/pagers.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/data_store_service/pagers.py @@ -13,10 +13,18 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, +) -from google.cloud.discoveryengine_v1alpha.types import data_store -from google.cloud.discoveryengine_v1alpha.types import data_store_service +from google.cloud.discoveryengine_v1alpha.types import data_store, data_store_service class ListDataStoresPager: @@ -36,12 +44,15 @@ class ListDataStoresPager: 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[..., data_store_service.ListDataStoresResponse], - request: data_store_service.ListDataStoresRequest, - response: data_store_service.ListDataStoresResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): + + def __init__( + self, + method: Callable[..., data_store_service.ListDataStoresResponse], + request: data_store_service.ListDataStoresRequest, + response: data_store_service.ListDataStoresResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): """Instantiate the pager. Args: @@ -75,7 +86,7 @@ def __iter__(self) -> Iterator[data_store.DataStore]: yield from page.data_stores def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) class ListDataStoresAsyncPager: @@ -95,12 +106,15 @@ class ListDataStoresAsyncPager: 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[data_store_service.ListDataStoresResponse]], - request: data_store_service.ListDataStoresRequest, - response: data_store_service.ListDataStoresResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): + + def __init__( + self, + method: Callable[..., Awaitable[data_store_service.ListDataStoresResponse]], + request: data_store_service.ListDataStoresRequest, + response: data_store_service.ListDataStoresResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): """Instantiates the pager. Args: @@ -128,6 +142,7 @@ async def pages(self) -> AsyncIterator[data_store_service.ListDataStoresResponse self._request.page_token = self._response.next_page_token self._response = await self._method(self._request, metadata=self._metadata) yield self._response + def __aiter__(self) -> AsyncIterator[data_store.DataStore]: async def async_generator(): async for page in self.pages: @@ -137,4 +152,4 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/__init__.py similarity index 67% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/__init__.py rename to packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/__init__.py index 3bb6e679b823..6f5f07baebad 100644 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/__init__.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/__init__.py @@ -19,20 +19,18 @@ from .base import DataStoreServiceTransport from .grpc import DataStoreServiceGrpcTransport from .grpc_asyncio import DataStoreServiceGrpcAsyncIOTransport -from .rest import DataStoreServiceRestTransport -from .rest import DataStoreServiceRestInterceptor - +from .rest import DataStoreServiceRestInterceptor, DataStoreServiceRestTransport # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[DataStoreServiceTransport]] -_transport_registry['grpc'] = DataStoreServiceGrpcTransport -_transport_registry['grpc_asyncio'] = DataStoreServiceGrpcAsyncIOTransport -_transport_registry['rest'] = DataStoreServiceRestTransport +_transport_registry["grpc"] = DataStoreServiceGrpcTransport +_transport_registry["grpc_asyncio"] = DataStoreServiceGrpcAsyncIOTransport +_transport_registry["rest"] = DataStoreServiceRestTransport __all__ = ( - 'DataStoreServiceTransport', - 'DataStoreServiceGrpcTransport', - 'DataStoreServiceGrpcAsyncIOTransport', - 'DataStoreServiceRestTransport', - 'DataStoreServiceRestInterceptor', + "DataStoreServiceTransport", + "DataStoreServiceGrpcTransport", + "DataStoreServiceGrpcAsyncIOTransport", + "DataStoreServiceRestTransport", + "DataStoreServiceRestInterceptor", ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/base.py similarity index 64% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/base.py rename to packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/base.py index 2b728dcc7339..9a8b0ba5311f 100644 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/base.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/base.py @@ -16,46 +16,46 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.cloud.discoveryengine_v1alpha import gapic_version as package_version - -import google.auth # type: ignore import google.api_core from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 +from google.api_core import gapic_v1, operations_v1 from google.api_core import retry as retries -from google.api_core import operations_v1 +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore -from google.cloud.discoveryengine_v1alpha.types import data_store +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version from google.cloud.discoveryengine_v1alpha.types import data_store as gcd_data_store +from google.cloud.discoveryengine_v1alpha.types import data_store from google.cloud.discoveryengine_v1alpha.types import data_store_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) class DataStoreServiceTransport(abc.ABC): """Abstract transport class for DataStoreService.""" - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + DEFAULT_HOST: str = "discoveryengine.googleapis.com" - DEFAULT_HOST: str = 'discoveryengine.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: + 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: @@ -89,30 +89,38 @@ def __init__( # 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") + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + 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"): + 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' + if ":" not in host: + host += ":443" self._host = host def _prep_wrapped_messages(self, client_info): @@ -143,14 +151,14 @@ def _prep_wrapped_messages(self, client_info): 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! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @@ -160,48 +168,51 @@ def operations_client(self): raise NotImplementedError() @property - def create_data_store(self) -> Callable[ - [data_store_service.CreateDataStoreRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def create_data_store( + self, + ) -> Callable[ + [data_store_service.CreateDataStoreRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def get_data_store(self) -> Callable[ - [data_store_service.GetDataStoreRequest], - Union[ - data_store.DataStore, - Awaitable[data_store.DataStore] - ]]: + def get_data_store( + self, + ) -> Callable[ + [data_store_service.GetDataStoreRequest], + Union[data_store.DataStore, Awaitable[data_store.DataStore]], + ]: raise NotImplementedError() @property - def list_data_stores(self) -> Callable[ - [data_store_service.ListDataStoresRequest], - Union[ - data_store_service.ListDataStoresResponse, - Awaitable[data_store_service.ListDataStoresResponse] - ]]: + def list_data_stores( + self, + ) -> Callable[ + [data_store_service.ListDataStoresRequest], + Union[ + data_store_service.ListDataStoresResponse, + Awaitable[data_store_service.ListDataStoresResponse], + ], + ]: raise NotImplementedError() @property - def delete_data_store(self) -> Callable[ - [data_store_service.DeleteDataStoreRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def delete_data_store( + self, + ) -> Callable[ + [data_store_service.DeleteDataStoreRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def update_data_store(self) -> Callable[ - [data_store_service.UpdateDataStoreRequest], - Union[ - gcd_data_store.DataStore, - Awaitable[gcd_data_store.DataStore] - ]]: + def update_data_store( + self, + ) -> Callable[ + [data_store_service.UpdateDataStoreRequest], + Union[gcd_data_store.DataStore, Awaitable[gcd_data_store.DataStore]], + ]: raise NotImplementedError() @property @@ -209,7 +220,10 @@ def list_operations( self, ) -> Callable[ [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], ]: raise NotImplementedError() @@ -227,6 +241,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'DataStoreServiceTransport', -) +__all__ = ("DataStoreServiceTransport",) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/grpc.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/grpc.py similarity index 80% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/grpc.py rename to packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/grpc.py index 1c382863e8e6..56ae5d0c24f2 100644 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/grpc.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/grpc.py @@ -13,24 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore - +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore import grpc # type: ignore -from google.cloud.discoveryengine_v1alpha.types import data_store from google.cloud.discoveryengine_v1alpha.types import data_store as gcd_data_store +from google.cloud.discoveryengine_v1alpha.types import data_store from google.cloud.discoveryengine_v1alpha.types import data_store_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import DataStoreServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, DataStoreServiceTransport class DataStoreServiceGrpcTransport(DataStoreServiceTransport): @@ -47,23 +45,26 @@ class DataStoreServiceGrpcTransport(DataStoreServiceTransport): 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: + def __init__( + self, + *, + host: str = "discoveryengine.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -183,13 +184,15 @@ def __init__(self, *, self._prep_wrapped_messages(client_info) @classmethod - def create_channel(cls, - host: str = 'discoveryengine.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: + def create_channel( + cls, + host: str = "discoveryengine.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. @@ -224,13 +227,12 @@ def create_channel(cls, default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs + **kwargs, ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ + """Return the channel designed to connect to this service.""" return self._grpc_channel @property @@ -242,17 +244,17 @@ def operations_client(self) -> operations_v1.OperationsClient: """ # Quick check: Only create a new client if we do not already have one. if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) + self._operations_client = operations_v1.OperationsClient(self.grpc_channel) # Return the client from cache. return self._operations_client @property - def create_data_store(self) -> Callable[ - [data_store_service.CreateDataStoreRequest], - operations_pb2.Operation]: + def create_data_store( + self, + ) -> Callable[ + [data_store_service.CreateDataStoreRequest], operations_pb2.Operation + ]: r"""Return a callable for the create data store method over gRPC. Creates a @@ -274,18 +276,18 @@ def create_data_store(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_data_store' not in self._stubs: - self._stubs['create_data_store'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.DataStoreService/CreateDataStore', + if "create_data_store" not in self._stubs: + self._stubs["create_data_store"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.DataStoreService/CreateDataStore", request_serializer=data_store_service.CreateDataStoreRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['create_data_store'] + return self._stubs["create_data_store"] @property - def get_data_store(self) -> Callable[ - [data_store_service.GetDataStoreRequest], - data_store.DataStore]: + def get_data_store( + self, + ) -> Callable[[data_store_service.GetDataStoreRequest], data_store.DataStore]: r"""Return a callable for the get data store method over gRPC. Gets a @@ -301,18 +303,21 @@ def get_data_store(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_data_store' not in self._stubs: - self._stubs['get_data_store'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.DataStoreService/GetDataStore', + if "get_data_store" not in self._stubs: + self._stubs["get_data_store"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.DataStoreService/GetDataStore", request_serializer=data_store_service.GetDataStoreRequest.serialize, response_deserializer=data_store.DataStore.deserialize, ) - return self._stubs['get_data_store'] + return self._stubs["get_data_store"] @property - def list_data_stores(self) -> Callable[ - [data_store_service.ListDataStoresRequest], - data_store_service.ListDataStoresResponse]: + def list_data_stores( + self, + ) -> Callable[ + [data_store_service.ListDataStoresRequest], + data_store_service.ListDataStoresResponse, + ]: r"""Return a callable for the list data stores method over gRPC. Lists all the @@ -329,18 +334,20 @@ def list_data_stores(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_data_stores' not in self._stubs: - self._stubs['list_data_stores'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.DataStoreService/ListDataStores', + if "list_data_stores" not in self._stubs: + self._stubs["list_data_stores"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.DataStoreService/ListDataStores", request_serializer=data_store_service.ListDataStoresRequest.serialize, response_deserializer=data_store_service.ListDataStoresResponse.deserialize, ) - return self._stubs['list_data_stores'] + return self._stubs["list_data_stores"] @property - def delete_data_store(self) -> Callable[ - [data_store_service.DeleteDataStoreRequest], - operations_pb2.Operation]: + def delete_data_store( + self, + ) -> Callable[ + [data_store_service.DeleteDataStoreRequest], operations_pb2.Operation + ]: r"""Return a callable for the delete data store method over gRPC. Deletes a @@ -356,18 +363,20 @@ def delete_data_store(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_data_store' not in self._stubs: - self._stubs['delete_data_store'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.DataStoreService/DeleteDataStore', + if "delete_data_store" not in self._stubs: + self._stubs["delete_data_store"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.DataStoreService/DeleteDataStore", request_serializer=data_store_service.DeleteDataStoreRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['delete_data_store'] + return self._stubs["delete_data_store"] @property - def update_data_store(self) -> Callable[ - [data_store_service.UpdateDataStoreRequest], - gcd_data_store.DataStore]: + def update_data_store( + self, + ) -> Callable[ + [data_store_service.UpdateDataStoreRequest], gcd_data_store.DataStore + ]: r"""Return a callable for the update data store method over gRPC. Updates a @@ -383,13 +392,13 @@ def update_data_store(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_data_store' not in self._stubs: - self._stubs['update_data_store'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.DataStoreService/UpdateDataStore', + if "update_data_store" not in self._stubs: + self._stubs["update_data_store"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.DataStoreService/UpdateDataStore", request_serializer=data_store_service.UpdateDataStoreRequest.serialize, response_deserializer=gcd_data_store.DataStore.deserialize, ) - return self._stubs['update_data_store'] + return self._stubs["update_data_store"] def close(self): self.grpc_channel.close() @@ -398,8 +407,7 @@ def close(self): def get_operation( self, ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ + 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 @@ -415,9 +423,10 @@ def 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. - """ + ) -> 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 @@ -435,6 +444,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'DataStoreServiceGrpcTransport', -) +__all__ = ("DataStoreServiceGrpcTransport",) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/grpc_asyncio.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/grpc_asyncio.py similarity index 80% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/grpc_asyncio.py rename to packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/grpc_asyncio.py index ae6065d7eb54..95fdaeb4fee1 100644 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/grpc_asyncio.py @@ -13,24 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import warnings from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +import grpc # type: ignore from grpc.experimental import aio # type: ignore -from google.cloud.discoveryengine_v1alpha.types import data_store from google.cloud.discoveryengine_v1alpha.types import data_store as gcd_data_store +from google.cloud.discoveryengine_v1alpha.types import data_store from google.cloud.discoveryengine_v1alpha.types import data_store_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import DataStoreServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, DataStoreServiceTransport from .grpc import DataStoreServiceGrpcTransport @@ -53,13 +51,15 @@ class DataStoreServiceGrpcAsyncIOTransport(DataStoreServiceTransport): _stubs: Dict[str, Callable] = {} @classmethod - def create_channel(cls, - host: str = 'discoveryengine.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: + def create_channel( + cls, + host: str = "discoveryengine.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. @@ -90,24 +90,26 @@ def create_channel(cls, default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs + **kwargs, ) - def __init__(self, *, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: + def __init__( + self, + *, + host: str = "discoveryengine.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -253,9 +255,11 @@ def operations_client(self) -> operations_v1.OperationsAsyncClient: return self._operations_client @property - def create_data_store(self) -> Callable[ - [data_store_service.CreateDataStoreRequest], - Awaitable[operations_pb2.Operation]]: + def create_data_store( + self, + ) -> Callable[ + [data_store_service.CreateDataStoreRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the create data store method over gRPC. Creates a @@ -277,18 +281,20 @@ def create_data_store(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_data_store' not in self._stubs: - self._stubs['create_data_store'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.DataStoreService/CreateDataStore', + if "create_data_store" not in self._stubs: + self._stubs["create_data_store"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.DataStoreService/CreateDataStore", request_serializer=data_store_service.CreateDataStoreRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['create_data_store'] + return self._stubs["create_data_store"] @property - def get_data_store(self) -> Callable[ - [data_store_service.GetDataStoreRequest], - Awaitable[data_store.DataStore]]: + def get_data_store( + self, + ) -> Callable[ + [data_store_service.GetDataStoreRequest], Awaitable[data_store.DataStore] + ]: r"""Return a callable for the get data store method over gRPC. Gets a @@ -304,18 +310,21 @@ def get_data_store(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_data_store' not in self._stubs: - self._stubs['get_data_store'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.DataStoreService/GetDataStore', + if "get_data_store" not in self._stubs: + self._stubs["get_data_store"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.DataStoreService/GetDataStore", request_serializer=data_store_service.GetDataStoreRequest.serialize, response_deserializer=data_store.DataStore.deserialize, ) - return self._stubs['get_data_store'] + return self._stubs["get_data_store"] @property - def list_data_stores(self) -> Callable[ - [data_store_service.ListDataStoresRequest], - Awaitable[data_store_service.ListDataStoresResponse]]: + def list_data_stores( + self, + ) -> Callable[ + [data_store_service.ListDataStoresRequest], + Awaitable[data_store_service.ListDataStoresResponse], + ]: r"""Return a callable for the list data stores method over gRPC. Lists all the @@ -332,18 +341,20 @@ def list_data_stores(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_data_stores' not in self._stubs: - self._stubs['list_data_stores'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.DataStoreService/ListDataStores', + if "list_data_stores" not in self._stubs: + self._stubs["list_data_stores"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.DataStoreService/ListDataStores", request_serializer=data_store_service.ListDataStoresRequest.serialize, response_deserializer=data_store_service.ListDataStoresResponse.deserialize, ) - return self._stubs['list_data_stores'] + return self._stubs["list_data_stores"] @property - def delete_data_store(self) -> Callable[ - [data_store_service.DeleteDataStoreRequest], - Awaitable[operations_pb2.Operation]]: + def delete_data_store( + self, + ) -> Callable[ + [data_store_service.DeleteDataStoreRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the delete data store method over gRPC. Deletes a @@ -359,18 +370,20 @@ def delete_data_store(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_data_store' not in self._stubs: - self._stubs['delete_data_store'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.DataStoreService/DeleteDataStore', + if "delete_data_store" not in self._stubs: + self._stubs["delete_data_store"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.DataStoreService/DeleteDataStore", request_serializer=data_store_service.DeleteDataStoreRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['delete_data_store'] + return self._stubs["delete_data_store"] @property - def update_data_store(self) -> Callable[ - [data_store_service.UpdateDataStoreRequest], - Awaitable[gcd_data_store.DataStore]]: + def update_data_store( + self, + ) -> Callable[ + [data_store_service.UpdateDataStoreRequest], Awaitable[gcd_data_store.DataStore] + ]: r"""Return a callable for the update data store method over gRPC. Updates a @@ -386,13 +399,13 @@ def update_data_store(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_data_store' not in self._stubs: - self._stubs['update_data_store'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.DataStoreService/UpdateDataStore', + if "update_data_store" not in self._stubs: + self._stubs["update_data_store"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.DataStoreService/UpdateDataStore", request_serializer=data_store_service.UpdateDataStoreRequest.serialize, response_deserializer=gcd_data_store.DataStore.deserialize, ) - return self._stubs['update_data_store'] + return self._stubs["update_data_store"] def close(self): return self.grpc_channel.close() @@ -401,8 +414,7 @@ def close(self): def get_operation( self, ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ + 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 @@ -418,9 +430,10 @@ def 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. - """ + ) -> 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 @@ -434,6 +447,4 @@ def list_operations( return self._stubs["list_operations"] -__all__ = ( - 'DataStoreServiceGrpcAsyncIOTransport', -) +__all__ = ("DataStoreServiceGrpcAsyncIOTransport",) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/rest.py similarity index 58% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/rest.py rename to packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/rest.py index 442e40a5726c..459926110c2f 100644 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/data_store_service/transports/rest.py @@ -14,26 +14,28 @@ # limitations under the License. # -from google.auth.transport.requests import AuthorizedSession # type: ignore +import dataclasses import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import ( + gapic_v1, + operations_v1, + path_template, + rest_helpers, + rest_streaming, +) from google.api_core import exceptions as core_exceptions from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore from google.protobuf import json_format -from google.api_core import operations_v1 -from google.cloud.location import locations_pb2 # type: ignore +import grpc # type: ignore from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] @@ -41,13 +43,14 @@ OptionalRetry = Union[retries.Retry, object] # type: ignore -from google.cloud.discoveryengine_v1alpha.types import data_store -from google.cloud.discoveryengine_v1alpha.types import data_store as gcd_data_store -from google.cloud.discoveryengine_v1alpha.types import data_store_service from google.longrunning import operations_pb2 # type: ignore -from .base import DataStoreServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from google.cloud.discoveryengine_v1alpha.types import data_store as gcd_data_store +from google.cloud.discoveryengine_v1alpha.types import data_store +from google.cloud.discoveryengine_v1alpha.types import data_store_service +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import DataStoreServiceTransport DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, @@ -116,7 +119,12 @@ def post_update_data_store(self, response): """ - def pre_create_data_store(self, request: data_store_service.CreateDataStoreRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[data_store_service.CreateDataStoreRequest, Sequence[Tuple[str, str]]]: + + def pre_create_data_store( + self, + request: data_store_service.CreateDataStoreRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[data_store_service.CreateDataStoreRequest, Sequence[Tuple[str, str]]]: """Pre-rpc interceptor for create_data_store Override in a subclass to manipulate the request or metadata @@ -124,7 +132,9 @@ def pre_create_data_store(self, request: data_store_service.CreateDataStoreReque """ return request, metadata - def post_create_data_store(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_create_data_store( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for create_data_store Override in a subclass to manipulate the response @@ -132,7 +142,12 @@ def post_create_data_store(self, response: operations_pb2.Operation) -> operatio it is returned to user code. """ return response - def pre_delete_data_store(self, request: data_store_service.DeleteDataStoreRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[data_store_service.DeleteDataStoreRequest, Sequence[Tuple[str, str]]]: + + def pre_delete_data_store( + self, + request: data_store_service.DeleteDataStoreRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[data_store_service.DeleteDataStoreRequest, Sequence[Tuple[str, str]]]: """Pre-rpc interceptor for delete_data_store Override in a subclass to manipulate the request or metadata @@ -140,7 +155,9 @@ def pre_delete_data_store(self, request: data_store_service.DeleteDataStoreReque """ return request, metadata - def post_delete_data_store(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_delete_data_store( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for delete_data_store Override in a subclass to manipulate the response @@ -148,7 +165,12 @@ def post_delete_data_store(self, response: operations_pb2.Operation) -> operatio it is returned to user code. """ return response - def pre_get_data_store(self, request: data_store_service.GetDataStoreRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[data_store_service.GetDataStoreRequest, Sequence[Tuple[str, str]]]: + + def pre_get_data_store( + self, + request: data_store_service.GetDataStoreRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[data_store_service.GetDataStoreRequest, Sequence[Tuple[str, str]]]: """Pre-rpc interceptor for get_data_store Override in a subclass to manipulate the request or metadata @@ -156,7 +178,9 @@ def pre_get_data_store(self, request: data_store_service.GetDataStoreRequest, me """ return request, metadata - def post_get_data_store(self, response: data_store.DataStore) -> data_store.DataStore: + def post_get_data_store( + self, response: data_store.DataStore + ) -> data_store.DataStore: """Post-rpc interceptor for get_data_store Override in a subclass to manipulate the response @@ -164,7 +188,12 @@ def post_get_data_store(self, response: data_store.DataStore) -> data_store.Data it is returned to user code. """ return response - def pre_list_data_stores(self, request: data_store_service.ListDataStoresRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[data_store_service.ListDataStoresRequest, Sequence[Tuple[str, str]]]: + + def pre_list_data_stores( + self, + request: data_store_service.ListDataStoresRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[data_store_service.ListDataStoresRequest, Sequence[Tuple[str, str]]]: """Pre-rpc interceptor for list_data_stores Override in a subclass to manipulate the request or metadata @@ -172,7 +201,9 @@ def pre_list_data_stores(self, request: data_store_service.ListDataStoresRequest """ return request, metadata - def post_list_data_stores(self, response: data_store_service.ListDataStoresResponse) -> data_store_service.ListDataStoresResponse: + def post_list_data_stores( + self, response: data_store_service.ListDataStoresResponse + ) -> data_store_service.ListDataStoresResponse: """Post-rpc interceptor for list_data_stores Override in a subclass to manipulate the response @@ -180,7 +211,12 @@ def post_list_data_stores(self, response: data_store_service.ListDataStoresRespo it is returned to user code. """ return response - def pre_update_data_store(self, request: data_store_service.UpdateDataStoreRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[data_store_service.UpdateDataStoreRequest, Sequence[Tuple[str, str]]]: + + def pre_update_data_store( + self, + request: data_store_service.UpdateDataStoreRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[data_store_service.UpdateDataStoreRequest, Sequence[Tuple[str, str]]]: """Pre-rpc interceptor for update_data_store Override in a subclass to manipulate the request or metadata @@ -188,7 +224,9 @@ def pre_update_data_store(self, request: data_store_service.UpdateDataStoreReque """ return request, metadata - def post_update_data_store(self, response: gcd_data_store.DataStore) -> gcd_data_store.DataStore: + def post_update_data_store( + self, response: gcd_data_store.DataStore + ) -> gcd_data_store.DataStore: """Post-rpc interceptor for update_data_store Override in a subclass to manipulate the response @@ -198,7 +236,9 @@ def post_update_data_store(self, response: gcd_data_store.DataStore) -> gcd_data return response def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, str]], ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: """Pre-rpc interceptor for get_operation @@ -217,8 +257,11 @@ def post_get_operation( it is returned to user code. """ return response + def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, str]], ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: """Pre-rpc interceptor for list_operations @@ -261,20 +304,21 @@ class DataStoreServiceRestTransport(DataStoreServiceTransport): """ - def __init__(self, *, - host: str = 'discoveryengine.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[DataStoreServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: + def __init__( + self, + *, + host: str = "discoveryengine.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[DataStoreServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -313,7 +357,9 @@ def __init__(self, *, # credentials object maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER url_match_items = maybe_url_match.groupdict() @@ -324,10 +370,11 @@ def __init__(self, *, credentials=credentials, client_info=client_info, always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience + api_audience=api_audience, ) self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) + self._credentials, default_host=self.DEFAULT_HOST + ) self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None if client_cert_source_for_mtls: self._session.configure_mtls_channel(client_cert_source_for_mtls) @@ -344,125 +391,128 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Only create a new client if we do not already have one. if self._operations_client is None: http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.GetOperation': [ + "google.longrunning.Operations.GetOperation": [ { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/engines/*/operations/*}", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/operations/*}', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/operations/*}", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/operations/*}', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*/operations/*}", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/operations/*}', + "method": "get", + "uri": "/v1alpha/{name=projects/*/operations/*}", }, ], - 'google.longrunning.Operations.ListOperations': [ + "google.longrunning.Operations.ListOperations": [ { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}/operations", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}/operations', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}/operations", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*}/operations', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*}/operations", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*}/operations", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*}/operations', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*}/operations", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*}/operations', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*}/operations", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*}/operations', + "method": "get", + "uri": "/v1alpha/{name=projects/*}/operations", }, ], } rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1alpha") + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1alpha", + ) - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) # Return the client from cache. return self._operations_client @@ -471,19 +521,26 @@ class _CreateDataStore(DataStoreServiceRestStub): def __hash__(self): return hash("CreateDataStore") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "dataStoreId" : "", } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "dataStoreId": "", + } @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: data_store_service.CreateDataStoreRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: data_store_service.CreateDataStoreRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: r"""Call the create data store method over HTTP. Args: @@ -505,51 +562,56 @@ def __call__(self, """ - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1alpha/{parent=projects/*/locations/*}/dataStores', - 'body': 'data_store', - }, -{ - 'method': 'post', - 'uri': '/v1alpha/{parent=projects/*/locations/*/collections/*}/dataStores', - 'body': 'data_store', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{parent=projects/*/locations/*}/dataStores", + "body": "data_store", + }, + { + "method": "post", + "uri": "/v1alpha/{parent=projects/*/locations/*/collections/*}/dataStores", + "body": "data_store", + }, ] - request, metadata = self._interceptor.pre_create_data_store(request, metadata) + request, metadata = self._interceptor.pre_create_data_store( + request, metadata + ) pb_request = data_store_service.CreateDataStoreRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], + transcoded_request["body"], including_default_value_fields=False, - use_integers_for_enums=True + use_integers_for_enums=True, ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] + uri = transcoded_request["uri"] + method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) query_params.update(self._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" # Send the request headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(self._session, method)( "{host}{uri}".format(host=self._host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -566,19 +628,24 @@ class _DeleteDataStore(DataStoreServiceRestStub): def __hash__(self): return hash("DeleteDataStore") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: data_store_service.DeleteDataStoreRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: data_store_service.DeleteDataStoreRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: r"""Call the delete data store method over HTTP. Args: @@ -600,41 +667,46 @@ def __call__(self, """ - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}", + }, + { + "method": "delete", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}", + }, ] - request, metadata = self._interceptor.pre_delete_data_store(request, metadata) + request, metadata = self._interceptor.pre_delete_data_store( + request, metadata + ) pb_request = data_store_service.DeleteDataStoreRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) - uri = transcoded_request['uri'] - method = transcoded_request['method'] + uri = transcoded_request["uri"] + method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) query_params.update(self._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" # Send the request headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(self._session, method)( "{host}{uri}".format(host=self._host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -651,19 +723,24 @@ class _GetDataStore(DataStoreServiceRestStub): def __hash__(self): return hash("GetDataStore") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: data_store_service.GetDataStoreRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> data_store.DataStore: + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: data_store_service.GetDataStoreRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> data_store.DataStore: r"""Call the get data store method over HTTP. Args: @@ -684,41 +761,44 @@ def __call__(self, """ - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}", + }, ] request, metadata = self._interceptor.pre_get_data_store(request, metadata) pb_request = data_store_service.GetDataStoreRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) - uri = transcoded_request['uri'] - method = transcoded_request['method'] + uri = transcoded_request["uri"] + method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) query_params.update(self._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" # Send the request headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(self._session, method)( "{host}{uri}".format(host=self._host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -737,19 +817,24 @@ class _ListDataStores(DataStoreServiceRestStub): def __hash__(self): return hash("ListDataStores") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: data_store_service.ListDataStoresRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> data_store_service.ListDataStoresResponse: + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: data_store_service.ListDataStoresRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> data_store_service.ListDataStoresResponse: r"""Call the list data stores method over HTTP. Args: @@ -771,41 +856,46 @@ def __call__(self, """ - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{parent=projects/*/locations/*}/dataStores', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{parent=projects/*/locations/*/collections/*}/dataStores', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{parent=projects/*/locations/*}/dataStores", + }, + { + "method": "get", + "uri": "/v1alpha/{parent=projects/*/locations/*/collections/*}/dataStores", + }, ] - request, metadata = self._interceptor.pre_list_data_stores(request, metadata) + request, metadata = self._interceptor.pre_list_data_stores( + request, metadata + ) pb_request = data_store_service.ListDataStoresRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) - uri = transcoded_request['uri'] - method = transcoded_request['method'] + uri = transcoded_request["uri"] + method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) query_params.update(self._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" # Send the request headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(self._session, method)( "{host}{uri}".format(host=self._host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -824,19 +914,24 @@ class _UpdateDataStore(DataStoreServiceRestStub): def __hash__(self): return hash("UpdateDataStore") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: data_store_service.UpdateDataStoreRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_data_store.DataStore: + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: data_store_service.UpdateDataStoreRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_data_store.DataStore: r"""Call the update data store method over HTTP. Args: @@ -857,51 +952,56 @@ def __call__(self, """ - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1alpha/{data_store.name=projects/*/locations/*/dataStores/*}', - 'body': 'data_store', - }, -{ - 'method': 'patch', - 'uri': '/v1alpha/{data_store.name=projects/*/locations/*/collections/*/dataStores/*}', - 'body': 'data_store', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1alpha/{data_store.name=projects/*/locations/*/dataStores/*}", + "body": "data_store", + }, + { + "method": "patch", + "uri": "/v1alpha/{data_store.name=projects/*/locations/*/collections/*/dataStores/*}", + "body": "data_store", + }, ] - request, metadata = self._interceptor.pre_update_data_store(request, metadata) + request, metadata = self._interceptor.pre_update_data_store( + request, metadata + ) pb_request = data_store_service.UpdateDataStoreRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], + transcoded_request["body"], including_default_value_fields=False, - use_integers_for_enums=True + use_integers_for_enums=True, ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] + uri = transcoded_request["uri"] + method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) query_params.update(self._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" # Send the request headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(self._session, method)( "{host}{uri}".format(host=self._host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -917,57 +1017,67 @@ def __call__(self, return resp @property - def create_data_store(self) -> Callable[ - [data_store_service.CreateDataStoreRequest], - operations_pb2.Operation]: + def create_data_store( + self, + ) -> Callable[ + [data_store_service.CreateDataStoreRequest], 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._CreateDataStore(self._session, self._host, self._interceptor) # type: ignore + return self._CreateDataStore(self._session, self._host, self._interceptor) # type: ignore @property - def delete_data_store(self) -> Callable[ - [data_store_service.DeleteDataStoreRequest], - operations_pb2.Operation]: + def delete_data_store( + self, + ) -> Callable[ + [data_store_service.DeleteDataStoreRequest], 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._DeleteDataStore(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteDataStore(self._session, self._host, self._interceptor) # type: ignore @property - def get_data_store(self) -> Callable[ - [data_store_service.GetDataStoreRequest], - data_store.DataStore]: + def get_data_store( + self, + ) -> Callable[[data_store_service.GetDataStoreRequest], data_store.DataStore]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._GetDataStore(self._session, self._host, self._interceptor) # type: ignore + return self._GetDataStore(self._session, self._host, self._interceptor) # type: ignore @property - def list_data_stores(self) -> Callable[ - [data_store_service.ListDataStoresRequest], - data_store_service.ListDataStoresResponse]: + def list_data_stores( + self, + ) -> Callable[ + [data_store_service.ListDataStoresRequest], + data_store_service.ListDataStoresResponse, + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._ListDataStores(self._session, self._host, self._interceptor) # type: ignore + return self._ListDataStores(self._session, self._host, self._interceptor) # type: ignore @property - def update_data_store(self) -> Callable[ - [data_store_service.UpdateDataStoreRequest], - gcd_data_store.DataStore]: + def update_data_store( + self, + ) -> Callable[ + [data_store_service.UpdateDataStoreRequest], gcd_data_store.DataStore + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._UpdateDataStore(self._session, self._host, self._interceptor) # type: ignore + return self._UpdateDataStore(self._session, self._host, self._interceptor) # type: ignore @property def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore class _GetOperation(DataStoreServiceRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: r"""Call the get operation method over HTTP. Args: @@ -983,74 +1093,74 @@ def __call__(self, operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/operations/*}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/engines/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/operations/*}", + }, ] request, metadata = self._interceptor.pre_get_operation(request, metadata) request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) + transcoded_request = path_template.transcode(http_options, **request_kwargs) - uri = transcoded_request['uri'] - method = transcoded_request['method'] + uri = transcoded_request["uri"] + method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) + query_params = json.loads(json.dumps(transcoded_request["query_params"])) # Send the request headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(self._session, method)( "{host}{uri}".format(host=self._host, uri=uri), @@ -1071,16 +1181,17 @@ def __call__(self, @property def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore class _ListOperations(DataStoreServiceRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: r"""Call the list operations method over HTTP. Args: @@ -1096,74 +1207,74 @@ def __call__(self, operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*}/operations', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}/operations", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}/operations", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*}/operations", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*}/operations", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*}/operations", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*}/operations", + }, ] request, metadata = self._interceptor.pre_list_operations(request, metadata) request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) + transcoded_request = path_template.transcode(http_options, **request_kwargs) - uri = transcoded_request['uri'] - method = transcoded_request['method'] + uri = transcoded_request["uri"] + method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) + query_params = json.loads(json.dumps(transcoded_request["query_params"])) # Send the request headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(self._session, method)( "{host}{uri}".format(host=self._host, uri=uri), @@ -1190,6 +1301,4 @@ def close(self): self._session.close() -__all__=( - 'DataStoreServiceRestTransport', -) +__all__ = ("DataStoreServiceRestTransport",) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/engine_service/__init__.py similarity index 92% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/__init__.py rename to packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/engine_service/__init__.py index 84cdcf706834..642a2e63fcb4 100644 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/__init__.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/engine_service/__init__.py @@ -13,10 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .client import EngineServiceClient from .async_client import EngineServiceAsyncClient +from .client import EngineServiceClient __all__ = ( - 'EngineServiceClient', - 'EngineServiceAsyncClient', + "EngineServiceClient", + "EngineServiceAsyncClient", ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/engine_service/async_client.py similarity index 86% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/async_client.py rename to packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/engine_service/async_client.py index 957377607715..9c9ae463b1cc 100644 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/async_client.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/engine_service/async_client.py @@ -16,16 +16,26 @@ from collections import OrderedDict import functools import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.discoveryengine_v1alpha import gapic_version as package_version +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) -from google.api_core.client_options import ClientOptions from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +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.discoveryengine_v1alpha import gapic_version as package_version try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] @@ -34,19 +44,21 @@ from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + from google.cloud.discoveryengine_v1alpha.services.engine_service import pagers from google.cloud.discoveryengine_v1alpha.types import common from google.cloud.discoveryengine_v1alpha.types import engine from google.cloud.discoveryengine_v1alpha.types import engine as gcd_engine from google.cloud.discoveryengine_v1alpha.types import engine_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import EngineServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import EngineServiceGrpcAsyncIOTransport + from .client import EngineServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, EngineServiceTransport +from .transports.grpc_asyncio import EngineServiceGrpcAsyncIOTransport class EngineServiceAsyncClient: @@ -63,16 +75,30 @@ class EngineServiceAsyncClient: parse_collection_path = staticmethod(EngineServiceClient.parse_collection_path) engine_path = staticmethod(EngineServiceClient.engine_path) parse_engine_path = staticmethod(EngineServiceClient.parse_engine_path) - common_billing_account_path = staticmethod(EngineServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(EngineServiceClient.parse_common_billing_account_path) + common_billing_account_path = staticmethod( + EngineServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + EngineServiceClient.parse_common_billing_account_path + ) common_folder_path = staticmethod(EngineServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(EngineServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(EngineServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(EngineServiceClient.parse_common_organization_path) + parse_common_folder_path = staticmethod( + EngineServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + EngineServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + EngineServiceClient.parse_common_organization_path + ) common_project_path = staticmethod(EngineServiceClient.common_project_path) - parse_common_project_path = staticmethod(EngineServiceClient.parse_common_project_path) + parse_common_project_path = staticmethod( + EngineServiceClient.parse_common_project_path + ) common_location_path = staticmethod(EngineServiceClient.common_location_path) - parse_common_location_path = staticmethod(EngineServiceClient.parse_common_location_path) + parse_common_location_path = staticmethod( + EngineServiceClient.parse_common_location_path + ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): @@ -108,7 +134,9 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + 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: @@ -150,14 +178,18 @@ def transport(self) -> EngineServiceTransport: """ return self._client.transport - get_transport_class = functools.partial(type(EngineServiceClient).get_transport_class, type(EngineServiceClient)) + get_transport_class = functools.partial( + type(EngineServiceClient).get_transport_class, type(EngineServiceClient) + ) - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, EngineServiceTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, EngineServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the engine service client. Args: @@ -195,19 +227,19 @@ def __init__(self, *, transport=transport, client_options=client_options, client_info=client_info, - ) - async def create_engine(self, - request: Optional[Union[engine_service.CreateEngineRequest, dict]] = None, - *, - parent: Optional[str] = None, - engine: Optional[gcd_engine.Engine] = None, - engine_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: + async def create_engine( + self, + request: Optional[Union[engine_service.CreateEngineRequest, dict]] = None, + *, + parent: Optional[str] = None, + engine: Optional[gcd_engine.Engine] = None, + engine_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: r"""Creates a [Engine][google.cloud.discoveryengine.v1alpha.Engine]. .. code-block:: python @@ -300,8 +332,10 @@ async def sample_create_engine(): # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, engine, engine_id]) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = engine_service.CreateEngineRequest(request) @@ -325,9 +359,7 @@ async def sample_create_engine(): # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Send the request. @@ -349,14 +381,15 @@ async def sample_create_engine(): # Done; return the response. return response - async def delete_engine(self, - request: Optional[Union[engine_service.DeleteEngineRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: + async def delete_engine( + self, + request: Optional[Union[engine_service.DeleteEngineRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: r"""Deletes a [Engine][google.cloud.discoveryengine.v1alpha.Engine]. .. code-block:: python @@ -439,8 +472,10 @@ async def sample_delete_engine(): # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = engine_service.DeleteEngineRequest(request) @@ -460,9 +495,7 @@ async def sample_delete_engine(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. @@ -484,15 +517,16 @@ async def sample_delete_engine(): # Done; return the response. return response - async def update_engine(self, - request: Optional[Union[engine_service.UpdateEngineRequest, dict]] = None, - *, - engine: Optional[gcd_engine.Engine] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_engine.Engine: + async def update_engine( + self, + request: Optional[Union[engine_service.UpdateEngineRequest, dict]] = None, + *, + engine: Optional[gcd_engine.Engine] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_engine.Engine: r"""Updates an [Engine][google.cloud.discoveryengine.v1alpha.Engine] .. code-block:: python @@ -575,8 +609,10 @@ async def sample_update_engine(): # gotten any keyword arguments that map to the request. has_flattened_params = any([engine, update_mask]) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = engine_service.UpdateEngineRequest(request) @@ -598,9 +634,9 @@ async def sample_update_engine(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("engine.name", request.engine.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("engine.name", request.engine.name),) + ), ) # Send the request. @@ -614,14 +650,15 @@ async def sample_update_engine(): # Done; return the response. return response - async def get_engine(self, - request: Optional[Union[engine_service.GetEngineRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> engine.Engine: + async def get_engine( + self, + request: Optional[Union[engine_service.GetEngineRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> engine.Engine: r"""Gets a [Engine][google.cloud.discoveryengine.v1alpha.Engine]. .. code-block:: python @@ -681,8 +718,10 @@ async def sample_get_engine(): # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = engine_service.GetEngineRequest(request) @@ -702,9 +741,7 @@ async def sample_get_engine(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. @@ -718,14 +755,15 @@ async def sample_get_engine(): # Done; return the response. return response - async def list_engines(self, - request: Optional[Union[engine_service.ListEnginesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEnginesAsyncPager: + async def list_engines( + self, + request: Optional[Union[engine_service.ListEnginesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEnginesAsyncPager: r"""Lists all the [Engine][google.cloud.discoveryengine.v1alpha.Engine]s associated with the project. @@ -790,8 +828,10 @@ async def sample_list_engines(): # gotten any keyword arguments that map to the request. has_flattened_params = any([parent]) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = engine_service.ListEnginesRequest(request) @@ -811,9 +851,7 @@ async def sample_list_engines(): # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Send the request. @@ -836,14 +874,15 @@ async def sample_list_engines(): # Done; return the response. return response - async def pause_engine(self, - request: Optional[Union[engine_service.PauseEngineRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> engine.Engine: + async def pause_engine( + self, + request: Optional[Union[engine_service.PauseEngineRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> engine.Engine: r"""Pauses the training of an existing engine. Only applicable if [solution_type][] is [SOLUTION_TYPE_RECOMMENDATION][google.cloud.discoveryengine.v1alpha.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. @@ -902,8 +941,10 @@ async def sample_pause_engine(): # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = engine_service.PauseEngineRequest(request) @@ -923,9 +964,7 @@ async def sample_pause_engine(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. @@ -939,14 +978,15 @@ async def sample_pause_engine(): # Done; return the response. return response - async def resume_engine(self, - request: Optional[Union[engine_service.ResumeEngineRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> engine.Engine: + async def resume_engine( + self, + request: Optional[Union[engine_service.ResumeEngineRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> engine.Engine: r"""Resumes the training of an existing engine. Only applicable if [solution_type][] is [SOLUTION_TYPE_RECOMMENDATION][google.cloud.discoveryengine.v1alpha.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. @@ -1005,8 +1045,10 @@ async def sample_resume_engine(): # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = engine_service.ResumeEngineRequest(request) @@ -1026,9 +1068,7 @@ async def sample_resume_engine(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. @@ -1042,14 +1082,15 @@ async def sample_resume_engine(): # Done; return the response. return response - async def tune_engine(self, - request: Optional[Union[engine_service.TuneEngineRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: + async def tune_engine( + self, + request: Optional[Union[engine_service.TuneEngineRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: r"""Tunes an existing engine. Only applicable if [solution_type][] is [SOLUTION_TYPE_RECOMMENDATION][google.cloud.discoveryengine.v1alpha.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. @@ -1118,8 +1159,10 @@ async def sample_tune_engine(): # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) request = engine_service.TuneEngineRequest(request) @@ -1139,9 +1182,7 @@ async def sample_tune_engine(): # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. @@ -1203,13 +1244,16 @@ async def 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.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1254,13 +1298,16 @@ async def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1271,9 +1318,10 @@ async def __aenter__(self) -> "EngineServiceAsyncClient": async def __aexit__(self, exc_type, exc, tb): await self.transport.close() -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - -__all__ = ( - "EngineServiceAsyncClient", +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ ) + + +__all__ = ("EngineServiceAsyncClient",) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/engine_service/client.py similarity index 83% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/client.py rename to packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/engine_service/client.py index b3b713dad2c0..1f1bf4f377eb 100644 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/client.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/engine_service/client.py @@ -16,19 +16,30 @@ from collections import OrderedDict import os import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.discoveryengine_v1alpha import gapic_version as package_version +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore +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.discoveryengine_v1alpha import gapic_version as package_version try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] @@ -37,17 +48,19 @@ from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + from google.cloud.discoveryengine_v1alpha.services.engine_service import pagers from google.cloud.discoveryengine_v1alpha.types import common from google.cloud.discoveryengine_v1alpha.types import engine from google.cloud.discoveryengine_v1alpha.types import engine as gcd_engine from google.cloud.discoveryengine_v1alpha.types import engine_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import EngineServiceTransport, DEFAULT_CLIENT_INFO + +from .transports.base import DEFAULT_CLIENT_INFO, EngineServiceTransport from .transports.grpc import EngineServiceGrpcTransport from .transports.grpc_asyncio import EngineServiceGrpcAsyncIOTransport from .transports.rest import EngineServiceRestTransport @@ -60,14 +73,16 @@ class EngineServiceClientMeta(type): support objects (e.g. transport) without polluting the client instance objects. """ + _transport_registry = OrderedDict() # type: Dict[str, Type[EngineServiceTransport]] _transport_registry["grpc"] = EngineServiceGrpcTransport _transport_registry["grpc_asyncio"] = EngineServiceGrpcAsyncIOTransport _transport_registry["rest"] = EngineServiceRestTransport - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[EngineServiceTransport]: + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[EngineServiceTransport]: """Returns an appropriate transport class. Args: @@ -157,8 +172,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): Returns: EngineServiceClient: The constructed client. """ - credentials = service_account.Credentials.from_service_account_file( - filename) + credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) @@ -175,84 +189,134 @@ def transport(self) -> EngineServiceTransport: return self._transport @staticmethod - def collection_path(project: str,location: str,collection: str,) -> str: + def collection_path( + project: str, + location: str, + collection: str, + ) -> str: """Returns a fully-qualified collection string.""" - return "projects/{project}/locations/{location}/collections/{collection}".format(project=project, location=location, collection=collection, ) + return ( + "projects/{project}/locations/{location}/collections/{collection}".format( + project=project, + location=location, + collection=collection, + ) + ) @staticmethod - def parse_collection_path(path: str) -> Dict[str,str]: + def parse_collection_path(path: str) -> Dict[str, str]: """Parses a collection path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/collections/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/collections/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def engine_path(project: str,location: str,collection: str,engine: str,) -> str: + def engine_path( + project: str, + location: str, + collection: str, + engine: str, + ) -> str: """Returns a fully-qualified engine string.""" - return "projects/{project}/locations/{location}/collections/{collection}/engines/{engine}".format(project=project, location=location, collection=collection, engine=engine, ) + return "projects/{project}/locations/{location}/collections/{collection}/engines/{engine}".format( + project=project, + location=location, + collection=collection, + engine=engine, + ) @staticmethod - def parse_engine_path(path: str) -> Dict[str,str]: + def parse_engine_path(path: str) -> Dict[str, str]: """Parses a engine path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/collections/(?P.+?)/engines/(?P.+?)$", path) + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/collections/(?P.+?)/engines/(?P.+?)$", + path, + ) return m.groupdict() if m else {} @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: + 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, ) + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: + 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: + def common_folder_path( + folder: str, + ) -> str: """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) + return "folders/{folder}".format( + folder=folder, + ) @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: + 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: + def common_organization_path( + organization: str, + ) -> str: """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) + return "organizations/{organization}".format( + organization=organization, + ) @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: + 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: + def common_project_path( + project: str, + ) -> str: """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) + return "projects/{project}".format( + project=project, + ) @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: + 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: + 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, ) + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: + 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): + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): """Return the API endpoint and client cert source for mutual TLS. The client cert source is determined in the following order: @@ -288,9 +352,13 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + 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 @@ -303,19 +371,23 @@ def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_optio # 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): + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): api_endpoint = cls.DEFAULT_MTLS_ENDPOINT else: api_endpoint = cls.DEFAULT_ENDPOINT return api_endpoint, client_cert_source - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, EngineServiceTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, EngineServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: """Instantiates the engine service client. Args: @@ -359,11 +431,15 @@ def __init__(self, *, client_options = client_options_lib.ClientOptions() client_options = cast(client_options_lib.ClientOptions, client_options) - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( + client_options + ) api_key_value = getattr(client_options, "api_key", None) if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") + 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 @@ -371,8 +447,10 @@ def __init__(self, *, if isinstance(transport, EngineServiceTransport): # transport is a EngineServiceTransport instance. if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) if client_options.scopes: raise ValueError( "When providing a transport instance, provide its scopes " @@ -382,8 +460,12 @@ def __init__(self, *, else: import google.auth._default # type: ignore - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) Transport = type(self).get_transport_class(transport) self._transport = Transport( @@ -398,16 +480,17 @@ def __init__(self, *, api_audience=client_options.api_audience, ) - def create_engine(self, - request: Optional[Union[engine_service.CreateEngineRequest, dict]] = None, - *, - parent: Optional[str] = None, - engine: Optional[gcd_engine.Engine] = None, - engine_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: + def create_engine( + self, + request: Optional[Union[engine_service.CreateEngineRequest, dict]] = None, + *, + parent: Optional[str] = None, + engine: Optional[gcd_engine.Engine] = None, + engine_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: r"""Creates a [Engine][google.cloud.discoveryengine.v1alpha.Engine]. .. code-block:: python @@ -500,8 +583,10 @@ def sample_create_engine(): # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, engine, engine_id]) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # Minor optimization to avoid making a copy if the user passes # in a engine_service.CreateEngineRequest. @@ -522,12 +607,10 @@ def sample_create_engine(): # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.create_engine] - # Certain fields should be provided within the metadata header; + # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Send the request. @@ -549,14 +632,15 @@ def sample_create_engine(): # Done; return the response. return response - def delete_engine(self, - request: Optional[Union[engine_service.DeleteEngineRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: + def delete_engine( + self, + request: Optional[Union[engine_service.DeleteEngineRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: r"""Deletes a [Engine][google.cloud.discoveryengine.v1alpha.Engine]. .. code-block:: python @@ -639,8 +723,10 @@ def sample_delete_engine(): # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # Minor optimization to avoid making a copy if the user passes # in a engine_service.DeleteEngineRequest. @@ -657,12 +743,10 @@ def sample_delete_engine(): # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.delete_engine] - # Certain fields should be provided within the metadata header; + # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. @@ -684,15 +768,16 @@ def sample_delete_engine(): # Done; return the response. return response - def update_engine(self, - request: Optional[Union[engine_service.UpdateEngineRequest, dict]] = None, - *, - engine: Optional[gcd_engine.Engine] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcd_engine.Engine: + def update_engine( + self, + request: Optional[Union[engine_service.UpdateEngineRequest, dict]] = None, + *, + engine: Optional[gcd_engine.Engine] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_engine.Engine: r"""Updates an [Engine][google.cloud.discoveryengine.v1alpha.Engine] .. code-block:: python @@ -775,8 +860,10 @@ def sample_update_engine(): # gotten any keyword arguments that map to the request. has_flattened_params = any([engine, update_mask]) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # Minor optimization to avoid making a copy if the user passes # in a engine_service.UpdateEngineRequest. @@ -795,12 +882,12 @@ def sample_update_engine(): # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.update_engine] - # Certain fields should be provided within the metadata header; + # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("engine.name", request.engine.name), - )), + gapic_v1.routing_header.to_grpc_metadata( + (("engine.name", request.engine.name),) + ), ) # Send the request. @@ -814,14 +901,15 @@ def sample_update_engine(): # Done; return the response. return response - def get_engine(self, - request: Optional[Union[engine_service.GetEngineRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> engine.Engine: + def get_engine( + self, + request: Optional[Union[engine_service.GetEngineRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> engine.Engine: r"""Gets a [Engine][google.cloud.discoveryengine.v1alpha.Engine]. .. code-block:: python @@ -881,8 +969,10 @@ def sample_get_engine(): # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # Minor optimization to avoid making a copy if the user passes # in a engine_service.GetEngineRequest. @@ -899,12 +989,10 @@ def sample_get_engine(): # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.get_engine] - # Certain fields should be provided within the metadata header; + # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. @@ -918,14 +1006,15 @@ def sample_get_engine(): # Done; return the response. return response - def list_engines(self, - request: Optional[Union[engine_service.ListEnginesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListEnginesPager: + def list_engines( + self, + request: Optional[Union[engine_service.ListEnginesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEnginesPager: r"""Lists all the [Engine][google.cloud.discoveryengine.v1alpha.Engine]s associated with the project. @@ -990,8 +1079,10 @@ def sample_list_engines(): # gotten any keyword arguments that map to the request. has_flattened_params = any([parent]) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # Minor optimization to avoid making a copy if the user passes # in a engine_service.ListEnginesRequest. @@ -1008,12 +1099,10 @@ def sample_list_engines(): # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.list_engines] - # Certain fields should be provided within the metadata header; + # 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), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), ) # Send the request. @@ -1036,14 +1125,15 @@ def sample_list_engines(): # Done; return the response. return response - def pause_engine(self, - request: Optional[Union[engine_service.PauseEngineRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> engine.Engine: + def pause_engine( + self, + request: Optional[Union[engine_service.PauseEngineRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> engine.Engine: r"""Pauses the training of an existing engine. Only applicable if [solution_type][] is [SOLUTION_TYPE_RECOMMENDATION][google.cloud.discoveryengine.v1alpha.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. @@ -1102,8 +1192,10 @@ def sample_pause_engine(): # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # Minor optimization to avoid making a copy if the user passes # in a engine_service.PauseEngineRequest. @@ -1120,12 +1212,10 @@ def sample_pause_engine(): # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.pause_engine] - # Certain fields should be provided within the metadata header; + # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. @@ -1139,14 +1229,15 @@ def sample_pause_engine(): # Done; return the response. return response - def resume_engine(self, - request: Optional[Union[engine_service.ResumeEngineRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> engine.Engine: + def resume_engine( + self, + request: Optional[Union[engine_service.ResumeEngineRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> engine.Engine: r"""Resumes the training of an existing engine. Only applicable if [solution_type][] is [SOLUTION_TYPE_RECOMMENDATION][google.cloud.discoveryengine.v1alpha.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. @@ -1205,8 +1296,10 @@ def sample_resume_engine(): # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # Minor optimization to avoid making a copy if the user passes # in a engine_service.ResumeEngineRequest. @@ -1223,12 +1316,10 @@ def sample_resume_engine(): # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.resume_engine] - # Certain fields should be provided within the metadata header; + # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. @@ -1242,14 +1333,15 @@ def sample_resume_engine(): # Done; return the response. return response - def tune_engine(self, - request: Optional[Union[engine_service.TuneEngineRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: + def tune_engine( + self, + request: Optional[Union[engine_service.TuneEngineRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: r"""Tunes an existing engine. Only applicable if [solution_type][] is [SOLUTION_TYPE_RECOMMENDATION][google.cloud.discoveryengine.v1alpha.SolutionType.SOLUTION_TYPE_RECOMMENDATION]. @@ -1318,8 +1410,10 @@ def sample_tune_engine(): # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) # Minor optimization to avoid making a copy if the user passes # in a engine_service.TuneEngineRequest. @@ -1336,12 +1430,10 @@ def sample_tune_engine(): # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.tune_engine] - # Certain fields should be provided within the metadata header; + # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. @@ -1416,13 +1508,16 @@ def 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.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response @@ -1467,29 +1562,24 @@ def get_operation( # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Send the request. response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) # Done; return the response. return response +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "EngineServiceClient", -) +__all__ = ("EngineServiceClient",) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/pagers.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/engine_service/pagers.py similarity index 84% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/pagers.py rename to packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/engine_service/pagers.py index 4024f3c35e51..2aa607973e4b 100644 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/pagers.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/engine_service/pagers.py @@ -13,10 +13,18 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, +) -from google.cloud.discoveryengine_v1alpha.types import engine -from google.cloud.discoveryengine_v1alpha.types import engine_service +from google.cloud.discoveryengine_v1alpha.types import engine, engine_service class ListEnginesPager: @@ -36,12 +44,15 @@ class ListEnginesPager: 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[..., engine_service.ListEnginesResponse], - request: engine_service.ListEnginesRequest, - response: engine_service.ListEnginesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): + + def __init__( + self, + method: Callable[..., engine_service.ListEnginesResponse], + request: engine_service.ListEnginesRequest, + response: engine_service.ListEnginesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): """Instantiate the pager. Args: @@ -75,7 +86,7 @@ def __iter__(self) -> Iterator[engine.Engine]: yield from page.engines def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) class ListEnginesAsyncPager: @@ -95,12 +106,15 @@ class ListEnginesAsyncPager: 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[engine_service.ListEnginesResponse]], - request: engine_service.ListEnginesRequest, - response: engine_service.ListEnginesResponse, - *, - metadata: Sequence[Tuple[str, str]] = ()): + + def __init__( + self, + method: Callable[..., Awaitable[engine_service.ListEnginesResponse]], + request: engine_service.ListEnginesRequest, + response: engine_service.ListEnginesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): """Instantiates the pager. Args: @@ -128,6 +142,7 @@ async def pages(self) -> AsyncIterator[engine_service.ListEnginesResponse]: self._request.page_token = self._response.next_page_token self._response = await self._method(self._request, metadata=self._metadata) yield self._response + def __aiter__(self) -> AsyncIterator[engine.Engine]: async def async_generator(): async for page in self.pages: @@ -137,4 +152,4 @@ async def async_generator(): return async_generator() def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/__init__.py similarity index 68% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/__init__.py rename to packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/__init__.py index e6f573dcd7dd..4b34767ce1ca 100644 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/__init__.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/__init__.py @@ -19,20 +19,18 @@ from .base import EngineServiceTransport from .grpc import EngineServiceGrpcTransport from .grpc_asyncio import EngineServiceGrpcAsyncIOTransport -from .rest import EngineServiceRestTransport -from .rest import EngineServiceRestInterceptor - +from .rest import EngineServiceRestInterceptor, EngineServiceRestTransport # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[EngineServiceTransport]] -_transport_registry['grpc'] = EngineServiceGrpcTransport -_transport_registry['grpc_asyncio'] = EngineServiceGrpcAsyncIOTransport -_transport_registry['rest'] = EngineServiceRestTransport +_transport_registry["grpc"] = EngineServiceGrpcTransport +_transport_registry["grpc_asyncio"] = EngineServiceGrpcAsyncIOTransport +_transport_registry["rest"] = EngineServiceRestTransport __all__ = ( - 'EngineServiceTransport', - 'EngineServiceGrpcTransport', - 'EngineServiceGrpcAsyncIOTransport', - 'EngineServiceRestTransport', - 'EngineServiceRestInterceptor', + "EngineServiceTransport", + "EngineServiceGrpcTransport", + "EngineServiceGrpcAsyncIOTransport", + "EngineServiceRestTransport", + "EngineServiceRestInterceptor", ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/base.py similarity index 63% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/base.py rename to packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/base.py index 7bf38c24e227..7689690ccd76 100644 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/base.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/base.py @@ -16,46 +16,46 @@ import abc from typing import Awaitable, Callable, Dict, Optional, Sequence, Union -from google.cloud.discoveryengine_v1alpha import gapic_version as package_version - -import google.auth # type: ignore import google.api_core from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 +from google.api_core import gapic_v1, operations_v1 from google.api_core import retry as retries -from google.api_core import operations_v1 +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore +from google.cloud.discoveryengine_v1alpha import gapic_version as package_version from google.cloud.discoveryengine_v1alpha.types import engine from google.cloud.discoveryengine_v1alpha.types import engine as gcd_engine from google.cloud.discoveryengine_v1alpha.types import engine_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) class EngineServiceTransport(abc.ABC): """Abstract transport class for EngineService.""" - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + DEFAULT_HOST: str = "discoveryengine.googleapis.com" - DEFAULT_HOST: str = 'discoveryengine.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: + 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: @@ -89,30 +89,38 @@ def __init__( # 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") + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) if credentials_file is not None: credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) # Don't apply audience if the credentials file passed from user. if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + 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"): + 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' + if ":" not in host: + host += ":443" self._host = host def _prep_wrapped_messages(self, client_info): @@ -158,14 +166,14 @@ def _prep_wrapped_messages(self, client_info): 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! + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! """ raise NotImplementedError() @@ -175,75 +183,78 @@ def operations_client(self): raise NotImplementedError() @property - def create_engine(self) -> Callable[ - [engine_service.CreateEngineRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def create_engine( + self, + ) -> Callable[ + [engine_service.CreateEngineRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def delete_engine(self) -> Callable[ - [engine_service.DeleteEngineRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def delete_engine( + self, + ) -> Callable[ + [engine_service.DeleteEngineRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property - def update_engine(self) -> Callable[ - [engine_service.UpdateEngineRequest], - Union[ - gcd_engine.Engine, - Awaitable[gcd_engine.Engine] - ]]: + def update_engine( + self, + ) -> Callable[ + [engine_service.UpdateEngineRequest], + Union[gcd_engine.Engine, Awaitable[gcd_engine.Engine]], + ]: raise NotImplementedError() @property - def get_engine(self) -> Callable[ - [engine_service.GetEngineRequest], - Union[ - engine.Engine, - Awaitable[engine.Engine] - ]]: + def get_engine( + self, + ) -> Callable[ + [engine_service.GetEngineRequest], + Union[engine.Engine, Awaitable[engine.Engine]], + ]: raise NotImplementedError() @property - def list_engines(self) -> Callable[ - [engine_service.ListEnginesRequest], - Union[ - engine_service.ListEnginesResponse, - Awaitable[engine_service.ListEnginesResponse] - ]]: + def list_engines( + self, + ) -> Callable[ + [engine_service.ListEnginesRequest], + Union[ + engine_service.ListEnginesResponse, + Awaitable[engine_service.ListEnginesResponse], + ], + ]: raise NotImplementedError() @property - def pause_engine(self) -> Callable[ - [engine_service.PauseEngineRequest], - Union[ - engine.Engine, - Awaitable[engine.Engine] - ]]: + def pause_engine( + self, + ) -> Callable[ + [engine_service.PauseEngineRequest], + Union[engine.Engine, Awaitable[engine.Engine]], + ]: raise NotImplementedError() @property - def resume_engine(self) -> Callable[ - [engine_service.ResumeEngineRequest], - Union[ - engine.Engine, - Awaitable[engine.Engine] - ]]: + def resume_engine( + self, + ) -> Callable[ + [engine_service.ResumeEngineRequest], + Union[engine.Engine, Awaitable[engine.Engine]], + ]: raise NotImplementedError() @property - def tune_engine(self) -> Callable[ - [engine_service.TuneEngineRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: + def tune_engine( + self, + ) -> Callable[ + [engine_service.TuneEngineRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: raise NotImplementedError() @property @@ -251,7 +262,10 @@ def list_operations( self, ) -> Callable[ [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], ]: raise NotImplementedError() @@ -269,6 +283,4 @@ def kind(self) -> str: raise NotImplementedError() -__all__ = ( - 'EngineServiceTransport', -) +__all__ = ("EngineServiceTransport",) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/grpc.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/grpc.py similarity index 79% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/grpc.py rename to packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/grpc.py index 0c2a0d8a9e70..a8097ee159d1 100644 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/grpc.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/grpc.py @@ -13,24 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore - +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore import grpc # type: ignore from google.cloud.discoveryengine_v1alpha.types import engine from google.cloud.discoveryengine_v1alpha.types import engine as gcd_engine from google.cloud.discoveryengine_v1alpha.types import engine_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import EngineServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, EngineServiceTransport class EngineServiceGrpcTransport(EngineServiceTransport): @@ -46,23 +44,26 @@ class EngineServiceGrpcTransport(EngineServiceTransport): 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 = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: + def __init__( + self, + *, + host: str = "discoveryengine.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -182,13 +183,15 @@ def __init__(self, *, self._prep_wrapped_messages(client_info) @classmethod - def create_channel(cls, - host: str = 'discoveryengine.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: + def create_channel( + cls, + host: str = "discoveryengine.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. @@ -223,13 +226,12 @@ def create_channel(cls, default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs + **kwargs, ) @property def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ + """Return the channel designed to connect to this service.""" return self._grpc_channel @property @@ -241,17 +243,15 @@ def operations_client(self) -> operations_v1.OperationsClient: """ # Quick check: Only create a new client if we do not already have one. if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) + self._operations_client = operations_v1.OperationsClient(self.grpc_channel) # Return the client from cache. return self._operations_client @property - def create_engine(self) -> Callable[ - [engine_service.CreateEngineRequest], - operations_pb2.Operation]: + def create_engine( + self, + ) -> Callable[[engine_service.CreateEngineRequest], operations_pb2.Operation]: r"""Return a callable for the create engine method over gRPC. Creates a [Engine][google.cloud.discoveryengine.v1alpha.Engine]. @@ -266,18 +266,18 @@ def create_engine(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_engine' not in self._stubs: - self._stubs['create_engine'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.EngineService/CreateEngine', + if "create_engine" not in self._stubs: + self._stubs["create_engine"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.EngineService/CreateEngine", request_serializer=engine_service.CreateEngineRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['create_engine'] + return self._stubs["create_engine"] @property - def delete_engine(self) -> Callable[ - [engine_service.DeleteEngineRequest], - operations_pb2.Operation]: + def delete_engine( + self, + ) -> Callable[[engine_service.DeleteEngineRequest], operations_pb2.Operation]: r"""Return a callable for the delete engine method over gRPC. Deletes a [Engine][google.cloud.discoveryengine.v1alpha.Engine]. @@ -292,18 +292,18 @@ def delete_engine(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_engine' not in self._stubs: - self._stubs['delete_engine'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.EngineService/DeleteEngine', + if "delete_engine" not in self._stubs: + self._stubs["delete_engine"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.EngineService/DeleteEngine", request_serializer=engine_service.DeleteEngineRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['delete_engine'] + return self._stubs["delete_engine"] @property - def update_engine(self) -> Callable[ - [engine_service.UpdateEngineRequest], - gcd_engine.Engine]: + def update_engine( + self, + ) -> Callable[[engine_service.UpdateEngineRequest], gcd_engine.Engine]: r"""Return a callable for the update engine method over gRPC. Updates an [Engine][google.cloud.discoveryengine.v1alpha.Engine] @@ -318,18 +318,16 @@ def update_engine(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_engine' not in self._stubs: - self._stubs['update_engine'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.EngineService/UpdateEngine', + if "update_engine" not in self._stubs: + self._stubs["update_engine"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.EngineService/UpdateEngine", request_serializer=engine_service.UpdateEngineRequest.serialize, response_deserializer=gcd_engine.Engine.deserialize, ) - return self._stubs['update_engine'] + return self._stubs["update_engine"] @property - def get_engine(self) -> Callable[ - [engine_service.GetEngineRequest], - engine.Engine]: + def get_engine(self) -> Callable[[engine_service.GetEngineRequest], engine.Engine]: r"""Return a callable for the get engine method over gRPC. Gets a [Engine][google.cloud.discoveryengine.v1alpha.Engine]. @@ -344,18 +342,20 @@ def get_engine(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_engine' not in self._stubs: - self._stubs['get_engine'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.EngineService/GetEngine', + if "get_engine" not in self._stubs: + self._stubs["get_engine"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.EngineService/GetEngine", request_serializer=engine_service.GetEngineRequest.serialize, response_deserializer=engine.Engine.deserialize, ) - return self._stubs['get_engine'] + return self._stubs["get_engine"] @property - def list_engines(self) -> Callable[ - [engine_service.ListEnginesRequest], - engine_service.ListEnginesResponse]: + def list_engines( + self, + ) -> Callable[ + [engine_service.ListEnginesRequest], engine_service.ListEnginesResponse + ]: r"""Return a callable for the list engines method over gRPC. Lists all the @@ -372,18 +372,18 @@ def list_engines(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_engines' not in self._stubs: - self._stubs['list_engines'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.EngineService/ListEngines', + if "list_engines" not in self._stubs: + self._stubs["list_engines"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.EngineService/ListEngines", request_serializer=engine_service.ListEnginesRequest.serialize, response_deserializer=engine_service.ListEnginesResponse.deserialize, ) - return self._stubs['list_engines'] + return self._stubs["list_engines"] @property - def pause_engine(self) -> Callable[ - [engine_service.PauseEngineRequest], - engine.Engine]: + def pause_engine( + self, + ) -> Callable[[engine_service.PauseEngineRequest], engine.Engine]: r"""Return a callable for the pause engine method over gRPC. Pauses the training of an existing engine. Only applicable if @@ -400,18 +400,18 @@ def pause_engine(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'pause_engine' not in self._stubs: - self._stubs['pause_engine'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.EngineService/PauseEngine', + if "pause_engine" not in self._stubs: + self._stubs["pause_engine"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.EngineService/PauseEngine", request_serializer=engine_service.PauseEngineRequest.serialize, response_deserializer=engine.Engine.deserialize, ) - return self._stubs['pause_engine'] + return self._stubs["pause_engine"] @property - def resume_engine(self) -> Callable[ - [engine_service.ResumeEngineRequest], - engine.Engine]: + def resume_engine( + self, + ) -> Callable[[engine_service.ResumeEngineRequest], engine.Engine]: r"""Return a callable for the resume engine method over gRPC. Resumes the training of an existing engine. Only applicable if @@ -428,18 +428,18 @@ def resume_engine(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'resume_engine' not in self._stubs: - self._stubs['resume_engine'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.EngineService/ResumeEngine', + if "resume_engine" not in self._stubs: + self._stubs["resume_engine"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.EngineService/ResumeEngine", request_serializer=engine_service.ResumeEngineRequest.serialize, response_deserializer=engine.Engine.deserialize, ) - return self._stubs['resume_engine'] + return self._stubs["resume_engine"] @property - def tune_engine(self) -> Callable[ - [engine_service.TuneEngineRequest], - operations_pb2.Operation]: + def tune_engine( + self, + ) -> Callable[[engine_service.TuneEngineRequest], operations_pb2.Operation]: r"""Return a callable for the tune engine method over gRPC. Tunes an existing engine. Only applicable if [solution_type][] @@ -456,13 +456,13 @@ def tune_engine(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'tune_engine' not in self._stubs: - self._stubs['tune_engine'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.EngineService/TuneEngine', + if "tune_engine" not in self._stubs: + self._stubs["tune_engine"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.EngineService/TuneEngine", request_serializer=engine_service.TuneEngineRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['tune_engine'] + return self._stubs["tune_engine"] def close(self): self.grpc_channel.close() @@ -471,8 +471,7 @@ def close(self): def get_operation( self, ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ + 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 @@ -488,9 +487,10 @@ def 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. - """ + ) -> 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 @@ -508,6 +508,4 @@ def kind(self) -> str: return "grpc" -__all__ = ( - 'EngineServiceGrpcTransport', -) +__all__ = ("EngineServiceGrpcTransport",) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/grpc_asyncio.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/grpc_asyncio.py similarity index 78% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/grpc_asyncio.py rename to packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/grpc_asyncio.py index 2fd747d0f02a..e0d7366b4e01 100644 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/grpc_asyncio.py @@ -13,24 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import warnings from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.discoveryengine_v1alpha.types import engine from google.cloud.discoveryengine_v1alpha.types import engine as gcd_engine from google.cloud.discoveryengine_v1alpha.types import engine_service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import EngineServiceTransport, DEFAULT_CLIENT_INFO + +from .base import DEFAULT_CLIENT_INFO, EngineServiceTransport from .grpc import EngineServiceGrpcTransport @@ -52,13 +50,15 @@ class EngineServiceGrpcAsyncIOTransport(EngineServiceTransport): _stubs: Dict[str, Callable] = {} @classmethod - def create_channel(cls, - host: str = 'discoveryengine.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: + def create_channel( + cls, + host: str = "discoveryengine.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. @@ -89,24 +89,26 @@ def create_channel(cls, default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, - **kwargs + **kwargs, ) - def __init__(self, *, - host: str = 'discoveryengine.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: + def __init__( + self, + *, + host: str = "discoveryengine.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -252,9 +254,11 @@ def operations_client(self) -> operations_v1.OperationsAsyncClient: return self._operations_client @property - def create_engine(self) -> Callable[ - [engine_service.CreateEngineRequest], - Awaitable[operations_pb2.Operation]]: + def create_engine( + self, + ) -> Callable[ + [engine_service.CreateEngineRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the create engine method over gRPC. Creates a [Engine][google.cloud.discoveryengine.v1alpha.Engine]. @@ -269,18 +273,20 @@ def create_engine(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'create_engine' not in self._stubs: - self._stubs['create_engine'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.EngineService/CreateEngine', + if "create_engine" not in self._stubs: + self._stubs["create_engine"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.EngineService/CreateEngine", request_serializer=engine_service.CreateEngineRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['create_engine'] + return self._stubs["create_engine"] @property - def delete_engine(self) -> Callable[ - [engine_service.DeleteEngineRequest], - Awaitable[operations_pb2.Operation]]: + def delete_engine( + self, + ) -> Callable[ + [engine_service.DeleteEngineRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the delete engine method over gRPC. Deletes a [Engine][google.cloud.discoveryengine.v1alpha.Engine]. @@ -295,18 +301,18 @@ def delete_engine(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'delete_engine' not in self._stubs: - self._stubs['delete_engine'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.EngineService/DeleteEngine', + if "delete_engine" not in self._stubs: + self._stubs["delete_engine"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.EngineService/DeleteEngine", request_serializer=engine_service.DeleteEngineRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['delete_engine'] + return self._stubs["delete_engine"] @property - def update_engine(self) -> Callable[ - [engine_service.UpdateEngineRequest], - Awaitable[gcd_engine.Engine]]: + def update_engine( + self, + ) -> Callable[[engine_service.UpdateEngineRequest], Awaitable[gcd_engine.Engine]]: r"""Return a callable for the update engine method over gRPC. Updates an [Engine][google.cloud.discoveryengine.v1alpha.Engine] @@ -321,18 +327,18 @@ def update_engine(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'update_engine' not in self._stubs: - self._stubs['update_engine'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.EngineService/UpdateEngine', + if "update_engine" not in self._stubs: + self._stubs["update_engine"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.EngineService/UpdateEngine", request_serializer=engine_service.UpdateEngineRequest.serialize, response_deserializer=gcd_engine.Engine.deserialize, ) - return self._stubs['update_engine'] + return self._stubs["update_engine"] @property - def get_engine(self) -> Callable[ - [engine_service.GetEngineRequest], - Awaitable[engine.Engine]]: + def get_engine( + self, + ) -> Callable[[engine_service.GetEngineRequest], Awaitable[engine.Engine]]: r"""Return a callable for the get engine method over gRPC. Gets a [Engine][google.cloud.discoveryengine.v1alpha.Engine]. @@ -347,18 +353,21 @@ def get_engine(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'get_engine' not in self._stubs: - self._stubs['get_engine'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.EngineService/GetEngine', + if "get_engine" not in self._stubs: + self._stubs["get_engine"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.EngineService/GetEngine", request_serializer=engine_service.GetEngineRequest.serialize, response_deserializer=engine.Engine.deserialize, ) - return self._stubs['get_engine'] + return self._stubs["get_engine"] @property - def list_engines(self) -> Callable[ - [engine_service.ListEnginesRequest], - Awaitable[engine_service.ListEnginesResponse]]: + def list_engines( + self, + ) -> Callable[ + [engine_service.ListEnginesRequest], + Awaitable[engine_service.ListEnginesResponse], + ]: r"""Return a callable for the list engines method over gRPC. Lists all the @@ -375,18 +384,18 @@ def list_engines(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'list_engines' not in self._stubs: - self._stubs['list_engines'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.EngineService/ListEngines', + if "list_engines" not in self._stubs: + self._stubs["list_engines"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.EngineService/ListEngines", request_serializer=engine_service.ListEnginesRequest.serialize, response_deserializer=engine_service.ListEnginesResponse.deserialize, ) - return self._stubs['list_engines'] + return self._stubs["list_engines"] @property - def pause_engine(self) -> Callable[ - [engine_service.PauseEngineRequest], - Awaitable[engine.Engine]]: + def pause_engine( + self, + ) -> Callable[[engine_service.PauseEngineRequest], Awaitable[engine.Engine]]: r"""Return a callable for the pause engine method over gRPC. Pauses the training of an existing engine. Only applicable if @@ -403,18 +412,18 @@ def pause_engine(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'pause_engine' not in self._stubs: - self._stubs['pause_engine'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.EngineService/PauseEngine', + if "pause_engine" not in self._stubs: + self._stubs["pause_engine"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.EngineService/PauseEngine", request_serializer=engine_service.PauseEngineRequest.serialize, response_deserializer=engine.Engine.deserialize, ) - return self._stubs['pause_engine'] + return self._stubs["pause_engine"] @property - def resume_engine(self) -> Callable[ - [engine_service.ResumeEngineRequest], - Awaitable[engine.Engine]]: + def resume_engine( + self, + ) -> Callable[[engine_service.ResumeEngineRequest], Awaitable[engine.Engine]]: r"""Return a callable for the resume engine method over gRPC. Resumes the training of an existing engine. Only applicable if @@ -431,18 +440,20 @@ def resume_engine(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'resume_engine' not in self._stubs: - self._stubs['resume_engine'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.EngineService/ResumeEngine', + if "resume_engine" not in self._stubs: + self._stubs["resume_engine"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.EngineService/ResumeEngine", request_serializer=engine_service.ResumeEngineRequest.serialize, response_deserializer=engine.Engine.deserialize, ) - return self._stubs['resume_engine'] + return self._stubs["resume_engine"] @property - def tune_engine(self) -> Callable[ - [engine_service.TuneEngineRequest], - Awaitable[operations_pb2.Operation]]: + def tune_engine( + self, + ) -> Callable[ + [engine_service.TuneEngineRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the tune engine method over gRPC. Tunes an existing engine. Only applicable if [solution_type][] @@ -459,13 +470,13 @@ def tune_engine(self) -> Callable[ # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if 'tune_engine' not in self._stubs: - self._stubs['tune_engine'] = self.grpc_channel.unary_unary( - '/google.cloud.discoveryengine.v1alpha.EngineService/TuneEngine', + if "tune_engine" not in self._stubs: + self._stubs["tune_engine"] = self.grpc_channel.unary_unary( + "/google.cloud.discoveryengine.v1alpha.EngineService/TuneEngine", request_serializer=engine_service.TuneEngineRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) - return self._stubs['tune_engine'] + return self._stubs["tune_engine"] def close(self): return self.grpc_channel.close() @@ -474,8 +485,7 @@ def close(self): def get_operation( self, ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ + 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 @@ -491,9 +501,10 @@ def 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. - """ + ) -> 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 @@ -507,6 +518,4 @@ def list_operations( return self._stubs["list_operations"] -__all__ = ( - 'EngineServiceGrpcAsyncIOTransport', -) +__all__ = ("EngineServiceGrpcAsyncIOTransport",) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/rest.py similarity index 62% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/rest.py rename to packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/rest.py index b763e7a23378..99d2c9785d5b 100644 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/rest.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/services/engine_service/transports/rest.py @@ -14,26 +14,28 @@ # limitations under the License. # -from google.auth.transport.requests import AuthorizedSession # type: ignore +import dataclasses import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import ( + gapic_v1, + operations_v1, + path_template, + rest_helpers, + rest_streaming, +) from google.api_core import exceptions as core_exceptions from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore from google.protobuf import json_format -from google.api_core import operations_v1 -from google.cloud.location import locations_pb2 # type: ignore +import grpc # type: ignore from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] @@ -41,13 +43,14 @@ OptionalRetry = Union[retries.Retry, object] # type: ignore +from google.longrunning import operations_pb2 # type: ignore + from google.cloud.discoveryengine_v1alpha.types import engine from google.cloud.discoveryengine_v1alpha.types import engine as gcd_engine from google.cloud.discoveryengine_v1alpha.types import engine_service -from google.longrunning import operations_pb2 # type: ignore - -from .base import EngineServiceTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import EngineServiceTransport DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, @@ -140,7 +143,12 @@ def post_update_engine(self, response): """ - def pre_create_engine(self, request: engine_service.CreateEngineRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[engine_service.CreateEngineRequest, Sequence[Tuple[str, str]]]: + + def pre_create_engine( + self, + request: engine_service.CreateEngineRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[engine_service.CreateEngineRequest, Sequence[Tuple[str, str]]]: """Pre-rpc interceptor for create_engine Override in a subclass to manipulate the request or metadata @@ -148,7 +156,9 @@ def pre_create_engine(self, request: engine_service.CreateEngineRequest, metadat """ return request, metadata - def post_create_engine(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_create_engine( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for create_engine Override in a subclass to manipulate the response @@ -156,7 +166,12 @@ def post_create_engine(self, response: operations_pb2.Operation) -> operations_p it is returned to user code. """ return response - def pre_delete_engine(self, request: engine_service.DeleteEngineRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[engine_service.DeleteEngineRequest, Sequence[Tuple[str, str]]]: + + def pre_delete_engine( + self, + request: engine_service.DeleteEngineRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[engine_service.DeleteEngineRequest, Sequence[Tuple[str, str]]]: """Pre-rpc interceptor for delete_engine Override in a subclass to manipulate the request or metadata @@ -164,7 +179,9 @@ def pre_delete_engine(self, request: engine_service.DeleteEngineRequest, metadat """ return request, metadata - def post_delete_engine(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_delete_engine( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for delete_engine Override in a subclass to manipulate the response @@ -172,7 +189,12 @@ def post_delete_engine(self, response: operations_pb2.Operation) -> operations_p it is returned to user code. """ return response - def pre_get_engine(self, request: engine_service.GetEngineRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[engine_service.GetEngineRequest, Sequence[Tuple[str, str]]]: + + def pre_get_engine( + self, + request: engine_service.GetEngineRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[engine_service.GetEngineRequest, Sequence[Tuple[str, str]]]: """Pre-rpc interceptor for get_engine Override in a subclass to manipulate the request or metadata @@ -188,7 +210,12 @@ def post_get_engine(self, response: engine.Engine) -> engine.Engine: it is returned to user code. """ return response - def pre_list_engines(self, request: engine_service.ListEnginesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[engine_service.ListEnginesRequest, Sequence[Tuple[str, str]]]: + + def pre_list_engines( + self, + request: engine_service.ListEnginesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[engine_service.ListEnginesRequest, Sequence[Tuple[str, str]]]: """Pre-rpc interceptor for list_engines Override in a subclass to manipulate the request or metadata @@ -196,7 +223,9 @@ def pre_list_engines(self, request: engine_service.ListEnginesRequest, metadata: """ return request, metadata - def post_list_engines(self, response: engine_service.ListEnginesResponse) -> engine_service.ListEnginesResponse: + def post_list_engines( + self, response: engine_service.ListEnginesResponse + ) -> engine_service.ListEnginesResponse: """Post-rpc interceptor for list_engines Override in a subclass to manipulate the response @@ -204,7 +233,12 @@ def post_list_engines(self, response: engine_service.ListEnginesResponse) -> eng it is returned to user code. """ return response - def pre_pause_engine(self, request: engine_service.PauseEngineRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[engine_service.PauseEngineRequest, Sequence[Tuple[str, str]]]: + + def pre_pause_engine( + self, + request: engine_service.PauseEngineRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[engine_service.PauseEngineRequest, Sequence[Tuple[str, str]]]: """Pre-rpc interceptor for pause_engine Override in a subclass to manipulate the request or metadata @@ -220,7 +254,12 @@ def post_pause_engine(self, response: engine.Engine) -> engine.Engine: it is returned to user code. """ return response - def pre_resume_engine(self, request: engine_service.ResumeEngineRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[engine_service.ResumeEngineRequest, Sequence[Tuple[str, str]]]: + + def pre_resume_engine( + self, + request: engine_service.ResumeEngineRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[engine_service.ResumeEngineRequest, Sequence[Tuple[str, str]]]: """Pre-rpc interceptor for resume_engine Override in a subclass to manipulate the request or metadata @@ -236,7 +275,12 @@ def post_resume_engine(self, response: engine.Engine) -> engine.Engine: it is returned to user code. """ return response - def pre_tune_engine(self, request: engine_service.TuneEngineRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[engine_service.TuneEngineRequest, Sequence[Tuple[str, str]]]: + + def pre_tune_engine( + self, + request: engine_service.TuneEngineRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[engine_service.TuneEngineRequest, Sequence[Tuple[str, str]]]: """Pre-rpc interceptor for tune_engine Override in a subclass to manipulate the request or metadata @@ -244,7 +288,9 @@ def pre_tune_engine(self, request: engine_service.TuneEngineRequest, metadata: S """ return request, metadata - def post_tune_engine(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + def post_tune_engine( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: """Post-rpc interceptor for tune_engine Override in a subclass to manipulate the response @@ -252,7 +298,12 @@ def post_tune_engine(self, response: operations_pb2.Operation) -> operations_pb2 it is returned to user code. """ return response - def pre_update_engine(self, request: engine_service.UpdateEngineRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[engine_service.UpdateEngineRequest, Sequence[Tuple[str, str]]]: + + def pre_update_engine( + self, + request: engine_service.UpdateEngineRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[engine_service.UpdateEngineRequest, Sequence[Tuple[str, str]]]: """Pre-rpc interceptor for update_engine Override in a subclass to manipulate the request or metadata @@ -270,7 +321,9 @@ def post_update_engine(self, response: gcd_engine.Engine) -> gcd_engine.Engine: return response def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, str]], ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: """Pre-rpc interceptor for get_operation @@ -289,8 +342,11 @@ def post_get_operation( it is returned to user code. """ return response + def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, str]], ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: """Pre-rpc interceptor for list_operations @@ -332,20 +388,21 @@ class EngineServiceRestTransport(EngineServiceTransport): """ - def __init__(self, *, - host: str = 'discoveryengine.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[EngineServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: + def __init__( + self, + *, + host: str = "discoveryengine.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[EngineServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: """Instantiate the transport. Args: @@ -384,7 +441,9 @@ def __init__(self, *, # credentials object maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER url_match_items = maybe_url_match.groupdict() @@ -395,10 +454,11 @@ def __init__(self, *, credentials=credentials, client_info=client_info, always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience + api_audience=api_audience, ) self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) + self._credentials, default_host=self.DEFAULT_HOST + ) self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None if client_cert_source_for_mtls: self._session.configure_mtls_channel(client_cert_source_for_mtls) @@ -415,125 +475,128 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Only create a new client if we do not already have one. if self._operations_client is None: http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.GetOperation': [ + "google.longrunning.Operations.GetOperation": [ { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/engines/*/operations/*}", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/operations/*}', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/operations/*}", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/operations/*}', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*/operations/*}", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/operations/*}', + "method": "get", + "uri": "/v1alpha/{name=projects/*/operations/*}", }, ], - 'google.longrunning.Operations.ListOperations': [ + "google.longrunning.Operations.ListOperations": [ { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}/operations", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}/operations', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}/operations", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*}/operations', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*}/operations", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*}/operations", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*}/operations', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*}/operations", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*}/operations', + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*}/operations", }, { - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*}/operations', + "method": "get", + "uri": "/v1alpha/{name=projects/*}/operations", }, ], } rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1alpha") + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1alpha", + ) - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) # Return the client from cache. return self._operations_client @@ -542,19 +605,26 @@ class _CreateEngine(EngineServiceRestStub): def __hash__(self): return hash("CreateEngine") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "engineId" : "", } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "engineId": "", + } @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: engine_service.CreateEngineRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: engine_service.CreateEngineRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: r"""Call the create engine method over HTTP. Args: @@ -576,11 +646,12 @@ def __call__(self, """ - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1alpha/{parent=projects/*/locations/*/collections/*}/engines', - 'body': 'engine', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{parent=projects/*/locations/*/collections/*}/engines", + "body": "engine", + }, ] request, metadata = self._interceptor.pre_create_engine(request, metadata) pb_request = engine_service.CreateEngineRequest.pb(request) @@ -589,33 +660,35 @@ def __call__(self, # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], + transcoded_request["body"], including_default_value_fields=False, - use_integers_for_enums=True + use_integers_for_enums=True, ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] + uri = transcoded_request["uri"] + method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) query_params.update(self._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" # Send the request headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(self._session, method)( "{host}{uri}".format(host=self._host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -632,19 +705,24 @@ class _DeleteEngine(EngineServiceRestStub): def __hash__(self): return hash("DeleteEngine") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: engine_service.DeleteEngineRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: engine_service.DeleteEngineRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: r"""Call the delete engine method over HTTP. Args: @@ -666,37 +744,40 @@ def __call__(self, """ - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}", + }, ] request, metadata = self._interceptor.pre_delete_engine(request, metadata) pb_request = engine_service.DeleteEngineRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) - uri = transcoded_request['uri'] - method = transcoded_request['method'] + uri = transcoded_request["uri"] + method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) query_params.update(self._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" # Send the request headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(self._session, method)( "{host}{uri}".format(host=self._host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -713,19 +794,24 @@ class _GetEngine(EngineServiceRestStub): def __hash__(self): return hash("GetEngine") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: engine_service.GetEngineRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> engine.Engine: + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: engine_service.GetEngineRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> engine.Engine: r"""Call the get engine method over HTTP. Args: @@ -747,37 +833,40 @@ def __call__(self, """ - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}", + }, ] request, metadata = self._interceptor.pre_get_engine(request, metadata) pb_request = engine_service.GetEngineRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) - uri = transcoded_request['uri'] - method = transcoded_request['method'] + uri = transcoded_request["uri"] + method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) query_params.update(self._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" # Send the request headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(self._session, method)( "{host}{uri}".format(host=self._host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -796,19 +885,24 @@ class _ListEngines(EngineServiceRestStub): def __hash__(self): return hash("ListEngines") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: engine_service.ListEnginesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> engine_service.ListEnginesResponse: + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: engine_service.ListEnginesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> engine_service.ListEnginesResponse: r"""Call the list engines method over HTTP. Args: @@ -830,37 +924,40 @@ def __call__(self, """ - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{parent=projects/*/locations/*/collections/*}/engines', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{parent=projects/*/locations/*/collections/*}/engines", + }, ] request, metadata = self._interceptor.pre_list_engines(request, metadata) pb_request = engine_service.ListEnginesRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) - uri = transcoded_request['uri'] - method = transcoded_request['method'] + uri = transcoded_request["uri"] + method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) query_params.update(self._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" # Send the request headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(self._session, method)( "{host}{uri}".format(host=self._host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -879,19 +976,24 @@ class _PauseEngine(EngineServiceRestStub): def __hash__(self): return hash("PauseEngine") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: engine_service.PauseEngineRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> engine.Engine: + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: engine_service.PauseEngineRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> engine.Engine: r"""Call the pause engine method over HTTP. Args: @@ -912,11 +1014,12 @@ def __call__(self, """ - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}:pause', - 'body': '*', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}:pause", + "body": "*", + }, ] request, metadata = self._interceptor.pre_pause_engine(request, metadata) pb_request = engine_service.PauseEngineRequest.pb(request) @@ -925,33 +1028,35 @@ def __call__(self, # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], + transcoded_request["body"], including_default_value_fields=False, - use_integers_for_enums=True + use_integers_for_enums=True, ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] + uri = transcoded_request["uri"] + method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) query_params.update(self._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" # Send the request headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(self._session, method)( "{host}{uri}".format(host=self._host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -970,19 +1075,24 @@ class _ResumeEngine(EngineServiceRestStub): def __hash__(self): return hash("ResumeEngine") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: engine_service.ResumeEngineRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> engine.Engine: + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: engine_service.ResumeEngineRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> engine.Engine: r"""Call the resume engine method over HTTP. Args: @@ -1003,11 +1113,12 @@ def __call__(self, """ - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}:resume', - 'body': '*', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}:resume", + "body": "*", + }, ] request, metadata = self._interceptor.pre_resume_engine(request, metadata) pb_request = engine_service.ResumeEngineRequest.pb(request) @@ -1016,33 +1127,35 @@ def __call__(self, # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], + transcoded_request["body"], including_default_value_fields=False, - use_integers_for_enums=True + use_integers_for_enums=True, ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] + uri = transcoded_request["uri"] + method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) query_params.update(self._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" # Send the request headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(self._session, method)( "{host}{uri}".format(host=self._host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1061,19 +1174,24 @@ class _TuneEngine(EngineServiceRestStub): def __hash__(self): return hash("TuneEngine") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: engine_service.TuneEngineRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: engine_service.TuneEngineRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: r"""Call the tune engine method over HTTP. Args: @@ -1096,11 +1214,12 @@ def __call__(self, """ - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}:tune', - 'body': '*', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}:tune", + "body": "*", + }, ] request, metadata = self._interceptor.pre_tune_engine(request, metadata) pb_request = engine_service.TuneEngineRequest.pb(request) @@ -1109,33 +1228,35 @@ def __call__(self, # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], + transcoded_request["body"], including_default_value_fields=False, - use_integers_for_enums=True + use_integers_for_enums=True, ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] + uri = transcoded_request["uri"] + method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) query_params.update(self._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" # Send the request headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(self._session, method)( "{host}{uri}".format(host=self._host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1152,19 +1273,24 @@ class _UpdateEngine(EngineServiceRestStub): def __hash__(self): return hash("UpdateEngine") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: engine_service.UpdateEngineRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> gcd_engine.Engine: + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: engine_service.UpdateEngineRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcd_engine.Engine: r"""Call the update engine method over HTTP. Args: @@ -1186,11 +1312,12 @@ def __call__(self, """ - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1alpha/{engine.name=projects/*/locations/*/collections/*/engines/*}', - 'body': 'engine', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1alpha/{engine.name=projects/*/locations/*/collections/*/engines/*}", + "body": "engine", + }, ] request, metadata = self._interceptor.pre_update_engine(request, metadata) pb_request = engine_service.UpdateEngineRequest.pb(request) @@ -1199,33 +1326,35 @@ def __call__(self, # Jsonify the request body body = json_format.MessageToJson( - transcoded_request['body'], + transcoded_request["body"], including_default_value_fields=False, - use_integers_for_enums=True + use_integers_for_enums=True, ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] + uri = transcoded_request["uri"] + method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) query_params.update(self._get_unset_required_fields(query_params)) query_params["$alt"] = "json;enum-encoding=int" # Send the request headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(self._session, method)( "{host}{uri}".format(host=self._host, uri=uri), timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), data=body, - ) + ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception # subclass. @@ -1241,81 +1370,82 @@ def __call__(self, return resp @property - def create_engine(self) -> Callable[ - [engine_service.CreateEngineRequest], - operations_pb2.Operation]: + def create_engine( + self, + ) -> Callable[[engine_service.CreateEngineRequest], 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._CreateEngine(self._session, self._host, self._interceptor) # type: ignore + return self._CreateEngine(self._session, self._host, self._interceptor) # type: ignore @property - def delete_engine(self) -> Callable[ - [engine_service.DeleteEngineRequest], - operations_pb2.Operation]: + def delete_engine( + self, + ) -> Callable[[engine_service.DeleteEngineRequest], 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._DeleteEngine(self._session, self._host, self._interceptor) # type: ignore + return self._DeleteEngine(self._session, self._host, self._interceptor) # type: ignore @property - def get_engine(self) -> Callable[ - [engine_service.GetEngineRequest], - engine.Engine]: + def get_engine(self) -> Callable[[engine_service.GetEngineRequest], engine.Engine]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._GetEngine(self._session, self._host, self._interceptor) # type: ignore + return self._GetEngine(self._session, self._host, self._interceptor) # type: ignore @property - def list_engines(self) -> Callable[ - [engine_service.ListEnginesRequest], - engine_service.ListEnginesResponse]: + def list_engines( + self, + ) -> Callable[ + [engine_service.ListEnginesRequest], engine_service.ListEnginesResponse + ]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._ListEngines(self._session, self._host, self._interceptor) # type: ignore + return self._ListEngines(self._session, self._host, self._interceptor) # type: ignore @property - def pause_engine(self) -> Callable[ - [engine_service.PauseEngineRequest], - engine.Engine]: + def pause_engine( + self, + ) -> Callable[[engine_service.PauseEngineRequest], engine.Engine]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._PauseEngine(self._session, self._host, self._interceptor) # type: ignore + return self._PauseEngine(self._session, self._host, self._interceptor) # type: ignore @property - def resume_engine(self) -> Callable[ - [engine_service.ResumeEngineRequest], - engine.Engine]: + def resume_engine( + self, + ) -> Callable[[engine_service.ResumeEngineRequest], engine.Engine]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._ResumeEngine(self._session, self._host, self._interceptor) # type: ignore + return self._ResumeEngine(self._session, self._host, self._interceptor) # type: ignore @property - def tune_engine(self) -> Callable[ - [engine_service.TuneEngineRequest], - operations_pb2.Operation]: + def tune_engine( + self, + ) -> Callable[[engine_service.TuneEngineRequest], 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._TuneEngine(self._session, self._host, self._interceptor) # type: ignore + return self._TuneEngine(self._session, self._host, self._interceptor) # type: ignore @property - def update_engine(self) -> Callable[ - [engine_service.UpdateEngineRequest], - gcd_engine.Engine]: + def update_engine( + self, + ) -> Callable[[engine_service.UpdateEngineRequest], gcd_engine.Engine]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. # In C++ this would require a dynamic_cast - return self._UpdateEngine(self._session, self._host, self._interceptor) # type: ignore + return self._UpdateEngine(self._session, self._host, self._interceptor) # type: ignore @property def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore class _GetOperation(EngineServiceRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: r"""Call the get operation method over HTTP. Args: @@ -1331,74 +1461,74 @@ def __call__(self, operations_pb2.Operation: Response from GetOperation method. """ - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/operations/*}', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/operations/*}', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/engines/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/operations/*}", + }, ] request, metadata = self._interceptor.pre_get_operation(request, metadata) request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) + transcoded_request = path_template.transcode(http_options, **request_kwargs) - uri = transcoded_request['uri'] - method = transcoded_request['method'] + uri = transcoded_request["uri"] + method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) + query_params = json.loads(json.dumps(transcoded_request["query_params"])) # Send the request headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(self._session, method)( "{host}{uri}".format(host=self._host, uri=uri), @@ -1419,16 +1549,17 @@ def __call__(self, @property def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore class _ListOperations(EngineServiceRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: r"""Call the list operations method over HTTP. Args: @@ -1444,74 +1575,74 @@ def __call__(self, operations_pb2.ListOperationsResponse: Response from ListOperations method. """ - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/collections/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*/locations/*}/operations', - }, -{ - 'method': 'get', - 'uri': '/v1alpha/{name=projects/*}/operations', - }, + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/dataStores/*}/operations", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}/operations", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/collections/*}/operations", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*/branches/*}/operations", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*/models/*}/operations", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*/dataStores/*}/operations", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v1alpha/{name=projects/*}/operations", + }, ] request, metadata = self._interceptor.pre_list_operations(request, metadata) request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) + transcoded_request = path_template.transcode(http_options, **request_kwargs) - uri = transcoded_request['uri'] - method = transcoded_request['method'] + uri = transcoded_request["uri"] + method = transcoded_request["method"] # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) + query_params = json.loads(json.dumps(transcoded_request["query_params"])) # Send the request headers = dict(metadata) - headers['Content-Type'] = 'application/json' + headers["Content-Type"] = "application/json" response = getattr(self._session, method)( "{host}{uri}".format(host=self._host, uri=uri), @@ -1538,6 +1669,4 @@ def close(self): self._session.close() -__all__=( - 'EngineServiceRestTransport', -) +__all__ = ("EngineServiceRestTransport",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/__init__.py index 1307be8e3188..155ada9e8c6c 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/__init__.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/__init__.py @@ -13,7 +13,16 @@ # See the License for the specific language governing permissions and # limitations under the License. # -from .common import CustomAttribute, DoubleList, Interval, SolutionType, UserInfo +from .common import ( + CustomAttribute, + DoubleList, + IndustryVertical, + Interval, + SearchAddOn, + SearchTier, + SolutionType, + UserInfo, +) from .completion_service import CompleteQueryRequest, CompleteQueryResponse from .conversation import ( Conversation, @@ -32,6 +41,17 @@ ListConversationsResponse, UpdateConversationRequest, ) +from .data_store import DataStore +from .data_store_service import ( + CreateDataStoreMetadata, + CreateDataStoreRequest, + DeleteDataStoreMetadata, + DeleteDataStoreRequest, + GetDataStoreRequest, + ListDataStoresRequest, + ListDataStoresResponse, + UpdateDataStoreRequest, +) from .document import Document from .document_service import ( CreateDocumentRequest, @@ -41,6 +61,22 @@ ListDocumentsResponse, UpdateDocumentRequest, ) +from .engine import Engine +from .engine_service import ( + CreateEngineMetadata, + CreateEngineRequest, + DeleteEngineMetadata, + DeleteEngineRequest, + GetEngineRequest, + ListEnginesRequest, + ListEnginesResponse, + PauseEngineRequest, + ResumeEngineRequest, + TuneEngineMetadata, + TuneEngineRequest, + TuneEngineResponse, + UpdateEngineRequest, +) from .import_config import ( BigQuerySource, GcsSource, @@ -96,6 +132,9 @@ "DoubleList", "Interval", "UserInfo", + "IndustryVertical", + "SearchAddOn", + "SearchTier", "SolutionType", "CompleteQueryRequest", "CompleteQueryResponse", @@ -112,6 +151,15 @@ "ListConversationsRequest", "ListConversationsResponse", "UpdateConversationRequest", + "DataStore", + "CreateDataStoreMetadata", + "CreateDataStoreRequest", + "DeleteDataStoreMetadata", + "DeleteDataStoreRequest", + "GetDataStoreRequest", + "ListDataStoresRequest", + "ListDataStoresResponse", + "UpdateDataStoreRequest", "Document", "CreateDocumentRequest", "DeleteDocumentRequest", @@ -119,6 +167,20 @@ "ListDocumentsRequest", "ListDocumentsResponse", "UpdateDocumentRequest", + "Engine", + "CreateEngineMetadata", + "CreateEngineRequest", + "DeleteEngineMetadata", + "DeleteEngineRequest", + "GetEngineRequest", + "ListEnginesRequest", + "ListEnginesResponse", + "PauseEngineRequest", + "ResumeEngineRequest", + "TuneEngineMetadata", + "TuneEngineRequest", + "TuneEngineResponse", + "UpdateEngineRequest", "BigQuerySource", "GcsSource", "ImportDocumentsMetadata", diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/common.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/common.py index 419a6f859e6a..a42c55f67dcb 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/common.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/common.py @@ -22,7 +22,10 @@ __protobuf__ = proto.module( package="google.cloud.discoveryengine.v1alpha", manifest={ + "IndustryVertical", "SolutionType", + "SearchTier", + "SearchAddOn", "Interval", "CustomAttribute", "UserInfo", @@ -31,6 +34,24 @@ ) +class IndustryVertical(proto.Enum): + r"""The industry vertical associated with the + [DataStore][google.cloud.discoveryengine.v1alpha.DataStore]. + + Values: + INDUSTRY_VERTICAL_UNSPECIFIED (0): + Value used when unset. + GENERIC (1): + The generic vertical for documents that are + not specific to any industry vertical. + MEDIA (2): + The media industry vertical. + """ + INDUSTRY_VERTICAL_UNSPECIFIED = 0 + GENERIC = 1 + MEDIA = 2 + + class SolutionType(proto.Enum): r"""The type of solution. @@ -51,6 +72,39 @@ class SolutionType(proto.Enum): SOLUTION_TYPE_CHAT = 3 +class SearchTier(proto.Enum): + r"""Tiers of search features. Different tiers might have + different pricing. To learn more, please check the pricing + documentation. + + Values: + SEARCH_TIER_UNSPECIFIED (0): + Default value when the enum is unspecified. + This is invalid to use. + SEARCH_TIER_STANDARD (1): + Standard tier. + SEARCH_TIER_ENTERPRISE (2): + Enterprise tier. + """ + SEARCH_TIER_UNSPECIFIED = 0 + SEARCH_TIER_STANDARD = 1 + SEARCH_TIER_ENTERPRISE = 2 + + +class SearchAddOn(proto.Enum): + r"""Add-on that provides additional functionality for search. + + Values: + SEARCH_ADD_ON_UNSPECIFIED (0): + Default value when the enum is unspecified. + This is invalid to use. + SEARCH_ADD_ON_LLM (1): + Large language model add-on. + """ + SEARCH_ADD_ON_UNSPECIFIED = 0 + SEARCH_ADD_ON_LLM = 1 + + class Interval(proto.Message): r"""A floating point interval. diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/data_store.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/data_store.py similarity index 98% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/data_store.py rename to packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/data_store.py index 6c7de7410189..612788945f72 100644 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/data_store.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/data_store.py @@ -17,16 +17,15 @@ from typing import MutableMapping, MutableSequence +from google.protobuf import timestamp_pb2 # type: ignore import proto # type: ignore from google.cloud.discoveryengine_v1alpha.types import common -from google.protobuf import timestamp_pb2 # type: ignore - __protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1alpha', + package="google.cloud.discoveryengine.v1alpha", manifest={ - 'DataStore', + "DataStore", }, ) @@ -74,6 +73,7 @@ class DataStore(proto.Message): [DataStore][google.cloud.discoveryengine.v1alpha.DataStore] was created at. """ + class ContentConfig(proto.Enum): r"""Content config of the data store. diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/data_store_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/data_store_service.py similarity index 97% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/data_store_service.py rename to packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/data_store_service.py index a35ac9c474c7..93561e06271b 100644 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/data_store_service.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/data_store_service.py @@ -17,24 +17,23 @@ from typing import MutableMapping, MutableSequence -import proto # type: ignore - -from google.cloud.discoveryengine_v1alpha.types import data_store as gcd_data_store from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore +from google.cloud.discoveryengine_v1alpha.types import data_store as gcd_data_store __protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1alpha', + package="google.cloud.discoveryengine.v1alpha", manifest={ - 'CreateDataStoreRequest', - 'GetDataStoreRequest', - 'CreateDataStoreMetadata', - 'ListDataStoresRequest', - 'ListDataStoresResponse', - 'DeleteDataStoreRequest', - 'UpdateDataStoreRequest', - 'DeleteDataStoreMetadata', + "CreateDataStoreRequest", + "GetDataStoreRequest", + "CreateDataStoreMetadata", + "ListDataStoresRequest", + "ListDataStoresResponse", + "DeleteDataStoreRequest", + "UpdateDataStoreRequest", + "DeleteDataStoreMetadata", }, ) diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/engine.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/engine.py similarity index 94% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/engine.py rename to packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/engine.py index 7847214528b9..de94031669f8 100644 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/engine.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/engine.py @@ -17,16 +17,15 @@ from typing import MutableMapping, MutableSequence +from google.protobuf import timestamp_pb2 # type: ignore import proto # type: ignore from google.cloud.discoveryengine_v1alpha.types import common -from google.protobuf import timestamp_pb2 # type: ignore - __protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1alpha', + package="google.cloud.discoveryengine.v1alpha", manifest={ - 'Engine', + "Engine", }, ) @@ -175,8 +174,7 @@ class SearchEngineConfig(proto.Message): ) class SimilarDocumentsEngineConfig(proto.Message): - r"""Additional config specs for a ``similar-items`` engine. - """ + r"""Additional config specs for a ``similar-items`` engine.""" class MediaRecommendationEngineConfig(proto.Message): r"""Additional config specs for a Media Recommendation engine. @@ -229,6 +227,7 @@ class MediaRecommendationEngineConfig(proto.Message): The default value for ``UpdateEngine`` method is to keep the state the same as before. """ + class TrainingState(proto.Enum): r"""The training state of the engine. @@ -273,15 +272,17 @@ class OptimizationObjectiveConfig(proto.Message): proto.STRING, number=2, ) - optimization_objective_config: 'Engine.MediaRecommendationEngineConfig.OptimizationObjectiveConfig' = proto.Field( + optimization_objective_config: "Engine.MediaRecommendationEngineConfig.OptimizationObjectiveConfig" = proto.Field( proto.MESSAGE, number=3, - message='Engine.MediaRecommendationEngineConfig.OptimizationObjectiveConfig', + message="Engine.MediaRecommendationEngineConfig.OptimizationObjectiveConfig", ) - training_state: 'Engine.MediaRecommendationEngineConfig.TrainingState' = proto.Field( - proto.ENUM, - number=4, - enum='Engine.MediaRecommendationEngineConfig.TrainingState', + training_state: "Engine.MediaRecommendationEngineConfig.TrainingState" = ( + proto.Field( + proto.ENUM, + number=4, + enum="Engine.MediaRecommendationEngineConfig.TrainingState", + ) ) class ChatEngineConfig(proto.Message): @@ -359,10 +360,12 @@ class AgentCreationConfig(proto.Message): number=3, ) - agent_creation_config: 'Engine.ChatEngineConfig.AgentCreationConfig' = proto.Field( - proto.MESSAGE, - number=1, - message='Engine.ChatEngineConfig.AgentCreationConfig', + agent_creation_config: "Engine.ChatEngineConfig.AgentCreationConfig" = ( + proto.Field( + proto.MESSAGE, + number=1, + message="Engine.ChatEngineConfig.AgentCreationConfig", + ) ) dialogflow_agent_to_link: str = proto.Field( proto.STRING, @@ -416,6 +419,7 @@ class RecommendationMetadata(proto.Message): the engine resource format. If no tuning has happened for this engine, the string is empty. """ + class ServingState(proto.Enum): r"""The serving state of the recommendation engine. @@ -454,15 +458,15 @@ class DataState(proto.Enum): DATA_OK = 1 DATA_ERROR = 2 - serving_state: 'Engine.RecommendationMetadata.ServingState' = proto.Field( + serving_state: "Engine.RecommendationMetadata.ServingState" = proto.Field( proto.ENUM, number=1, - enum='Engine.RecommendationMetadata.ServingState', + enum="Engine.RecommendationMetadata.ServingState", ) - data_state: 'Engine.RecommendationMetadata.DataState' = proto.Field( + data_state: "Engine.RecommendationMetadata.DataState" = proto.Field( proto.ENUM, number=2, - enum='Engine.RecommendationMetadata.DataState', + enum="Engine.RecommendationMetadata.DataState", ) last_tune_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, @@ -495,37 +499,37 @@ class ChatEngineMetadata(proto.Message): similar_documents_config: SimilarDocumentsEngineConfig = proto.Field( proto.MESSAGE, number=9, - oneof='engine_config', + oneof="engine_config", message=SimilarDocumentsEngineConfig, ) chat_engine_config: ChatEngineConfig = proto.Field( proto.MESSAGE, number=11, - oneof='engine_config', + oneof="engine_config", message=ChatEngineConfig, ) search_engine_config: SearchEngineConfig = proto.Field( proto.MESSAGE, number=13, - oneof='engine_config', + oneof="engine_config", message=SearchEngineConfig, ) media_recommendation_engine_config: MediaRecommendationEngineConfig = proto.Field( proto.MESSAGE, number=14, - oneof='engine_config', + oneof="engine_config", message=MediaRecommendationEngineConfig, ) recommendation_metadata: RecommendationMetadata = proto.Field( proto.MESSAGE, number=10, - oneof='engine_metadata', + oneof="engine_metadata", message=RecommendationMetadata, ) chat_engine_metadata: ChatEngineMetadata = proto.Field( proto.MESSAGE, number=12, - oneof='engine_metadata', + oneof="engine_metadata", message=ChatEngineMetadata, ) name: str = proto.Field( diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/engine_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/engine_service.py similarity index 95% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/engine_service.py rename to packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/engine_service.py index 7462beedf5dd..3dc3a4820ac6 100644 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/google/cloud/discoveryengine_v1alpha/types/engine_service.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/engine_service.py @@ -17,29 +17,28 @@ from typing import MutableMapping, MutableSequence -import proto # type: ignore - -from google.cloud.discoveryengine_v1alpha.types import engine as gcd_engine from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore +from google.cloud.discoveryengine_v1alpha.types import engine as gcd_engine __protobuf__ = proto.module( - package='google.cloud.discoveryengine.v1alpha', + package="google.cloud.discoveryengine.v1alpha", manifest={ - 'CreateEngineRequest', - 'CreateEngineMetadata', - 'DeleteEngineRequest', - 'DeleteEngineMetadata', - 'GetEngineRequest', - 'ListEnginesRequest', - 'ListEnginesResponse', - 'UpdateEngineRequest', - 'PauseEngineRequest', - 'ResumeEngineRequest', - 'TuneEngineRequest', - 'TuneEngineMetadata', - 'TuneEngineResponse', + "CreateEngineRequest", + "CreateEngineMetadata", + "DeleteEngineRequest", + "DeleteEngineMetadata", + "GetEngineRequest", + "ListEnginesRequest", + "ListEnginesResponse", + "UpdateEngineRequest", + "PauseEngineRequest", + "ResumeEngineRequest", + "TuneEngineRequest", + "TuneEngineMetadata", + "TuneEngineResponse", }, ) @@ -349,8 +348,7 @@ class TuneEngineMetadata(proto.Message): class TuneEngineResponse(proto.Message): - r"""Response associated with a tune operation. - """ + r"""Response associated with a tune operation.""" __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/recommendation_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/recommendation_service.py index 0e19b143a3a1..c317ffb522b7 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/recommendation_service.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/recommendation_service.py @@ -37,11 +37,20 @@ class RecommendRequest(proto.Message): Attributes: serving_config (str): - Required. Full resource name of the format: + Required. Full resource name of a + [ServingConfig][google.cloud.discoveryengine.v1alpha.ServingConfig]: + ``projects/*/locations/global/collections/*/engines/*/servingConfigs/*``, + or ``projects/*/locations/global/collections/*/dataStores/*/servingConfigs/*`` - Before you can request recommendations from your model, you - must create at least one serving config for it. + One default serving config is created along with your + recommendation engine creation. The engine ID will be used + as the ID of the default serving config. For example, for + Engine + ``projects/*/locations/global/collections/*/engines/my-engine``, + you can use + ``projects/*/locations/global/collections/*/engines/my-engine/servingConfigs/my-engine`` + for your [Recommend][] requests. user_event (google.cloud.discoveryengine_v1alpha.types.UserEvent): Required. Context about the user, what they are looking at and what action they took to trigger the Recommend request. diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/search_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/search_service.py index 6332371b1256..7a80a3dbe6d5 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/search_service.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1alpha/types/search_service.py @@ -41,6 +41,8 @@ class SearchRequest(proto.Message): serving_config (str): Required. The resource name of the Search serving config, such as + ``projects/*/locations/global/collections/default_collection/engines/*/servingConfigs/default_serving_config``, + or ``projects/*/locations/global/collections/default_collection/dataStores/default_data_store/servingConfigs/default_serving_config``. This field is used to identify the serving configuration name, set of models used to make the search. @@ -91,12 +93,25 @@ class SearchRequest(proto.Message): If this field is unrecognizable, an ``INVALID_ARGUMENT`` is returned. + + Filtering in Vertex AI Search is done by mapping the LHS + filter key to a key property defined in the Vertex AI Search + backend -- this mapping is defined by the customer in their + schema. For example a media customer might have a field + 'name' in their schema. In this case the filter would look + like this: filter --> name:'ANY("king kong")' + + For more information about filtering including syntax and + filter operators, see + `Filter `__ order_by (str): The order in which documents are returned. Documents can be ordered by a field in an [Document][google.cloud.discoveryengine.v1alpha.Document] object. Leave it unset if ordered by relevance. ``order_by`` - expression is case-sensitive. + expression is case-sensitive. For more information on + ordering, see + `Ordering `__ If this field is unrecognizable, an ``INVALID_ARGUMENT`` is returned. @@ -112,8 +127,9 @@ class SearchRequest(proto.Message): A maximum of 100 values are allowed. Otherwise, an ``INVALID_ARGUMENT`` error is returned. boost_spec (google.cloud.discoveryengine_v1alpha.types.SearchRequest.BoostSpec): - Boost specification to boost certain - documents. + Boost specification to boost certain documents. For more + information on boosting, see + `Boosting `__ params (MutableMapping[str, google.protobuf.struct_pb2.Value]): Additional search parameters. @@ -121,11 +137,15 @@ class SearchRequest(proto.Message): - ``user_country_code``: string. Default empty. If set to non-empty, results are restricted or boosted based on the - location provided. + location provided. Example: user_country_code: "au" + + For available codes see `Country + Codes `__ + - ``search_type``: double. Default empty. Enables non-webpage searching depending on the value. The only valid non-default value is 1, which enables image - searching. + searching. Example: search_type: 1 query_expansion_spec (google.cloud.discoveryengine_v1alpha.types.SearchRequest.QueryExpansionSpec): The query expansion specification that specifies the conditions under which query diff --git a/packages/google-cloud-discoveryengine/noxfile.py b/packages/google-cloud-discoveryengine/noxfile.py index 716326a3d430..6b51f78aa204 100644 --- a/packages/google-cloud-discoveryengine/noxfile.py +++ b/packages/google-cloud-discoveryengine/noxfile.py @@ -29,8 +29,10 @@ BLACK_VERSION = "black[jupyter]==23.7.0" ISORT_VERSION = "isort==5.11.0" + LINT_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"] + DEFAULT_PYTHON_VERSION = "3.10" UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11"] @@ -89,6 +91,7 @@ def lint(session): "--check", *LINT_PATHS, ) + session.run("flake8", "google", "tests") diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_create_data_store_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_create_data_store_async.py similarity index 100% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_create_data_store_async.py rename to packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_create_data_store_async.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_create_data_store_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_create_data_store_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_create_data_store_sync.py rename to packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_create_data_store_sync.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_delete_data_store_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_delete_data_store_async.py similarity index 100% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_delete_data_store_async.py rename to packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_delete_data_store_async.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_delete_data_store_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_delete_data_store_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_delete_data_store_sync.py rename to packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_delete_data_store_sync.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_get_data_store_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_get_data_store_async.py similarity index 100% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_get_data_store_async.py rename to packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_get_data_store_async.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_get_data_store_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_get_data_store_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_get_data_store_sync.py rename to packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_get_data_store_sync.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_list_data_stores_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_list_data_stores_async.py similarity index 100% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_list_data_stores_async.py rename to packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_list_data_stores_async.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_list_data_stores_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_list_data_stores_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_list_data_stores_sync.py rename to packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_list_data_stores_sync.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_update_data_store_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_update_data_store_async.py similarity index 100% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_update_data_store_async.py rename to packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_update_data_store_async.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_update_data_store_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_update_data_store_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_update_data_store_sync.py rename to packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_data_store_service_update_data_store_sync.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_create_engine_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_create_engine_async.py similarity index 100% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_create_engine_async.py rename to packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_create_engine_async.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_create_engine_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_create_engine_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_create_engine_sync.py rename to packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_create_engine_sync.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_delete_engine_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_delete_engine_async.py similarity index 100% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_delete_engine_async.py rename to packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_delete_engine_async.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_delete_engine_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_delete_engine_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_delete_engine_sync.py rename to packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_delete_engine_sync.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_get_engine_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_get_engine_async.py similarity index 100% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_get_engine_async.py rename to packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_get_engine_async.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_get_engine_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_get_engine_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_get_engine_sync.py rename to packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_get_engine_sync.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_list_engines_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_list_engines_async.py similarity index 100% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_list_engines_async.py rename to packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_list_engines_async.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_list_engines_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_list_engines_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_list_engines_sync.py rename to packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_list_engines_sync.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_pause_engine_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_pause_engine_async.py similarity index 100% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_pause_engine_async.py rename to packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_pause_engine_async.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_pause_engine_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_pause_engine_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_pause_engine_sync.py rename to packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_pause_engine_sync.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_resume_engine_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_resume_engine_async.py similarity index 100% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_resume_engine_async.py rename to packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_resume_engine_async.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_resume_engine_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_resume_engine_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_resume_engine_sync.py rename to packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_resume_engine_sync.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_tune_engine_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_tune_engine_async.py similarity index 100% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_tune_engine_async.py rename to packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_tune_engine_async.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_tune_engine_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_tune_engine_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_tune_engine_sync.py rename to packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_tune_engine_sync.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_update_engine_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_update_engine_async.py similarity index 100% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_update_engine_async.py rename to packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_update_engine_async.py diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_update_engine_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_update_engine_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_update_engine_sync.py rename to packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1alpha_generated_engine_service_update_engine_sync.py diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1alpha.json b/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1alpha.json index f371886ef73b..ce41071d0b4c 100644 --- a/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1alpha.json +++ b/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1alpha.json @@ -1153,33 +1153,33 @@ "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient", - "shortName": "DocumentServiceAsyncClient" + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceAsyncClient", + "shortName": "DataStoreServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient.create_document", + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceAsyncClient.create_data_store", "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.CreateDocument", + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService.CreateDataStore", "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", - "shortName": "DocumentService" + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService", + "shortName": "DataStoreService" }, - "shortName": "CreateDocument" + "shortName": "CreateDataStore" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.CreateDocumentRequest" + "type": "google.cloud.discoveryengine_v1alpha.types.CreateDataStoreRequest" }, { "name": "parent", "type": "str" }, { - "name": "document", - "type": "google.cloud.discoveryengine_v1alpha.types.Document" + "name": "data_store", + "type": "google.cloud.discoveryengine_v1alpha.types.DataStore" }, { - "name": "document_id", + "name": "data_store_id", "type": "str" }, { @@ -1195,22 +1195,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.Document", - "shortName": "create_document" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_data_store" }, - "description": "Sample for CreateDocument", - "file": "discoveryengine_v1alpha_generated_document_service_create_document_async.py", + "description": "Sample for CreateDataStore", + "file": "discoveryengine_v1alpha_generated_data_store_service_create_data_store_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DocumentService_CreateDocument_async", + "regionTag": "discoveryengine_v1alpha_generated_DataStoreService_CreateDataStore_async", "segments": [ { - "end": 52, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 60, "start": 27, "type": "SHORT" }, @@ -1220,54 +1220,54 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1alpha_generated_document_service_create_document_async.py" + "title": "discoveryengine_v1alpha_generated_data_store_service_create_data_store_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient", - "shortName": "DocumentServiceClient" + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceClient", + "shortName": "DataStoreServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient.create_document", + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceClient.create_data_store", "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.CreateDocument", + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService.CreateDataStore", "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", - "shortName": "DocumentService" + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService", + "shortName": "DataStoreService" }, - "shortName": "CreateDocument" + "shortName": "CreateDataStore" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.CreateDocumentRequest" + "type": "google.cloud.discoveryengine_v1alpha.types.CreateDataStoreRequest" }, { "name": "parent", "type": "str" }, { - "name": "document", - "type": "google.cloud.discoveryengine_v1alpha.types.Document" + "name": "data_store", + "type": "google.cloud.discoveryengine_v1alpha.types.DataStore" }, { - "name": "document_id", + "name": "data_store_id", "type": "str" }, { @@ -1283,22 +1283,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.Document", - "shortName": "create_document" + "resultType": "google.api_core.operation.Operation", + "shortName": "create_data_store" }, - "description": "Sample for CreateDocument", - "file": "discoveryengine_v1alpha_generated_document_service_create_document_sync.py", + "description": "Sample for CreateDataStore", + "file": "discoveryengine_v1alpha_generated_data_store_service_create_data_store_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DocumentService_CreateDocument_sync", + "regionTag": "discoveryengine_v1alpha_generated_DataStoreService_CreateDataStore_sync", "segments": [ { - "end": 52, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 60, "start": 27, "type": "SHORT" }, @@ -1308,44 +1308,44 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1alpha_generated_document_service_create_document_sync.py" + "title": "discoveryengine_v1alpha_generated_data_store_service_create_data_store_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient", - "shortName": "DocumentServiceAsyncClient" + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceAsyncClient", + "shortName": "DataStoreServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient.delete_document", + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceAsyncClient.delete_data_store", "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.DeleteDocument", + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService.DeleteDataStore", "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", - "shortName": "DocumentService" + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService", + "shortName": "DataStoreService" }, - "shortName": "DeleteDocument" + "shortName": "DeleteDataStore" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.DeleteDocumentRequest" + "type": "google.cloud.discoveryengine_v1alpha.types.DeleteDataStoreRequest" }, { "name": "name", @@ -1364,21 +1364,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "shortName": "delete_document" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_data_store" }, - "description": "Sample for DeleteDocument", - "file": "discoveryengine_v1alpha_generated_document_service_delete_document_async.py", + "description": "Sample for DeleteDataStore", + "file": "discoveryengine_v1alpha_generated_data_store_service_delete_data_store_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DocumentService_DeleteDocument_async", + "regionTag": "discoveryengine_v1alpha_generated_DataStoreService_DeleteDataStore_async", "segments": [ { - "end": 49, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 55, "start": 27, "type": "SHORT" }, @@ -1393,36 +1394,38 @@ "type": "REQUEST_INITIALIZATION" }, { + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1alpha_generated_document_service_delete_document_async.py" + "title": "discoveryengine_v1alpha_generated_data_store_service_delete_data_store_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient", - "shortName": "DocumentServiceClient" + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceClient", + "shortName": "DataStoreServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient.delete_document", + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceClient.delete_data_store", "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.DeleteDocument", + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService.DeleteDataStore", "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", - "shortName": "DocumentService" + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService", + "shortName": "DataStoreService" }, - "shortName": "DeleteDocument" + "shortName": "DeleteDataStore" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.DeleteDocumentRequest" + "type": "google.cloud.discoveryengine_v1alpha.types.DeleteDataStoreRequest" }, { "name": "name", @@ -1441,21 +1444,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "shortName": "delete_document" + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_data_store" }, - "description": "Sample for DeleteDocument", - "file": "discoveryengine_v1alpha_generated_document_service_delete_document_sync.py", + "description": "Sample for DeleteDataStore", + "file": "discoveryengine_v1alpha_generated_data_store_service_delete_data_store_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DocumentService_DeleteDocument_sync", + "regionTag": "discoveryengine_v1alpha_generated_DataStoreService_DeleteDataStore_sync", "segments": [ { - "end": 49, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 55, "start": 27, "type": "SHORT" }, @@ -1470,37 +1474,39 @@ "type": "REQUEST_INITIALIZATION" }, { + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1alpha_generated_document_service_delete_document_sync.py" + "title": "discoveryengine_v1alpha_generated_data_store_service_delete_data_store_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient", - "shortName": "DocumentServiceAsyncClient" + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceAsyncClient", + "shortName": "DataStoreServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient.get_document", + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceAsyncClient.get_data_store", "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.GetDocument", + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService.GetDataStore", "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", - "shortName": "DocumentService" + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService", + "shortName": "DataStoreService" }, - "shortName": "GetDocument" + "shortName": "GetDataStore" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.GetDocumentRequest" + "type": "google.cloud.discoveryengine_v1alpha.types.GetDataStoreRequest" }, { "name": "name", @@ -1519,14 +1525,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.Document", - "shortName": "get_document" + "resultType": "google.cloud.discoveryengine_v1alpha.types.DataStore", + "shortName": "get_data_store" }, - "description": "Sample for GetDocument", - "file": "discoveryengine_v1alpha_generated_document_service_get_document_async.py", + "description": "Sample for GetDataStore", + "file": "discoveryengine_v1alpha_generated_data_store_service_get_data_store_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DocumentService_GetDocument_async", + "regionTag": "discoveryengine_v1alpha_generated_DataStoreService_GetDataStore_async", "segments": [ { "end": 51, @@ -1559,28 +1565,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1alpha_generated_document_service_get_document_async.py" + "title": "discoveryengine_v1alpha_generated_data_store_service_get_data_store_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient", - "shortName": "DocumentServiceClient" + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceClient", + "shortName": "DataStoreServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient.get_document", + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceClient.get_data_store", "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.GetDocument", + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService.GetDataStore", "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", - "shortName": "DocumentService" + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService", + "shortName": "DataStoreService" }, - "shortName": "GetDocument" + "shortName": "GetDataStore" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.GetDocumentRequest" + "type": "google.cloud.discoveryengine_v1alpha.types.GetDataStoreRequest" }, { "name": "name", @@ -1599,14 +1605,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.Document", - "shortName": "get_document" + "resultType": "google.cloud.discoveryengine_v1alpha.types.DataStore", + "shortName": "get_data_store" }, - "description": "Sample for GetDocument", - "file": "discoveryengine_v1alpha_generated_document_service_get_document_sync.py", + "description": "Sample for GetDataStore", + "file": "discoveryengine_v1alpha_generated_data_store_service_get_data_store_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DocumentService_GetDocument_sync", + "regionTag": "discoveryengine_v1alpha_generated_DataStoreService_GetDataStore_sync", "segments": [ { "end": 51, @@ -1639,29 +1645,33 @@ "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1alpha_generated_document_service_get_document_sync.py" + "title": "discoveryengine_v1alpha_generated_data_store_service_get_data_store_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient", - "shortName": "DocumentServiceAsyncClient" + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceAsyncClient", + "shortName": "DataStoreServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient.import_documents", + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceAsyncClient.list_data_stores", "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.ImportDocuments", + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService.ListDataStores", "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", - "shortName": "DocumentService" + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService", + "shortName": "DataStoreService" }, - "shortName": "ImportDocuments" + "shortName": "ListDataStores" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.ImportDocumentsRequest" + "type": "google.cloud.discoveryengine_v1alpha.types.ListDataStoresRequest" + }, + { + "name": "parent", + "type": "str" }, { "name": "retry", @@ -1676,22 +1686,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "import_documents" + "resultType": "google.cloud.discoveryengine_v1alpha.services.data_store_service.pagers.ListDataStoresAsyncPager", + "shortName": "list_data_stores" }, - "description": "Sample for ImportDocuments", - "file": "discoveryengine_v1alpha_generated_document_service_import_documents_async.py", + "description": "Sample for ListDataStores", + "file": "discoveryengine_v1alpha_generated_data_store_service_list_data_stores_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DocumentService_ImportDocuments_async", + "regionTag": "discoveryengine_v1alpha_generated_DataStoreService_ListDataStores_async", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -1706,38 +1716,42 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1alpha_generated_document_service_import_documents_async.py" + "title": "discoveryengine_v1alpha_generated_data_store_service_list_data_stores_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient", - "shortName": "DocumentServiceClient" + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceClient", + "shortName": "DataStoreServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient.import_documents", + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceClient.list_data_stores", "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.ImportDocuments", + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService.ListDataStores", "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", - "shortName": "DocumentService" + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService", + "shortName": "DataStoreService" }, - "shortName": "ImportDocuments" + "shortName": "ListDataStores" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.ImportDocumentsRequest" + "type": "google.cloud.discoveryengine_v1alpha.types.ListDataStoresRequest" + }, + { + "name": "parent", + "type": "str" }, { "name": "retry", @@ -1752,22 +1766,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "import_documents" + "resultType": "google.cloud.discoveryengine_v1alpha.services.data_store_service.pagers.ListDataStoresPager", + "shortName": "list_data_stores" }, - "description": "Sample for ImportDocuments", - "file": "discoveryengine_v1alpha_generated_document_service_import_documents_sync.py", + "description": "Sample for ListDataStores", + "file": "discoveryengine_v1alpha_generated_data_store_service_list_data_stores_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DocumentService_ImportDocuments_sync", + "regionTag": "discoveryengine_v1alpha_generated_DataStoreService_ListDataStores_sync", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -1782,43 +1796,47 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1alpha_generated_document_service_import_documents_sync.py" + "title": "discoveryengine_v1alpha_generated_data_store_service_list_data_stores_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient", - "shortName": "DocumentServiceAsyncClient" + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceAsyncClient", + "shortName": "DataStoreServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient.list_documents", + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceAsyncClient.update_data_store", "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.ListDocuments", + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService.UpdateDataStore", "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", - "shortName": "DocumentService" + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService", + "shortName": "DataStoreService" }, - "shortName": "ListDocuments" + "shortName": "UpdateDataStore" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.ListDocumentsRequest" + "type": "google.cloud.discoveryengine_v1alpha.types.UpdateDataStoreRequest" }, { - "name": "parent", - "type": "str" + "name": "data_store", + "type": "google.cloud.discoveryengine_v1alpha.types.DataStore" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -1833,22 +1851,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1alpha.services.document_service.pagers.ListDocumentsAsyncPager", - "shortName": "list_documents" + "resultType": "google.cloud.discoveryengine_v1alpha.types.DataStore", + "shortName": "update_data_store" }, - "description": "Sample for ListDocuments", - "file": "discoveryengine_v1alpha_generated_document_service_list_documents_async.py", + "description": "Sample for UpdateDataStore", + "file": "discoveryengine_v1alpha_generated_data_store_service_update_data_store_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DocumentService_ListDocuments_async", + "regionTag": "discoveryengine_v1alpha_generated_DataStoreService_UpdateDataStore_async", "segments": [ { - "end": 52, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 54, "start": 27, "type": "SHORT" }, @@ -1858,47 +1876,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1alpha_generated_document_service_list_documents_async.py" + "title": "discoveryengine_v1alpha_generated_data_store_service_update_data_store_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient", - "shortName": "DocumentServiceClient" + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceClient", + "shortName": "DataStoreServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient.list_documents", + "fullName": "google.cloud.discoveryengine_v1alpha.DataStoreServiceClient.update_data_store", "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.ListDocuments", + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService.UpdateDataStore", "service": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", - "shortName": "DocumentService" + "fullName": "google.cloud.discoveryengine.v1alpha.DataStoreService", + "shortName": "DataStoreService" }, - "shortName": "ListDocuments" + "shortName": "UpdateDataStore" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.ListDocumentsRequest" + "type": "google.cloud.discoveryengine_v1alpha.types.UpdateDataStoreRequest" }, { - "name": "parent", - "type": "str" + "name": "data_store", + "type": "google.cloud.discoveryengine_v1alpha.types.DataStore" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -1913,22 +1935,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1alpha.services.document_service.pagers.ListDocumentsPager", - "shortName": "list_documents" + "resultType": "google.cloud.discoveryengine_v1alpha.types.DataStore", + "shortName": "update_data_store" }, - "description": "Sample for ListDocuments", - "file": "discoveryengine_v1alpha_generated_document_service_list_documents_sync.py", + "description": "Sample for UpdateDataStore", + "file": "discoveryengine_v1alpha_generated_data_store_service_update_data_store_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DocumentService_ListDocuments_sync", + "regionTag": "discoveryengine_v1alpha_generated_DataStoreService_UpdateDataStore_sync", "segments": [ { - "end": 52, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 54, "start": 27, "type": "SHORT" }, @@ -1938,22 +1960,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1alpha_generated_document_service_list_documents_sync.py" + "title": "discoveryengine_v1alpha_generated_data_store_service_update_data_store_sync.py" }, { "canonical": true, @@ -1963,19 +1985,31 @@ "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient", "shortName": "DocumentServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient.purge_documents", + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient.create_document", "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.PurgeDocuments", + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.CreateDocument", "service": { "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", "shortName": "DocumentService" }, - "shortName": "PurgeDocuments" + "shortName": "CreateDocument" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.PurgeDocumentsRequest" + "type": "google.cloud.discoveryengine_v1alpha.types.CreateDocumentRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "document", + "type": "google.cloud.discoveryengine_v1alpha.types.Document" + }, + { + "name": "document_id", + "type": "str" }, { "name": "retry", @@ -1990,22 +2024,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "purge_documents" + "resultType": "google.cloud.discoveryengine_v1alpha.types.Document", + "shortName": "create_document" }, - "description": "Sample for PurgeDocuments", - "file": "discoveryengine_v1alpha_generated_document_service_purge_documents_async.py", + "description": "Sample for CreateDocument", + "file": "discoveryengine_v1alpha_generated_document_service_create_document_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DocumentService_PurgeDocuments_async", + "regionTag": "discoveryengine_v1alpha_generated_DocumentService_CreateDocument_async", "segments": [ { - "end": 56, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 52, "start": 27, "type": "SHORT" }, @@ -2020,17 +2054,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 53, + "end": 49, "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1alpha_generated_document_service_purge_documents_async.py" + "title": "discoveryengine_v1alpha_generated_document_service_create_document_async.py" }, { "canonical": true, @@ -2039,19 +2073,31 @@ "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient", "shortName": "DocumentServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient.purge_documents", + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient.create_document", "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.PurgeDocuments", + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.CreateDocument", "service": { "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", "shortName": "DocumentService" }, - "shortName": "PurgeDocuments" + "shortName": "CreateDocument" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.PurgeDocumentsRequest" + "type": "google.cloud.discoveryengine_v1alpha.types.CreateDocumentRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "document", + "type": "google.cloud.discoveryengine_v1alpha.types.Document" + }, + { + "name": "document_id", + "type": "str" }, { "name": "retry", @@ -2066,22 +2112,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "purge_documents" + "resultType": "google.cloud.discoveryengine_v1alpha.types.Document", + "shortName": "create_document" }, - "description": "Sample for PurgeDocuments", - "file": "discoveryengine_v1alpha_generated_document_service_purge_documents_sync.py", + "description": "Sample for CreateDocument", + "file": "discoveryengine_v1alpha_generated_document_service_create_document_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DocumentService_PurgeDocuments_sync", + "regionTag": "discoveryengine_v1alpha_generated_DocumentService_CreateDocument_sync", "segments": [ { - "end": 56, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 52, "start": 27, "type": "SHORT" }, @@ -2096,17 +2142,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 53, + "end": 49, "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1alpha_generated_document_service_purge_documents_sync.py" + "title": "discoveryengine_v1alpha_generated_document_service_create_document_sync.py" }, { "canonical": true, @@ -2116,19 +2162,23 @@ "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient", "shortName": "DocumentServiceAsyncClient" }, - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient.update_document", + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient.delete_document", "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.UpdateDocument", + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.DeleteDocument", "service": { "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", "shortName": "DocumentService" }, - "shortName": "UpdateDocument" + "shortName": "DeleteDocument" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.UpdateDocumentRequest" + "type": "google.cloud.discoveryengine_v1alpha.types.DeleteDocumentRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -2143,22 +2193,21 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.Document", - "shortName": "update_document" + "shortName": "delete_document" }, - "description": "Sample for UpdateDocument", - "file": "discoveryengine_v1alpha_generated_document_service_update_document_async.py", + "description": "Sample for DeleteDocument", + "file": "discoveryengine_v1alpha_generated_document_service_delete_document_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DocumentService_UpdateDocument_async", + "regionTag": "discoveryengine_v1alpha_generated_DocumentService_DeleteDocument_async", "segments": [ { - "end": 50, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 50, + "end": 49, "start": 27, "type": "SHORT" }, @@ -2168,22 +2217,20 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 47, - "start": 45, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 51, - "start": 48, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "discoveryengine_v1alpha_generated_document_service_update_document_async.py" + "title": "discoveryengine_v1alpha_generated_document_service_delete_document_async.py" }, { "canonical": true, @@ -2192,19 +2239,23 @@ "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient", "shortName": "DocumentServiceClient" }, - "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient.update_document", + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient.delete_document", "method": { - "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.UpdateDocument", + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.DeleteDocument", "service": { "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", "shortName": "DocumentService" }, - "shortName": "UpdateDocument" + "shortName": "DeleteDocument" }, "parameters": [ { "name": "request", - "type": "google.cloud.discoveryengine_v1alpha.types.UpdateDocumentRequest" + "type": "google.cloud.discoveryengine_v1alpha.types.DeleteDocumentRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -2219,22 +2270,21 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.discoveryengine_v1alpha.types.Document", - "shortName": "update_document" + "shortName": "delete_document" }, - "description": "Sample for UpdateDocument", - "file": "discoveryengine_v1alpha_generated_document_service_update_document_sync.py", + "description": "Sample for DeleteDocument", + "file": "discoveryengine_v1alpha_generated_document_service_delete_document_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "discoveryengine_v1alpha_generated_DocumentService_UpdateDocument_sync", + "regionTag": "discoveryengine_v1alpha_generated_DocumentService_DeleteDocument_sync", "segments": [ { - "end": 50, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 50, + "end": 49, "start": 27, "type": "SHORT" }, @@ -2244,22 +2294,2113 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 47, - "start": 45, + "start": 46, "type": "REQUEST_EXECUTION" }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1alpha_generated_document_service_delete_document_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient", + "shortName": "DocumentServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient.get_document", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.GetDocument", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "GetDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.GetDocumentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.Document", + "shortName": "get_document" + }, + "description": "Sample for GetDocument", + "file": "discoveryengine_v1alpha_generated_document_service_get_document_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_DocumentService_GetDocument_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, { "end": 51, - "start": 48, + "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": "discoveryengine_v1alpha_generated_document_service_update_document_sync.py" + "title": "discoveryengine_v1alpha_generated_document_service_get_document_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient", + "shortName": "DocumentServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient.get_document", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.GetDocument", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "GetDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.GetDocumentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.Document", + "shortName": "get_document" + }, + "description": "Sample for GetDocument", + "file": "discoveryengine_v1alpha_generated_document_service_get_document_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_DocumentService_GetDocument_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": "discoveryengine_v1alpha_generated_document_service_get_document_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient", + "shortName": "DocumentServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient.import_documents", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.ImportDocuments", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "ImportDocuments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.ImportDocumentsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "import_documents" + }, + "description": "Sample for ImportDocuments", + "file": "discoveryengine_v1alpha_generated_document_service_import_documents_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_DocumentService_ImportDocuments_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": "discoveryengine_v1alpha_generated_document_service_import_documents_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient", + "shortName": "DocumentServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient.import_documents", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.ImportDocuments", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "ImportDocuments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.ImportDocumentsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "import_documents" + }, + "description": "Sample for ImportDocuments", + "file": "discoveryengine_v1alpha_generated_document_service_import_documents_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_DocumentService_ImportDocuments_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": "discoveryengine_v1alpha_generated_document_service_import_documents_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient", + "shortName": "DocumentServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient.list_documents", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.ListDocuments", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "ListDocuments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.ListDocumentsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.services.document_service.pagers.ListDocumentsAsyncPager", + "shortName": "list_documents" + }, + "description": "Sample for ListDocuments", + "file": "discoveryengine_v1alpha_generated_document_service_list_documents_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_DocumentService_ListDocuments_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": "discoveryengine_v1alpha_generated_document_service_list_documents_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient", + "shortName": "DocumentServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient.list_documents", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.ListDocuments", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "ListDocuments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.ListDocumentsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.services.document_service.pagers.ListDocumentsPager", + "shortName": "list_documents" + }, + "description": "Sample for ListDocuments", + "file": "discoveryengine_v1alpha_generated_document_service_list_documents_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_DocumentService_ListDocuments_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": "discoveryengine_v1alpha_generated_document_service_list_documents_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient", + "shortName": "DocumentServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient.purge_documents", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.PurgeDocuments", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "PurgeDocuments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.PurgeDocumentsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "purge_documents" + }, + "description": "Sample for PurgeDocuments", + "file": "discoveryengine_v1alpha_generated_document_service_purge_documents_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_DocumentService_PurgeDocuments_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": "discoveryengine_v1alpha_generated_document_service_purge_documents_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient", + "shortName": "DocumentServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient.purge_documents", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.PurgeDocuments", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "PurgeDocuments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.PurgeDocumentsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "purge_documents" + }, + "description": "Sample for PurgeDocuments", + "file": "discoveryengine_v1alpha_generated_document_service_purge_documents_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_DocumentService_PurgeDocuments_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": "discoveryengine_v1alpha_generated_document_service_purge_documents_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient", + "shortName": "DocumentServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceAsyncClient.update_document", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.UpdateDocument", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "UpdateDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.UpdateDocumentRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.Document", + "shortName": "update_document" + }, + "description": "Sample for UpdateDocument", + "file": "discoveryengine_v1alpha_generated_document_service_update_document_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_DocumentService_UpdateDocument_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": "discoveryengine_v1alpha_generated_document_service_update_document_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient", + "shortName": "DocumentServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.DocumentServiceClient.update_document", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService.UpdateDocument", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.DocumentService", + "shortName": "DocumentService" + }, + "shortName": "UpdateDocument" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.UpdateDocumentRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.Document", + "shortName": "update_document" + }, + "description": "Sample for UpdateDocument", + "file": "discoveryengine_v1alpha_generated_document_service_update_document_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_DocumentService_UpdateDocument_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": "discoveryengine_v1alpha_generated_document_service_update_document_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient", + "shortName": "EngineServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient.create_engine", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.CreateEngine", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", + "shortName": "EngineService" + }, + "shortName": "CreateEngine" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.CreateEngineRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "engine", + "type": "google.cloud.discoveryengine_v1alpha.types.Engine" + }, + { + "name": "engine_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_engine" + }, + "description": "Sample for CreateEngine", + "file": "discoveryengine_v1alpha_generated_engine_service_create_engine_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_EngineService_CreateEngine_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1alpha_generated_engine_service_create_engine_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient", + "shortName": "EngineServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient.create_engine", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.CreateEngine", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", + "shortName": "EngineService" + }, + "shortName": "CreateEngine" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.CreateEngineRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "engine", + "type": "google.cloud.discoveryengine_v1alpha.types.Engine" + }, + { + "name": "engine_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_engine" + }, + "description": "Sample for CreateEngine", + "file": "discoveryengine_v1alpha_generated_engine_service_create_engine_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_EngineService_CreateEngine_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "discoveryengine_v1alpha_generated_engine_service_create_engine_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient", + "shortName": "EngineServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient.delete_engine", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.DeleteEngine", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", + "shortName": "EngineService" + }, + "shortName": "DeleteEngine" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.DeleteEngineRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_engine" + }, + "description": "Sample for DeleteEngine", + "file": "discoveryengine_v1alpha_generated_engine_service_delete_engine_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_EngineService_DeleteEngine_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": "discoveryengine_v1alpha_generated_engine_service_delete_engine_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient", + "shortName": "EngineServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient.delete_engine", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.DeleteEngine", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", + "shortName": "EngineService" + }, + "shortName": "DeleteEngine" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.DeleteEngineRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_engine" + }, + "description": "Sample for DeleteEngine", + "file": "discoveryengine_v1alpha_generated_engine_service_delete_engine_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_EngineService_DeleteEngine_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": "discoveryengine_v1alpha_generated_engine_service_delete_engine_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient", + "shortName": "EngineServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient.get_engine", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.GetEngine", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", + "shortName": "EngineService" + }, + "shortName": "GetEngine" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.GetEngineRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.Engine", + "shortName": "get_engine" + }, + "description": "Sample for GetEngine", + "file": "discoveryengine_v1alpha_generated_engine_service_get_engine_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_EngineService_GetEngine_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": "discoveryengine_v1alpha_generated_engine_service_get_engine_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient", + "shortName": "EngineServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient.get_engine", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.GetEngine", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", + "shortName": "EngineService" + }, + "shortName": "GetEngine" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.GetEngineRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.Engine", + "shortName": "get_engine" + }, + "description": "Sample for GetEngine", + "file": "discoveryengine_v1alpha_generated_engine_service_get_engine_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_EngineService_GetEngine_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": "discoveryengine_v1alpha_generated_engine_service_get_engine_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient", + "shortName": "EngineServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient.list_engines", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.ListEngines", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", + "shortName": "EngineService" + }, + "shortName": "ListEngines" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.ListEnginesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.services.engine_service.pagers.ListEnginesAsyncPager", + "shortName": "list_engines" + }, + "description": "Sample for ListEngines", + "file": "discoveryengine_v1alpha_generated_engine_service_list_engines_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_EngineService_ListEngines_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": "discoveryengine_v1alpha_generated_engine_service_list_engines_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient", + "shortName": "EngineServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient.list_engines", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.ListEngines", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", + "shortName": "EngineService" + }, + "shortName": "ListEngines" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.ListEnginesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.services.engine_service.pagers.ListEnginesPager", + "shortName": "list_engines" + }, + "description": "Sample for ListEngines", + "file": "discoveryengine_v1alpha_generated_engine_service_list_engines_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_EngineService_ListEngines_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": "discoveryengine_v1alpha_generated_engine_service_list_engines_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient", + "shortName": "EngineServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient.pause_engine", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.PauseEngine", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", + "shortName": "EngineService" + }, + "shortName": "PauseEngine" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.PauseEngineRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.Engine", + "shortName": "pause_engine" + }, + "description": "Sample for PauseEngine", + "file": "discoveryengine_v1alpha_generated_engine_service_pause_engine_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_EngineService_PauseEngine_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": "discoveryengine_v1alpha_generated_engine_service_pause_engine_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient", + "shortName": "EngineServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient.pause_engine", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.PauseEngine", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", + "shortName": "EngineService" + }, + "shortName": "PauseEngine" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.PauseEngineRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.Engine", + "shortName": "pause_engine" + }, + "description": "Sample for PauseEngine", + "file": "discoveryengine_v1alpha_generated_engine_service_pause_engine_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_EngineService_PauseEngine_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": "discoveryengine_v1alpha_generated_engine_service_pause_engine_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient", + "shortName": "EngineServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient.resume_engine", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.ResumeEngine", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", + "shortName": "EngineService" + }, + "shortName": "ResumeEngine" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.ResumeEngineRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.Engine", + "shortName": "resume_engine" + }, + "description": "Sample for ResumeEngine", + "file": "discoveryengine_v1alpha_generated_engine_service_resume_engine_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_EngineService_ResumeEngine_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": "discoveryengine_v1alpha_generated_engine_service_resume_engine_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient", + "shortName": "EngineServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient.resume_engine", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.ResumeEngine", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", + "shortName": "EngineService" + }, + "shortName": "ResumeEngine" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.ResumeEngineRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.Engine", + "shortName": "resume_engine" + }, + "description": "Sample for ResumeEngine", + "file": "discoveryengine_v1alpha_generated_engine_service_resume_engine_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_EngineService_ResumeEngine_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": "discoveryengine_v1alpha_generated_engine_service_resume_engine_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient", + "shortName": "EngineServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient.tune_engine", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.TuneEngine", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", + "shortName": "EngineService" + }, + "shortName": "TuneEngine" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.TuneEngineRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "tune_engine" + }, + "description": "Sample for TuneEngine", + "file": "discoveryengine_v1alpha_generated_engine_service_tune_engine_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_EngineService_TuneEngine_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": "discoveryengine_v1alpha_generated_engine_service_tune_engine_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient", + "shortName": "EngineServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient.tune_engine", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.TuneEngine", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", + "shortName": "EngineService" + }, + "shortName": "TuneEngine" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.TuneEngineRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "tune_engine" + }, + "description": "Sample for TuneEngine", + "file": "discoveryengine_v1alpha_generated_engine_service_tune_engine_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_EngineService_TuneEngine_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": "discoveryengine_v1alpha_generated_engine_service_tune_engine_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient", + "shortName": "EngineServiceAsyncClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceAsyncClient.update_engine", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.UpdateEngine", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", + "shortName": "EngineService" + }, + "shortName": "UpdateEngine" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.UpdateEngineRequest" + }, + { + "name": "engine", + "type": "google.cloud.discoveryengine_v1alpha.types.Engine" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.Engine", + "shortName": "update_engine" + }, + "description": "Sample for UpdateEngine", + "file": "discoveryengine_v1alpha_generated_engine_service_update_engine_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_EngineService_UpdateEngine_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": "discoveryengine_v1alpha_generated_engine_service_update_engine_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient", + "shortName": "EngineServiceClient" + }, + "fullName": "google.cloud.discoveryengine_v1alpha.EngineServiceClient.update_engine", + "method": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService.UpdateEngine", + "service": { + "fullName": "google.cloud.discoveryengine.v1alpha.EngineService", + "shortName": "EngineService" + }, + "shortName": "UpdateEngine" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.discoveryengine_v1alpha.types.UpdateEngineRequest" + }, + { + "name": "engine", + "type": "google.cloud.discoveryengine_v1alpha.types.Engine" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.discoveryengine_v1alpha.types.Engine", + "shortName": "update_engine" + }, + "description": "Sample for UpdateEngine", + "file": "discoveryengine_v1alpha_generated_engine_service_update_engine_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "discoveryengine_v1alpha_generated_EngineService_UpdateEngine_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": "discoveryengine_v1alpha_generated_engine_service_update_engine_sync.py" }, { "canonical": true, diff --git a/packages/google-cloud-discoveryengine/scripts/fixup_discoveryengine_v1alpha_keywords.py b/packages/google-cloud-discoveryengine/scripts/fixup_discoveryengine_v1alpha_keywords.py index 57b5409f2a37..36332ca4a1e0 100644 --- a/packages/google-cloud-discoveryengine/scripts/fixup_discoveryengine_v1alpha_keywords.py +++ b/packages/google-cloud-discoveryengine/scripts/fixup_discoveryengine_v1alpha_keywords.py @@ -43,26 +43,39 @@ class discoveryengineCallTransformer(cst.CSTTransformer): 'complete_query': ('data_store', 'query', 'query_model', 'user_pseudo_id', 'include_tail_suggestions', ), 'converse_conversation': ('name', 'query', 'serving_config', 'conversation', 'safe_search', 'user_labels', 'summary_spec', ), 'create_conversation': ('parent', 'conversation', ), + 'create_data_store': ('parent', 'data_store', 'data_store_id', 'create_advanced_site_search', ), 'create_document': ('parent', 'document', 'document_id', ), + 'create_engine': ('parent', 'engine', 'engine_id', ), 'create_schema': ('parent', 'schema', 'schema_id', ), 'delete_conversation': ('name', ), + 'delete_data_store': ('name', ), 'delete_document': ('name', ), + 'delete_engine': ('name', ), 'delete_schema': ('name', ), 'get_conversation': ('name', ), + 'get_data_store': ('name', ), 'get_document': ('name', ), + 'get_engine': ('name', ), 'get_schema': ('name', ), 'import_documents': ('parent', 'inline_source', 'gcs_source', 'bigquery_source', 'error_config', 'reconciliation_mode', 'auto_generate_ids', 'id_field', ), 'import_user_events': ('parent', 'inline_source', 'gcs_source', 'bigquery_source', 'error_config', ), 'list_conversations': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_data_stores': ('parent', 'page_size', 'page_token', 'filter', ), 'list_documents': ('parent', 'page_size', 'page_token', ), + 'list_engines': ('parent', 'page_size', 'page_token', 'filter', ), 'list_schemas': ('parent', 'page_size', 'page_token', ), + 'pause_engine': ('name', ), 'purge_documents': ('parent', 'filter', 'force', ), 'purge_user_events': ('parent', 'filter', 'force', ), 'recommend': ('serving_config', 'user_event', 'page_size', 'filter', 'validate_only', 'params', 'user_labels', ), 'recrawl_uris': ('site_search_engine', 'uris', ), + 'resume_engine': ('name', ), 'search': ('serving_config', 'branch', 'query', 'image_query', 'page_size', 'page_token', 'offset', 'filter', 'order_by', 'user_info', 'facet_specs', 'boost_spec', 'params', 'query_expansion_spec', 'spell_correction_spec', 'user_pseudo_id', 'content_search_spec', 'embedding_spec', 'ranking_expression', 'safe_search', 'user_labels', ), + 'tune_engine': ('name', ), 'update_conversation': ('conversation', 'update_mask', ), + 'update_data_store': ('data_store', 'update_mask', ), 'update_document': ('document', 'allow_missing', ), + 'update_engine': ('engine', 'update_mask', ), 'update_schema': ('schema', 'allow_missing', ), 'write_user_event': ('parent', 'user_event', ), } diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_data_store_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_data_store_service.py similarity index 71% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_data_store_service.py rename to packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_data_store_service.py index 6db7ece05a16..1799257e63ab 100644 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_data_store_service.py +++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_data_store_service.py @@ -14,6 +14,7 @@ # limitations under the License. # import os + # try/except added for compatibility with python < 3.8 try: from unittest import mock @@ -21,47 +22,50 @@ except ImportError: # pragma: NO COVER import mock -import grpc -from grpc.experimental import aio from collections.abc import Iterable -from google.protobuf import json_format import json import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format +from google.api_core import ( + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + operation, + operations_v1, + path_template, +) from google.api_core import client_options from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template +import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError -from google.cloud.discoveryengine_v1alpha.services.data_store_service import DataStoreServiceAsyncClient -from google.cloud.discoveryengine_v1alpha.services.data_store_service import DataStoreServiceClient -from google.cloud.discoveryengine_v1alpha.services.data_store_service import pagers -from google.cloud.discoveryengine_v1alpha.services.data_store_service import transports -from google.cloud.discoveryengine_v1alpha.types import common -from google.cloud.discoveryengine_v1alpha.types import data_store -from google.cloud.discoveryengine_v1alpha.types import data_store as gcd_data_store -from google.cloud.discoveryengine_v1alpha.types import data_store_service from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore -import google.auth +import grpc +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +from google.cloud.discoveryengine_v1alpha.services.data_store_service import ( + DataStoreServiceAsyncClient, + DataStoreServiceClient, + pagers, + transports, +) +from google.cloud.discoveryengine_v1alpha.types import data_store as gcd_data_store +from google.cloud.discoveryengine_v1alpha.types import common +from google.cloud.discoveryengine_v1alpha.types import data_store +from google.cloud.discoveryengine_v1alpha.types import data_store_service def client_cert_source_callback(): @@ -72,7 +76,11 @@ def client_cert_source_callback(): # 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 + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) def test__get_default_mtls_endpoint(): @@ -83,21 +91,43 @@ def test__get_default_mtls_endpoint(): non_googleapi = "api.example.com" assert DataStoreServiceClient._get_default_mtls_endpoint(None) is None - assert DataStoreServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert DataStoreServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert DataStoreServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert DataStoreServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert DataStoreServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (DataStoreServiceClient, "grpc"), - (DataStoreServiceAsyncClient, "grpc_asyncio"), - (DataStoreServiceClient, "rest"), -]) -def test_data_store_service_client_from_service_account_info(client_class, transport_name): + assert ( + DataStoreServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + DataStoreServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + DataStoreServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + DataStoreServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + DataStoreServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (DataStoreServiceClient, "grpc"), + (DataStoreServiceAsyncClient, "grpc_asyncio"), + (DataStoreServiceClient, "rest"), + ], +) +def test_data_store_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: + 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) @@ -105,52 +135,70 @@ def test_data_store_service_client_from_service_account_info(client_class, trans assert isinstance(client, client_class) assert client.transport._host == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' + "discoveryengine.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://discoveryengine.googleapis.com" ) -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.DataStoreServiceGrpcTransport, "grpc"), - (transports.DataStoreServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.DataStoreServiceRestTransport, "rest"), -]) -def test_data_store_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: +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.DataStoreServiceGrpcTransport, "grpc"), + (transports.DataStoreServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.DataStoreServiceRestTransport, "rest"), + ], +) +def test_data_store_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: + 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", [ - (DataStoreServiceClient, "grpc"), - (DataStoreServiceAsyncClient, "grpc_asyncio"), - (DataStoreServiceClient, "rest"), -]) -def test_data_store_service_client_from_service_account_file(client_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (DataStoreServiceClient, "grpc"), + (DataStoreServiceAsyncClient, "grpc_asyncio"), + (DataStoreServiceClient, "rest"), + ], +) +def test_data_store_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: + 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) + 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) + 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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' + "discoveryengine.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://discoveryengine.googleapis.com" ) @@ -166,30 +214,45 @@ def test_data_store_service_client_get_transport_class(): assert transport == transports.DataStoreServiceGrpcTransport -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DataStoreServiceClient, transports.DataStoreServiceGrpcTransport, "grpc"), - (DataStoreServiceAsyncClient, transports.DataStoreServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (DataStoreServiceClient, transports.DataStoreServiceRestTransport, "rest"), -]) -@mock.patch.object(DataStoreServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataStoreServiceClient)) -@mock.patch.object(DataStoreServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataStoreServiceAsyncClient)) -def test_data_store_service_client_client_options(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (DataStoreServiceClient, transports.DataStoreServiceGrpcTransport, "grpc"), + ( + DataStoreServiceAsyncClient, + transports.DataStoreServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (DataStoreServiceClient, transports.DataStoreServiceRestTransport, "rest"), + ], +) +@mock.patch.object( + DataStoreServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(DataStoreServiceClient), +) +@mock.patch.object( + DataStoreServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(DataStoreServiceAsyncClient), +) +def test_data_store_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(DataStoreServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) + with mock.patch.object(DataStoreServiceClient, "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(DataStoreServiceClient, 'get_transport_class') as gtc: + with mock.patch.object(DataStoreServiceClient, "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: + 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( @@ -207,7 +270,7 @@ def test_data_store_service_client_client_options(client_class, transport_class, # 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: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( @@ -225,7 +288,7 @@ def test_data_store_service_client_client_options(client_class, transport_class, # 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: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( @@ -247,13 +310,15 @@ def test_data_store_service_client_client_options(client_class, transport_class, client = client_class(transport=transport_name) # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): with pytest.raises(ValueError): client = client_class(transport=transport_name) # Check the case quota_project_id is provided options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: + 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( @@ -268,8 +333,10 @@ def test_data_store_service_client_client_options(client_class, transport_class, 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: + 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( @@ -281,29 +348,77 @@ def test_data_store_service_client_client_options(client_class, transport_class, 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", [ - (DataStoreServiceClient, transports.DataStoreServiceGrpcTransport, "grpc", "true"), - (DataStoreServiceAsyncClient, transports.DataStoreServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (DataStoreServiceClient, transports.DataStoreServiceGrpcTransport, "grpc", "false"), - (DataStoreServiceAsyncClient, transports.DataStoreServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (DataStoreServiceClient, transports.DataStoreServiceRestTransport, "rest", "true"), - (DataStoreServiceClient, transports.DataStoreServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(DataStoreServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataStoreServiceClient)) -@mock.patch.object(DataStoreServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataStoreServiceAsyncClient)) + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + DataStoreServiceClient, + transports.DataStoreServiceGrpcTransport, + "grpc", + "true", + ), + ( + DataStoreServiceAsyncClient, + transports.DataStoreServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + DataStoreServiceClient, + transports.DataStoreServiceGrpcTransport, + "grpc", + "false", + ), + ( + DataStoreServiceAsyncClient, + transports.DataStoreServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + DataStoreServiceClient, + transports.DataStoreServiceRestTransport, + "rest", + "true", + ), + ( + DataStoreServiceClient, + transports.DataStoreServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + DataStoreServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(DataStoreServiceClient), +) +@mock.patch.object( + DataStoreServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(DataStoreServiceAsyncClient), +) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_data_store_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): +def test_data_store_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: + 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) @@ -328,10 +443,18 @@ def test_data_store_service_client_mtls_env_auto(client_class, transport_class, # 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): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): if use_client_cert_env == "false": expected_host = client.DEFAULT_ENDPOINT expected_client_cert_source = None @@ -354,9 +477,14 @@ def test_data_store_service_client_mtls_env_auto(client_class, transport_class, ) # 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): + 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( @@ -372,19 +500,31 @@ def test_data_store_service_client_mtls_env_auto(client_class, transport_class, ) -@pytest.mark.parametrize("client_class", [ - DataStoreServiceClient, DataStoreServiceAsyncClient -]) -@mock.patch.object(DataStoreServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataStoreServiceClient)) -@mock.patch.object(DataStoreServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(DataStoreServiceAsyncClient)) +@pytest.mark.parametrize( + "client_class", [DataStoreServiceClient, DataStoreServiceAsyncClient] +) +@mock.patch.object( + DataStoreServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(DataStoreServiceClient), +) +@mock.patch.object( + DataStoreServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(DataStoreServiceAsyncClient), +) def test_data_store_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) + 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 @@ -392,8 +532,12 @@ def test_data_store_service_client_get_mtls_endpoint_and_cert_source(client_clas 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) + 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 @@ -411,31 +555,52 @@ def test_data_store_service_client_get_mtls_endpoint_and_cert_source(client_clas # 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): + 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() + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (DataStoreServiceClient, transports.DataStoreServiceGrpcTransport, "grpc"), - (DataStoreServiceAsyncClient, transports.DataStoreServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (DataStoreServiceClient, transports.DataStoreServiceRestTransport, "rest"), -]) -def test_data_store_service_client_client_options_scopes(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (DataStoreServiceClient, transports.DataStoreServiceGrpcTransport, "grpc"), + ( + DataStoreServiceAsyncClient, + transports.DataStoreServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (DataStoreServiceClient, transports.DataStoreServiceRestTransport, "rest"), + ], +) +def test_data_store_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: + 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( @@ -450,18 +615,37 @@ def test_data_store_service_client_client_options_scopes(client_class, transport api_audience=None, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (DataStoreServiceClient, transports.DataStoreServiceGrpcTransport, "grpc", grpc_helpers), - (DataStoreServiceAsyncClient, transports.DataStoreServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (DataStoreServiceClient, transports.DataStoreServiceRestTransport, "rest", None), -]) -def test_data_store_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + DataStoreServiceClient, + transports.DataStoreServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + DataStoreServiceAsyncClient, + transports.DataStoreServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + DataStoreServiceClient, + transports.DataStoreServiceRestTransport, + "rest", + None, + ), + ], +) +def test_data_store_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" - ) + options = client_options.ClientOptions(credentials_file="credentials.json") - with mock.patch.object(transport_class, '__init__') as patched: + 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( @@ -476,11 +660,14 @@ def test_data_store_service_client_client_options_credentials_file(client_class, api_audience=None, ) + def test_data_store_service_client_client_options_from_dict(): - with mock.patch('google.cloud.discoveryengine_v1alpha.services.data_store_service.transports.DataStoreServiceGrpcTransport.__init__') as grpc_transport: + with mock.patch( + "google.cloud.discoveryengine_v1alpha.services.data_store_service.transports.DataStoreServiceGrpcTransport.__init__" + ) as grpc_transport: grpc_transport.return_value = None client = DataStoreServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} + client_options={"api_endpoint": "squid.clam.whelk"} ) grpc_transport.assert_called_once_with( credentials=None, @@ -495,17 +682,30 @@ def test_data_store_service_client_client_options_from_dict(): ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (DataStoreServiceClient, transports.DataStoreServiceGrpcTransport, "grpc", grpc_helpers), - (DataStoreServiceAsyncClient, transports.DataStoreServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_data_store_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + DataStoreServiceClient, + transports.DataStoreServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + DataStoreServiceAsyncClient, + transports.DataStoreServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_data_store_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" - ) + options = client_options.ClientOptions(credentials_file="credentials.json") - with mock.patch.object(transport_class, '__init__') as patched: + 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( @@ -538,9 +738,7 @@ def test_data_store_service_client_create_channel_credentials_file(client_class, credentials=file_creds, credentials_file=None, quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), scopes=None, default_host="discoveryengine.googleapis.com", ssl_credentials=None, @@ -551,11 +749,14 @@ def test_data_store_service_client_create_channel_credentials_file(client_class, ) -@pytest.mark.parametrize("request_type", [ - data_store_service.CreateDataStoreRequest, - dict, -]) -def test_create_data_store(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + data_store_service.CreateDataStoreRequest, + dict, + ], +) +def test_create_data_store(request_type, transport: str = "grpc"): client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -567,10 +768,10 @@ def test_create_data_store(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_data_store), - '__call__') as call: + type(client.transport.create_data_store), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') + call.return_value = operations_pb2.Operation(name="operations/spam") response = client.create_data_store(request) # Establish that the underlying gRPC stub method was called. @@ -587,20 +788,24 @@ def test_create_data_store_empty_call(): # i.e. request == None and no flattened fields passed, work. client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_data_store), - '__call__') as call: + type(client.transport.create_data_store), "__call__" + ) as call: client.create_data_store() call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == data_store_service.CreateDataStoreRequest() + @pytest.mark.asyncio -async def test_create_data_store_async(transport: str = 'grpc_asyncio', request_type=data_store_service.CreateDataStoreRequest): +async def test_create_data_store_async( + transport: str = "grpc_asyncio", + request_type=data_store_service.CreateDataStoreRequest, +): client = DataStoreServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -612,11 +817,11 @@ async def test_create_data_store_async(transport: str = 'grpc_asyncio', request_ # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_data_store), - '__call__') as call: + type(client.transport.create_data_store), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) response = await client.create_data_store(request) @@ -643,13 +848,13 @@ def test_create_data_store_field_headers(): # a field header. Set these to a non-empty value. request = data_store_service.CreateDataStoreRequest() - request.parent = 'parent_value' + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_data_store), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') + type(client.transport.create_data_store), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") client.create_data_store(request) # Establish that the underlying gRPC stub method was called. @@ -660,9 +865,9 @@ def test_create_data_store_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -675,13 +880,15 @@ async def test_create_data_store_field_headers_async(): # a field header. Set these to a non-empty value. request = data_store_service.CreateDataStoreRequest() - request.parent = 'parent_value' + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_data_store), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + type(client.transport.create_data_store), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) await client.create_data_store(request) # Establish that the underlying gRPC stub method was called. @@ -692,9 +899,9 @@ async def test_create_data_store_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] def test_create_data_store_flattened(): @@ -704,16 +911,16 @@ def test_create_data_store_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_data_store), - '__call__') as call: + type(client.transport.create_data_store), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + 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_data_store( - parent='parent_value', - data_store=gcd_data_store.DataStore(name='name_value'), - data_store_id='data_store_id_value', + parent="parent_value", + data_store=gcd_data_store.DataStore(name="name_value"), + data_store_id="data_store_id_value", ) # Establish that the underlying call was made with the expected @@ -721,13 +928,13 @@ def test_create_data_store_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val arg = args[0].data_store - mock_val = gcd_data_store.DataStore(name='name_value') + mock_val = gcd_data_store.DataStore(name="name_value") assert arg == mock_val arg = args[0].data_store_id - mock_val = 'data_store_id_value' + mock_val = "data_store_id_value" assert arg == mock_val @@ -741,11 +948,12 @@ def test_create_data_store_flattened_error(): with pytest.raises(ValueError): client.create_data_store( data_store_service.CreateDataStoreRequest(), - parent='parent_value', - data_store=gcd_data_store.DataStore(name='name_value'), - data_store_id='data_store_id_value', + parent="parent_value", + data_store=gcd_data_store.DataStore(name="name_value"), + data_store_id="data_store_id_value", ) + @pytest.mark.asyncio async def test_create_data_store_flattened_async(): client = DataStoreServiceAsyncClient( @@ -754,20 +962,20 @@ async def test_create_data_store_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_data_store), - '__call__') as call: + type(client.transport.create_data_store), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + 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_data_store( - parent='parent_value', - data_store=gcd_data_store.DataStore(name='name_value'), - data_store_id='data_store_id_value', + parent="parent_value", + data_store=gcd_data_store.DataStore(name="name_value"), + data_store_id="data_store_id_value", ) # Establish that the underlying call was made with the expected @@ -775,15 +983,16 @@ async def test_create_data_store_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val arg = args[0].data_store - mock_val = gcd_data_store.DataStore(name='name_value') + mock_val = gcd_data_store.DataStore(name="name_value") assert arg == mock_val arg = args[0].data_store_id - mock_val = 'data_store_id_value' + mock_val = "data_store_id_value" assert arg == mock_val + @pytest.mark.asyncio async def test_create_data_store_flattened_error_async(): client = DataStoreServiceAsyncClient( @@ -795,17 +1004,20 @@ async def test_create_data_store_flattened_error_async(): with pytest.raises(ValueError): await client.create_data_store( data_store_service.CreateDataStoreRequest(), - parent='parent_value', - data_store=gcd_data_store.DataStore(name='name_value'), - data_store_id='data_store_id_value', + parent="parent_value", + data_store=gcd_data_store.DataStore(name="name_value"), + data_store_id="data_store_id_value", ) -@pytest.mark.parametrize("request_type", [ - data_store_service.GetDataStoreRequest, - dict, -]) -def test_get_data_store(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + data_store_service.GetDataStoreRequest, + dict, + ], +) +def test_get_data_store(request_type, transport: str = "grpc"): client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -816,16 +1028,14 @@ def test_get_data_store(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_data_store), - '__call__') as call: + with mock.patch.object(type(client.transport.get_data_store), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = data_store.DataStore( - name='name_value', - display_name='display_name_value', + name="name_value", + display_name="display_name_value", industry_vertical=common.IndustryVertical.GENERIC, solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - default_schema_id='default_schema_id_value', + default_schema_id="default_schema_id_value", content_config=data_store.DataStore.ContentConfig.NO_CONTENT, ) response = client.get_data_store(request) @@ -837,11 +1047,11 @@ def test_get_data_store(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, data_store.DataStore) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' + assert response.name == "name_value" + assert response.display_name == "display_name_value" assert response.industry_vertical == common.IndustryVertical.GENERIC assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - assert response.default_schema_id == 'default_schema_id_value' + assert response.default_schema_id == "default_schema_id_value" assert response.content_config == data_store.DataStore.ContentConfig.NO_CONTENT @@ -850,20 +1060,21 @@ def test_get_data_store_empty_call(): # i.e. request == None and no flattened fields passed, work. client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_data_store), - '__call__') as call: + with mock.patch.object(type(client.transport.get_data_store), "__call__") as call: client.get_data_store() call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == data_store_service.GetDataStoreRequest() + @pytest.mark.asyncio -async def test_get_data_store_async(transport: str = 'grpc_asyncio', request_type=data_store_service.GetDataStoreRequest): +async def test_get_data_store_async( + transport: str = "grpc_asyncio", request_type=data_store_service.GetDataStoreRequest +): client = DataStoreServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -874,18 +1085,18 @@ async def test_get_data_store_async(transport: str = 'grpc_asyncio', request_typ request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_data_store), - '__call__') as call: + with mock.patch.object(type(client.transport.get_data_store), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(data_store.DataStore( - name='name_value', - display_name='display_name_value', - industry_vertical=common.IndustryVertical.GENERIC, - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - default_schema_id='default_schema_id_value', - content_config=data_store.DataStore.ContentConfig.NO_CONTENT, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_store.DataStore( + name="name_value", + display_name="display_name_value", + industry_vertical=common.IndustryVertical.GENERIC, + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + default_schema_id="default_schema_id_value", + content_config=data_store.DataStore.ContentConfig.NO_CONTENT, + ) + ) response = await client.get_data_store(request) # Establish that the underlying gRPC stub method was called. @@ -895,11 +1106,11 @@ async def test_get_data_store_async(transport: str = 'grpc_asyncio', request_typ # Establish that the response is the type that we expect. assert isinstance(response, data_store.DataStore) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' + assert response.name == "name_value" + assert response.display_name == "display_name_value" assert response.industry_vertical == common.IndustryVertical.GENERIC assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - assert response.default_schema_id == 'default_schema_id_value' + assert response.default_schema_id == "default_schema_id_value" assert response.content_config == data_store.DataStore.ContentConfig.NO_CONTENT @@ -917,12 +1128,10 @@ def test_get_data_store_field_headers(): # a field header. Set these to a non-empty value. request = data_store_service.GetDataStoreRequest() - request.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.get_data_store), - '__call__') as call: + with mock.patch.object(type(client.transport.get_data_store), "__call__") as call: call.return_value = data_store.DataStore() client.get_data_store(request) @@ -934,9 +1143,9 @@ def test_get_data_store_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -949,13 +1158,13 @@ async def test_get_data_store_field_headers_async(): # a field header. Set these to a non-empty value. request = data_store_service.GetDataStoreRequest() - request.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.get_data_store), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_store.DataStore()) + with mock.patch.object(type(client.transport.get_data_store), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_store.DataStore() + ) await client.get_data_store(request) # Establish that the underlying gRPC stub method was called. @@ -966,9 +1175,9 @@ async def test_get_data_store_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] def test_get_data_store_flattened(): @@ -977,15 +1186,13 @@ def test_get_data_store_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_data_store), - '__call__') as call: + with mock.patch.object(type(client.transport.get_data_store), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = data_store.DataStore() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_data_store( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -993,7 +1200,7 @@ def test_get_data_store_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val @@ -1007,9 +1214,10 @@ def test_get_data_store_flattened_error(): with pytest.raises(ValueError): client.get_data_store( data_store_service.GetDataStoreRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_get_data_store_flattened_async(): client = DataStoreServiceAsyncClient( @@ -1017,17 +1225,17 @@ async def test_get_data_store_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_data_store), - '__call__') as call: + with mock.patch.object(type(client.transport.get_data_store), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = data_store.DataStore() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_store.DataStore()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_store.DataStore() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_data_store( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1035,9 +1243,10 @@ async def test_get_data_store_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val + @pytest.mark.asyncio async def test_get_data_store_flattened_error_async(): client = DataStoreServiceAsyncClient( @@ -1049,15 +1258,18 @@ async def test_get_data_store_flattened_error_async(): with pytest.raises(ValueError): await client.get_data_store( data_store_service.GetDataStoreRequest(), - name='name_value', + name="name_value", ) -@pytest.mark.parametrize("request_type", [ - data_store_service.ListDataStoresRequest, - dict, -]) -def test_list_data_stores(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + data_store_service.ListDataStoresRequest, + dict, + ], +) +def test_list_data_stores(request_type, transport: str = "grpc"): client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1068,12 +1280,10 @@ def test_list_data_stores(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_data_stores), - '__call__') as call: + with mock.patch.object(type(client.transport.list_data_stores), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = data_store_service.ListDataStoresResponse( - next_page_token='next_page_token_value', + next_page_token="next_page_token_value", ) response = client.list_data_stores(request) @@ -1084,7 +1294,7 @@ def test_list_data_stores(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListDataStoresPager) - assert response.next_page_token == 'next_page_token_value' + assert response.next_page_token == "next_page_token_value" def test_list_data_stores_empty_call(): @@ -1092,20 +1302,22 @@ def test_list_data_stores_empty_call(): # i.e. request == None and no flattened fields passed, work. client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_stores), - '__call__') as call: + with mock.patch.object(type(client.transport.list_data_stores), "__call__") as call: client.list_data_stores() call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == data_store_service.ListDataStoresRequest() + @pytest.mark.asyncio -async def test_list_data_stores_async(transport: str = 'grpc_asyncio', request_type=data_store_service.ListDataStoresRequest): +async def test_list_data_stores_async( + transport: str = "grpc_asyncio", + request_type=data_store_service.ListDataStoresRequest, +): client = DataStoreServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1116,13 +1328,13 @@ async def test_list_data_stores_async(transport: str = 'grpc_asyncio', request_t request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_stores), - '__call__') as call: + with mock.patch.object(type(client.transport.list_data_stores), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(data_store_service.ListDataStoresResponse( - next_page_token='next_page_token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_store_service.ListDataStoresResponse( + next_page_token="next_page_token_value", + ) + ) response = await client.list_data_stores(request) # Establish that the underlying gRPC stub method was called. @@ -1132,7 +1344,7 @@ async def test_list_data_stores_async(transport: str = 'grpc_asyncio', request_t # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListDataStoresAsyncPager) - assert response.next_page_token == 'next_page_token_value' + assert response.next_page_token == "next_page_token_value" @pytest.mark.asyncio @@ -1149,12 +1361,10 @@ def test_list_data_stores_field_headers(): # a field header. Set these to a non-empty value. request = data_store_service.ListDataStoresRequest() - request.parent = 'parent_value' + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_stores), - '__call__') as call: + with mock.patch.object(type(client.transport.list_data_stores), "__call__") as call: call.return_value = data_store_service.ListDataStoresResponse() client.list_data_stores(request) @@ -1166,9 +1376,9 @@ def test_list_data_stores_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -1181,13 +1391,13 @@ async def test_list_data_stores_field_headers_async(): # a field header. Set these to a non-empty value. request = data_store_service.ListDataStoresRequest() - request.parent = 'parent_value' + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_stores), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_store_service.ListDataStoresResponse()) + with mock.patch.object(type(client.transport.list_data_stores), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_store_service.ListDataStoresResponse() + ) await client.list_data_stores(request) # Establish that the underlying gRPC stub method was called. @@ -1198,9 +1408,9 @@ async def test_list_data_stores_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] def test_list_data_stores_flattened(): @@ -1209,15 +1419,13 @@ def test_list_data_stores_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_stores), - '__call__') as call: + with mock.patch.object(type(client.transport.list_data_stores), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = data_store_service.ListDataStoresResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_data_stores( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -1225,7 +1433,7 @@ def test_list_data_stores_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val @@ -1239,9 +1447,10 @@ def test_list_data_stores_flattened_error(): with pytest.raises(ValueError): client.list_data_stores( data_store_service.ListDataStoresRequest(), - parent='parent_value', + parent="parent_value", ) + @pytest.mark.asyncio async def test_list_data_stores_flattened_async(): client = DataStoreServiceAsyncClient( @@ -1249,17 +1458,17 @@ async def test_list_data_stores_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_stores), - '__call__') as call: + with mock.patch.object(type(client.transport.list_data_stores), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = data_store_service.ListDataStoresResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(data_store_service.ListDataStoresResponse()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_store_service.ListDataStoresResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.list_data_stores( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -1267,9 +1476,10 @@ async def test_list_data_stores_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val + @pytest.mark.asyncio async def test_list_data_stores_flattened_error_async(): client = DataStoreServiceAsyncClient( @@ -1281,7 +1491,7 @@ async def test_list_data_stores_flattened_error_async(): with pytest.raises(ValueError): await client.list_data_stores( data_store_service.ListDataStoresRequest(), - parent='parent_value', + parent="parent_value", ) @@ -1292,9 +1502,7 @@ def test_list_data_stores_pager(transport_name: str = "grpc"): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_stores), - '__call__') as call: + with mock.patch.object(type(client.transport.list_data_stores), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( data_store_service.ListDataStoresResponse( @@ -1303,17 +1511,17 @@ def test_list_data_stores_pager(transport_name: str = "grpc"): data_store.DataStore(), data_store.DataStore(), ], - next_page_token='abc', + next_page_token="abc", ), data_store_service.ListDataStoresResponse( data_stores=[], - next_page_token='def', + next_page_token="def", ), data_store_service.ListDataStoresResponse( data_stores=[ data_store.DataStore(), ], - next_page_token='ghi', + next_page_token="ghi", ), data_store_service.ListDataStoresResponse( data_stores=[ @@ -1326,9 +1534,7 @@ def test_list_data_stores_pager(transport_name: str = "grpc"): metadata = () metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), ) pager = client.list_data_stores(request={}) @@ -1336,8 +1542,9 @@ def test_list_data_stores_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, data_store.DataStore) - for i in results) + assert all(isinstance(i, data_store.DataStore) for i in results) + + def test_list_data_stores_pages(transport_name: str = "grpc"): client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials, @@ -1345,9 +1552,7 @@ def test_list_data_stores_pages(transport_name: str = "grpc"): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_stores), - '__call__') as call: + with mock.patch.object(type(client.transport.list_data_stores), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( data_store_service.ListDataStoresResponse( @@ -1356,17 +1561,17 @@ def test_list_data_stores_pages(transport_name: str = "grpc"): data_store.DataStore(), data_store.DataStore(), ], - next_page_token='abc', + next_page_token="abc", ), data_store_service.ListDataStoresResponse( data_stores=[], - next_page_token='def', + next_page_token="def", ), data_store_service.ListDataStoresResponse( data_stores=[ data_store.DataStore(), ], - next_page_token='ghi', + next_page_token="ghi", ), data_store_service.ListDataStoresResponse( data_stores=[ @@ -1377,9 +1582,10 @@ def test_list_data_stores_pages(transport_name: str = "grpc"): RuntimeError, ) pages = list(client.list_data_stores(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token + @pytest.mark.asyncio async def test_list_data_stores_async_pager(): client = DataStoreServiceAsyncClient( @@ -1388,8 +1594,8 @@ async def test_list_data_stores_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_data_stores), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_data_stores), "__call__", new_callable=mock.AsyncMock + ) as call: # Set the response to a series of pages. call.side_effect = ( data_store_service.ListDataStoresResponse( @@ -1398,17 +1604,17 @@ async def test_list_data_stores_async_pager(): data_store.DataStore(), data_store.DataStore(), ], - next_page_token='abc', + next_page_token="abc", ), data_store_service.ListDataStoresResponse( data_stores=[], - next_page_token='def', + next_page_token="def", ), data_store_service.ListDataStoresResponse( data_stores=[ data_store.DataStore(), ], - next_page_token='ghi', + next_page_token="ghi", ), data_store_service.ListDataStoresResponse( data_stores=[ @@ -1418,15 +1624,16 @@ async def test_list_data_stores_async_pager(): ), RuntimeError, ) - async_pager = await client.list_data_stores(request={},) - assert async_pager.next_page_token == 'abc' + async_pager = await client.list_data_stores( + request={}, + ) + assert async_pager.next_page_token == "abc" responses = [] - async for response in async_pager: # pragma: no branch + async for response in async_pager: # pragma: no branch responses.append(response) assert len(responses) == 6 - assert all(isinstance(i, data_store.DataStore) - for i in responses) + assert all(isinstance(i, data_store.DataStore) for i in responses) @pytest.mark.asyncio @@ -1437,8 +1644,8 @@ async def test_list_data_stores_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_data_stores), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_data_stores), "__call__", new_callable=mock.AsyncMock + ) as call: # Set the response to a series of pages. call.side_effect = ( data_store_service.ListDataStoresResponse( @@ -1447,17 +1654,17 @@ async def test_list_data_stores_async_pages(): data_store.DataStore(), data_store.DataStore(), ], - next_page_token='abc', + next_page_token="abc", ), data_store_service.ListDataStoresResponse( data_stores=[], - next_page_token='def', + next_page_token="def", ), data_store_service.ListDataStoresResponse( data_stores=[ data_store.DataStore(), ], - next_page_token='ghi', + next_page_token="ghi", ), data_store_service.ListDataStoresResponse( data_stores=[ @@ -1470,18 +1677,22 @@ async def test_list_data_stores_async_pages(): pages = [] # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( # pragma: no branch await client.list_data_stores(request={}) ).pages: pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize("request_type", [ - data_store_service.DeleteDataStoreRequest, - dict, -]) -def test_delete_data_store(request_type, transport: str = 'grpc'): + +@pytest.mark.parametrize( + "request_type", + [ + data_store_service.DeleteDataStoreRequest, + dict, + ], +) +def test_delete_data_store(request_type, transport: str = "grpc"): client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1493,10 +1704,10 @@ def test_delete_data_store(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_data_store), - '__call__') as call: + type(client.transport.delete_data_store), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') + call.return_value = operations_pb2.Operation(name="operations/spam") response = client.delete_data_store(request) # Establish that the underlying gRPC stub method was called. @@ -1513,20 +1724,24 @@ def test_delete_data_store_empty_call(): # i.e. request == None and no flattened fields passed, work. client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_data_store), - '__call__') as call: + type(client.transport.delete_data_store), "__call__" + ) as call: client.delete_data_store() call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == data_store_service.DeleteDataStoreRequest() + @pytest.mark.asyncio -async def test_delete_data_store_async(transport: str = 'grpc_asyncio', request_type=data_store_service.DeleteDataStoreRequest): +async def test_delete_data_store_async( + transport: str = "grpc_asyncio", + request_type=data_store_service.DeleteDataStoreRequest, +): client = DataStoreServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1538,11 +1753,11 @@ async def test_delete_data_store_async(transport: str = 'grpc_asyncio', request_ # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_data_store), - '__call__') as call: + type(client.transport.delete_data_store), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) response = await client.delete_data_store(request) @@ -1569,13 +1784,13 @@ def test_delete_data_store_field_headers(): # a field header. Set these to a non-empty value. request = data_store_service.DeleteDataStoreRequest() - request.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.delete_data_store), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') + type(client.transport.delete_data_store), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") client.delete_data_store(request) # Establish that the underlying gRPC stub method was called. @@ -1586,9 +1801,9 @@ def test_delete_data_store_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -1601,13 +1816,15 @@ async def test_delete_data_store_field_headers_async(): # a field header. Set these to a non-empty value. request = data_store_service.DeleteDataStoreRequest() - request.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.delete_data_store), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + type(client.transport.delete_data_store), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) await client.delete_data_store(request) # Establish that the underlying gRPC stub method was called. @@ -1618,9 +1835,9 @@ async def test_delete_data_store_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] def test_delete_data_store_flattened(): @@ -1630,14 +1847,14 @@ def test_delete_data_store_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_data_store), - '__call__') as call: + type(client.transport.delete_data_store), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + 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_data_store( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1645,7 +1862,7 @@ def test_delete_data_store_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val @@ -1659,9 +1876,10 @@ def test_delete_data_store_flattened_error(): with pytest.raises(ValueError): client.delete_data_store( data_store_service.DeleteDataStoreRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_delete_data_store_flattened_async(): client = DataStoreServiceAsyncClient( @@ -1670,18 +1888,18 @@ async def test_delete_data_store_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_data_store), - '__call__') as call: + type(client.transport.delete_data_store), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + 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_data_store( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1689,9 +1907,10 @@ async def test_delete_data_store_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val + @pytest.mark.asyncio async def test_delete_data_store_flattened_error_async(): client = DataStoreServiceAsyncClient( @@ -1703,15 +1922,18 @@ async def test_delete_data_store_flattened_error_async(): with pytest.raises(ValueError): await client.delete_data_store( data_store_service.DeleteDataStoreRequest(), - name='name_value', + name="name_value", ) -@pytest.mark.parametrize("request_type", [ - data_store_service.UpdateDataStoreRequest, - dict, -]) -def test_update_data_store(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + data_store_service.UpdateDataStoreRequest, + dict, + ], +) +def test_update_data_store(request_type, transport: str = "grpc"): client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1723,15 +1945,15 @@ def test_update_data_store(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_data_store), - '__call__') as call: + type(client.transport.update_data_store), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_data_store.DataStore( - name='name_value', - display_name='display_name_value', + name="name_value", + display_name="display_name_value", industry_vertical=common.IndustryVertical.GENERIC, solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - default_schema_id='default_schema_id_value', + default_schema_id="default_schema_id_value", content_config=gcd_data_store.DataStore.ContentConfig.NO_CONTENT, ) response = client.update_data_store(request) @@ -1743,11 +1965,11 @@ def test_update_data_store(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, gcd_data_store.DataStore) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' + assert response.name == "name_value" + assert response.display_name == "display_name_value" assert response.industry_vertical == common.IndustryVertical.GENERIC assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - assert response.default_schema_id == 'default_schema_id_value' + assert response.default_schema_id == "default_schema_id_value" assert response.content_config == gcd_data_store.DataStore.ContentConfig.NO_CONTENT @@ -1756,20 +1978,24 @@ def test_update_data_store_empty_call(): # i.e. request == None and no flattened fields passed, work. client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_store), - '__call__') as call: + type(client.transport.update_data_store), "__call__" + ) as call: client.update_data_store() call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == data_store_service.UpdateDataStoreRequest() + @pytest.mark.asyncio -async def test_update_data_store_async(transport: str = 'grpc_asyncio', request_type=data_store_service.UpdateDataStoreRequest): +async def test_update_data_store_async( + transport: str = "grpc_asyncio", + request_type=data_store_service.UpdateDataStoreRequest, +): client = DataStoreServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1781,17 +2007,19 @@ async def test_update_data_store_async(transport: str = 'grpc_asyncio', request_ # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_store), - '__call__') as call: + type(client.transport.update_data_store), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_data_store.DataStore( - name='name_value', - display_name='display_name_value', - industry_vertical=common.IndustryVertical.GENERIC, - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - default_schema_id='default_schema_id_value', - content_config=gcd_data_store.DataStore.ContentConfig.NO_CONTENT, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_data_store.DataStore( + name="name_value", + display_name="display_name_value", + industry_vertical=common.IndustryVertical.GENERIC, + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + default_schema_id="default_schema_id_value", + content_config=gcd_data_store.DataStore.ContentConfig.NO_CONTENT, + ) + ) response = await client.update_data_store(request) # Establish that the underlying gRPC stub method was called. @@ -1801,11 +2029,11 @@ async def test_update_data_store_async(transport: str = 'grpc_asyncio', request_ # Establish that the response is the type that we expect. assert isinstance(response, gcd_data_store.DataStore) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' + assert response.name == "name_value" + assert response.display_name == "display_name_value" assert response.industry_vertical == common.IndustryVertical.GENERIC assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - assert response.default_schema_id == 'default_schema_id_value' + assert response.default_schema_id == "default_schema_id_value" assert response.content_config == gcd_data_store.DataStore.ContentConfig.NO_CONTENT @@ -1823,12 +2051,12 @@ def test_update_data_store_field_headers(): # a field header. Set these to a non-empty value. request = data_store_service.UpdateDataStoreRequest() - request.data_store.name = 'name_value' + request.data_store.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_store), - '__call__') as call: + type(client.transport.update_data_store), "__call__" + ) as call: call.return_value = gcd_data_store.DataStore() client.update_data_store(request) @@ -1840,9 +2068,9 @@ def test_update_data_store_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'data_store.name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "data_store.name=name_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -1855,13 +2083,15 @@ async def test_update_data_store_field_headers_async(): # a field header. Set these to a non-empty value. request = data_store_service.UpdateDataStoreRequest() - request.data_store.name = 'name_value' + request.data_store.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_store), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_data_store.DataStore()) + type(client.transport.update_data_store), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_data_store.DataStore() + ) await client.update_data_store(request) # Establish that the underlying gRPC stub method was called. @@ -1872,9 +2102,9 @@ async def test_update_data_store_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'data_store.name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "data_store.name=name_value", + ) in kw["metadata"] def test_update_data_store_flattened(): @@ -1884,15 +2114,15 @@ def test_update_data_store_flattened(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_store), - '__call__') as call: + type(client.transport.update_data_store), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_data_store.DataStore() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_data_store( - data_store=gcd_data_store.DataStore(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + data_store=gcd_data_store.DataStore(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -1900,10 +2130,10 @@ def test_update_data_store_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].data_store - mock_val = gcd_data_store.DataStore(name='name_value') + mock_val = gcd_data_store.DataStore(name="name_value") assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @@ -1917,10 +2147,11 @@ def test_update_data_store_flattened_error(): with pytest.raises(ValueError): client.update_data_store( data_store_service.UpdateDataStoreRequest(), - data_store=gcd_data_store.DataStore(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + data_store=gcd_data_store.DataStore(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) + @pytest.mark.asyncio async def test_update_data_store_flattened_async(): client = DataStoreServiceAsyncClient( @@ -1929,17 +2160,19 @@ async def test_update_data_store_flattened_async(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_store), - '__call__') as call: + type(client.transport.update_data_store), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = gcd_data_store.DataStore() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_data_store.DataStore()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_data_store.DataStore() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.update_data_store( - data_store=gcd_data_store.DataStore(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + data_store=gcd_data_store.DataStore(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -1947,12 +2180,13 @@ async def test_update_data_store_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].data_store - mock_val = gcd_data_store.DataStore(name='name_value') + mock_val = gcd_data_store.DataStore(name="name_value") assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val + @pytest.mark.asyncio async def test_update_data_store_flattened_error_async(): client = DataStoreServiceAsyncClient( @@ -1964,15 +2198,18 @@ async def test_update_data_store_flattened_error_async(): with pytest.raises(ValueError): await client.update_data_store( data_store_service.UpdateDataStoreRequest(), - data_store=gcd_data_store.DataStore(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + data_store=gcd_data_store.DataStore(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -@pytest.mark.parametrize("request_type", [ - data_store_service.CreateDataStoreRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + data_store_service.CreateDataStoreRequest, + dict, + ], +) def test_create_data_store_rest(request_type): client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -1980,8 +2217,16 @@ def test_create_data_store_rest(request_type): ) # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["data_store"] = {'name': 'name_value', 'display_name': 'display_name_value', 'industry_vertical': 1, 'solution_types': [1], 'default_schema_id': 'default_schema_id_value', 'content_config': 1, 'create_time': {'seconds': 751, 'nanos': 543}} + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["data_store"] = { + "name": "name_value", + "display_name": "display_name_value", + "industry_vertical": 1, + "solution_types": [1], + "default_schema_id": "default_schema_id_value", + "content_config": 1, + "create_time": {"seconds": 751, "nanos": 543}, + } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 @@ -2001,7 +2246,7 @@ def get_message_fields(field): 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 + else: # pragma: NO COVER message_fields = field.message.DESCRIPTOR.fields return message_fields @@ -2015,7 +2260,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["data_store"].items(): # pragma: NO COVER + for field, value in request_init["data_store"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -2030,12 +2275,16 @@ def get_message_fields(field): 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} + { + "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 + 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") @@ -2048,16 +2297,16 @@ def get_message_fields(field): request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.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 = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.create_data_store(request) @@ -2065,7 +2314,9 @@ def get_message_fields(field): assert response.operation.name == "operations/spam" -def test_create_data_store_rest_required_fields(request_type=data_store_service.CreateDataStoreRequest): +def test_create_data_store_rest_required_fields( + request_type=data_store_service.CreateDataStoreRequest, +): transport_class = transports.DataStoreServiceRestTransport request_init = {} @@ -2073,66 +2324,77 @@ def test_create_data_store_rest_required_fields(request_type=data_store_service. request_init["data_store_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) # verify fields with default values are dropped assert "dataStoreId" not in jsonified_request - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_data_store._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_data_store._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present assert "dataStoreId" in jsonified_request assert jsonified_request["dataStoreId"] == request_init["data_store_id"] - jsonified_request["parent"] = 'parent_value' - jsonified_request["dataStoreId"] = 'data_store_id_value' + jsonified_request["parent"] = "parent_value" + jsonified_request["dataStoreId"] = "data_store_id_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_data_store._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_data_store._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("create_advanced_site_search", "data_store_id", )) + assert not set(unset_fields) - set( + ( + "create_advanced_site_search", + "data_store_id", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' + assert jsonified_request["parent"] == "parent_value" assert "dataStoreId" in jsonified_request - assert jsonified_request["dataStoreId"] == 'data_store_id_value' + assert jsonified_request["dataStoreId"] == "data_store_id_value" client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + 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: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force 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, + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, } - transcode_result['body'] = 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') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.create_data_store(request) @@ -2142,34 +2404,60 @@ def test_create_data_store_rest_required_fields(request_type=data_store_service. "dataStoreId", "", ), - ('$alt', 'json;enum-encoding=int') + ("$alt", "json;enum-encoding=int"), ] - actual_params = req.call_args.kwargs['params'] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_create_data_store_rest_unset_required_fields(): - transport = transports.DataStoreServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.DataStoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.create_data_store._get_unset_required_fields({}) - assert set(unset_fields) == (set(("createAdvancedSiteSearch", "dataStoreId", )) & set(("parent", "dataStore", "dataStoreId", ))) + assert set(unset_fields) == ( + set( + ( + "createAdvancedSiteSearch", + "dataStoreId", + ) + ) + & set( + ( + "parent", + "dataStore", + "dataStoreId", + ) + ) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) def test_create_data_store_rest_interceptors(null_interceptor): transport = transports.DataStoreServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DataStoreServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.DataStoreServiceRestInterceptor(), + ) client = DataStoreServiceClient(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.DataStoreServiceRestInterceptor, "post_create_data_store") as post, \ - mock.patch.object(transports.DataStoreServiceRestInterceptor, "pre_create_data_store") as pre: + 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.DataStoreServiceRestInterceptor, "post_create_data_store" + ) as post, mock.patch.object( + transports.DataStoreServiceRestInterceptor, "pre_create_data_store" + ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = data_store_service.CreateDataStoreRequest.pb(data_store_service.CreateDataStoreRequest()) + pb_message = data_store_service.CreateDataStoreRequest.pb( + data_store_service.CreateDataStoreRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2180,34 +2468,46 @@ def test_create_data_store_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) request = data_store_service.CreateDataStoreRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.create_data_store(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.create_data_store( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() -def test_create_data_store_rest_bad_request(transport: str = 'rest', request_type=data_store_service.CreateDataStoreRequest): +def test_create_data_store_rest_bad_request( + transport: str = "rest", request_type=data_store_service.CreateDataStoreRequest +): client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} + 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): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 400 @@ -2223,18 +2523,18 @@ def test_create_data_store_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: + with mock.patch.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 = 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 = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - parent='parent_value', - data_store=gcd_data_store.DataStore(name='name_value'), - data_store_id='data_store_id_value', + parent="parent_value", + data_store=gcd_data_store.DataStore(name="name_value"), + data_store_id="data_store_id_value", ) mock_args.update(sample_request) @@ -2242,7 +2542,7 @@ def test_create_data_store_rest_flattened(): response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value client.create_data_store(**mock_args) @@ -2251,10 +2551,14 @@ def test_create_data_store_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1alpha/{parent=projects/*/locations/*}/dataStores" % client.transport._host, args[1]) + assert path_template.validate( + "%s/v1alpha/{parent=projects/*/locations/*}/dataStores" + % client.transport._host, + args[1], + ) -def test_create_data_store_rest_flattened_error(transport: str = 'rest'): +def test_create_data_store_rest_flattened_error(transport: str = "rest"): client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2265,23 +2569,25 @@ def test_create_data_store_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.create_data_store( data_store_service.CreateDataStoreRequest(), - parent='parent_value', - data_store=gcd_data_store.DataStore(name='name_value'), - data_store_id='data_store_id_value', + parent="parent_value", + data_store=gcd_data_store.DataStore(name="name_value"), + data_store_id="data_store_id_value", ) def test_create_data_store_rest_error(): client = DataStoreServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) -@pytest.mark.parametrize("request_type", [ - data_store_service.GetDataStoreRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + data_store_service.GetDataStoreRequest, + dict, + ], +) def test_get_data_store_rest(request_type): client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2289,19 +2595,19 @@ def test_get_data_store_rest(request_type): ) # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3'} + request_init = {"name": "projects/sample1/locations/sample2/dataStores/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: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = data_store.DataStore( - name='name_value', - display_name='display_name_value', - industry_vertical=common.IndustryVertical.GENERIC, - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - default_schema_id='default_schema_id_value', - content_config=data_store.DataStore.ContentConfig.NO_CONTENT, + name="name_value", + display_name="display_name_value", + industry_vertical=common.IndustryVertical.GENERIC, + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + default_schema_id="default_schema_id_value", + content_config=data_store.DataStore.ContentConfig.NO_CONTENT, ) # Wrap the value into a proper Response obj @@ -2311,70 +2617,78 @@ def test_get_data_store_rest(request_type): return_value = data_store.DataStore.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.get_data_store(request) # Establish that the response is the type that we expect. assert isinstance(response, data_store.DataStore) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' + assert response.name == "name_value" + assert response.display_name == "display_name_value" assert response.industry_vertical == common.IndustryVertical.GENERIC assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - assert response.default_schema_id == 'default_schema_id_value' + assert response.default_schema_id == "default_schema_id_value" assert response.content_config == data_store.DataStore.ContentConfig.NO_CONTENT -def test_get_data_store_rest_required_fields(request_type=data_store_service.GetDataStoreRequest): +def test_get_data_store_rest_required_fields( + request_type=data_store_service.GetDataStoreRequest, +): transport_class = transports.DataStoreServiceRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_data_store._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_data_store._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = 'name_value' + jsonified_request["name"] = "name_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_data_store._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_data_store._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' + assert jsonified_request["name"] == "name_value" client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = data_store.DataStore() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force 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, + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, } transcode.return_value = transcode_result @@ -2385,39 +2699,48 @@ def test_get_data_store_rest_required_fields(request_type=data_store_service.Get return_value = data_store.DataStore.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.get_data_store(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_get_data_store_rest_unset_required_fields(): - transport = transports.DataStoreServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.DataStoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.get_data_store._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) def test_get_data_store_rest_interceptors(null_interceptor): transport = transports.DataStoreServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DataStoreServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.DataStoreServiceRestInterceptor(), + ) client = DataStoreServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DataStoreServiceRestInterceptor, "post_get_data_store") as post, \ - mock.patch.object(transports.DataStoreServiceRestInterceptor, "pre_get_data_store") as pre: + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.DataStoreServiceRestInterceptor, "post_get_data_store" + ) as post, mock.patch.object( + transports.DataStoreServiceRestInterceptor, "pre_get_data_store" + ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = data_store_service.GetDataStoreRequest.pb(data_store_service.GetDataStoreRequest()) + pb_message = data_store_service.GetDataStoreRequest.pb( + data_store_service.GetDataStoreRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2431,31 +2754,41 @@ def test_get_data_store_rest_interceptors(null_interceptor): req.return_value._content = data_store.DataStore.to_json(data_store.DataStore()) request = data_store_service.GetDataStoreRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = data_store.DataStore() - client.get_data_store(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.get_data_store( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() -def test_get_data_store_rest_bad_request(transport: str = 'rest', request_type=data_store_service.GetDataStoreRequest): +def test_get_data_store_rest_bad_request( + transport: str = "rest", request_type=data_store_service.GetDataStoreRequest +): client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3'} + request_init = {"name": "projects/sample1/locations/sample2/dataStores/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): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 400 @@ -2471,16 +2804,18 @@ def test_get_data_store_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: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = data_store.DataStore() # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/dataStores/sample3'} + sample_request = { + "name": "projects/sample1/locations/sample2/dataStores/sample3" + } # get truthy value for each flattened field mock_args = dict( - name='name_value', + name="name_value", ) mock_args.update(sample_request) @@ -2490,7 +2825,7 @@ def test_get_data_store_rest_flattened(): # Convert return value to protobuf type return_value = data_store.DataStore.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value client.get_data_store(**mock_args) @@ -2499,10 +2834,14 @@ def test_get_data_store_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1alpha/{name=projects/*/locations/*/dataStores/*}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/v1alpha/{name=projects/*/locations/*/dataStores/*}" + % client.transport._host, + args[1], + ) -def test_get_data_store_rest_flattened_error(transport: str = 'rest'): +def test_get_data_store_rest_flattened_error(transport: str = "rest"): client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2513,21 +2852,23 @@ def test_get_data_store_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.get_data_store( data_store_service.GetDataStoreRequest(), - name='name_value', + name="name_value", ) def test_get_data_store_rest_error(): client = DataStoreServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) -@pytest.mark.parametrize("request_type", [ - data_store_service.ListDataStoresRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + data_store_service.ListDataStoresRequest, + dict, + ], +) def test_list_data_stores_rest(request_type): client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2535,14 +2876,14 @@ def test_list_data_stores_rest(request_type): ) # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} + 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: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = data_store_service.ListDataStoresResponse( - next_page_token='next_page_token_value', + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj @@ -2552,67 +2893,81 @@ def test_list_data_stores_rest(request_type): return_value = data_store_service.ListDataStoresResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.list_data_stores(request) # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListDataStoresPager) - assert response.next_page_token == 'next_page_token_value' + assert response.next_page_token == "next_page_token_value" -def test_list_data_stores_rest_required_fields(request_type=data_store_service.ListDataStoresRequest): +def test_list_data_stores_rest_required_fields( + request_type=data_store_service.ListDataStoresRequest, +): transport_class = transports.DataStoreServiceRestTransport request_init = {} request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_data_stores._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_data_stores._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = 'parent_value' + jsonified_request["parent"] = "parent_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_data_stores._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_data_stores._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) + assert not set(unset_fields) - set( + ( + "filter", + "page_size", + "page_token", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' + assert jsonified_request["parent"] == "parent_value" client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = data_store_service.ListDataStoresResponse() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force 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, + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, } transcode.return_value = transcode_result @@ -2623,39 +2978,57 @@ def test_list_data_stores_rest_required_fields(request_type=data_store_service.L return_value = data_store_service.ListDataStoresResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.list_data_stores(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_list_data_stores_rest_unset_required_fields(): - transport = transports.DataStoreServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.DataStoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.list_data_stores._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) def test_list_data_stores_rest_interceptors(null_interceptor): transport = transports.DataStoreServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DataStoreServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.DataStoreServiceRestInterceptor(), + ) client = DataStoreServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DataStoreServiceRestInterceptor, "post_list_data_stores") as post, \ - mock.patch.object(transports.DataStoreServiceRestInterceptor, "pre_list_data_stores") as pre: + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.DataStoreServiceRestInterceptor, "post_list_data_stores" + ) as post, mock.patch.object( + transports.DataStoreServiceRestInterceptor, "pre_list_data_stores" + ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = data_store_service.ListDataStoresRequest.pb(data_store_service.ListDataStoresRequest()) + pb_message = data_store_service.ListDataStoresRequest.pb( + data_store_service.ListDataStoresRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2666,34 +3039,46 @@ def test_list_data_stores_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = data_store_service.ListDataStoresResponse.to_json(data_store_service.ListDataStoresResponse()) + req.return_value._content = data_store_service.ListDataStoresResponse.to_json( + data_store_service.ListDataStoresResponse() + ) request = data_store_service.ListDataStoresRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = data_store_service.ListDataStoresResponse() - client.list_data_stores(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.list_data_stores( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() -def test_list_data_stores_rest_bad_request(transport: str = 'rest', request_type=data_store_service.ListDataStoresRequest): +def test_list_data_stores_rest_bad_request( + transport: str = "rest", request_type=data_store_service.ListDataStoresRequest +): client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} + 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): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 400 @@ -2709,16 +3094,16 @@ def test_list_data_stores_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: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = data_store_service.ListDataStoresResponse() # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} + sample_request = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - parent='parent_value', + parent="parent_value", ) mock_args.update(sample_request) @@ -2728,7 +3113,7 @@ def test_list_data_stores_rest_flattened(): # Convert return value to protobuf type return_value = data_store_service.ListDataStoresResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value client.list_data_stores(**mock_args) @@ -2737,10 +3122,14 @@ def test_list_data_stores_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1alpha/{parent=projects/*/locations/*}/dataStores" % client.transport._host, args[1]) + assert path_template.validate( + "%s/v1alpha/{parent=projects/*/locations/*}/dataStores" + % client.transport._host, + args[1], + ) -def test_list_data_stores_rest_flattened_error(transport: str = 'rest'): +def test_list_data_stores_rest_flattened_error(transport: str = "rest"): client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2751,20 +3140,20 @@ def test_list_data_stores_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.list_data_stores( data_store_service.ListDataStoresRequest(), - parent='parent_value', + parent="parent_value", ) -def test_list_data_stores_rest_pager(transport: str = 'rest'): +def test_list_data_stores_rest_pager(transport: str = "rest"): client = DataStoreServiceClient( 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: + 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: + # with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( data_store_service.ListDataStoresResponse( @@ -2773,17 +3162,17 @@ def test_list_data_stores_rest_pager(transport: str = 'rest'): data_store.DataStore(), data_store.DataStore(), ], - next_page_token='abc', + next_page_token="abc", ), data_store_service.ListDataStoresResponse( data_stores=[], - next_page_token='def', + next_page_token="def", ), data_store_service.ListDataStoresResponse( data_stores=[ data_store.DataStore(), ], - next_page_token='ghi', + next_page_token="ghi", ), data_store_service.ListDataStoresResponse( data_stores=[ @@ -2796,31 +3185,35 @@ def test_list_data_stores_rest_pager(transport: str = 'rest'): response = response + response # Wrap the values into proper Response objs - response = tuple(data_store_service.ListDataStoresResponse.to_json(x) for x in response) + response = tuple( + data_store_service.ListDataStoresResponse.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._content = response_val.encode("UTF-8") return_val.status_code = 200 req.side_effect = return_values - sample_request = {'parent': 'projects/sample1/locations/sample2'} + sample_request = {"parent": "projects/sample1/locations/sample2"} pager = client.list_data_stores(request=sample_request) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, data_store.DataStore) - for i in results) + assert all(isinstance(i, data_store.DataStore) for i in results) pages = list(client.list_data_stores(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize("request_type", [ - data_store_service.DeleteDataStoreRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + data_store_service.DeleteDataStoreRequest, + dict, + ], +) def test_delete_data_store_rest(request_type): client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2828,20 +3221,20 @@ def test_delete_data_store_rest(request_type): ) # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3'} + request_init = {"name": "projects/sample1/locations/sample2/dataStores/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: + with mock.patch.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 = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.delete_data_store(request) @@ -2849,56 +3242,64 @@ def test_delete_data_store_rest(request_type): assert response.operation.name == "operations/spam" -def test_delete_data_store_rest_required_fields(request_type=data_store_service.DeleteDataStoreRequest): +def test_delete_data_store_rest_required_fields( + request_type=data_store_service.DeleteDataStoreRequest, +): transport_class = transports.DataStoreServiceRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_data_store._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_data_store._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = 'name_value' + jsonified_request["name"] = "name_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_data_store._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_data_store._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' + assert jsonified_request["name"] == "name_value" client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + 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: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force 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, + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, } transcode.return_value = transcode_result @@ -2906,40 +3307,50 @@ def test_delete_data_store_rest_required_fields(request_type=data_store_service. response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.delete_data_store(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_delete_data_store_rest_unset_required_fields(): - transport = transports.DataStoreServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.DataStoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.delete_data_store._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) def test_delete_data_store_rest_interceptors(null_interceptor): transport = transports.DataStoreServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DataStoreServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.DataStoreServiceRestInterceptor(), + ) client = DataStoreServiceClient(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.DataStoreServiceRestInterceptor, "post_delete_data_store") as post, \ - mock.patch.object(transports.DataStoreServiceRestInterceptor, "pre_delete_data_store") as pre: + 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.DataStoreServiceRestInterceptor, "post_delete_data_store" + ) as post, mock.patch.object( + transports.DataStoreServiceRestInterceptor, "pre_delete_data_store" + ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = data_store_service.DeleteDataStoreRequest.pb(data_store_service.DeleteDataStoreRequest()) + pb_message = data_store_service.DeleteDataStoreRequest.pb( + data_store_service.DeleteDataStoreRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2950,34 +3361,46 @@ def test_delete_data_store_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) request = data_store_service.DeleteDataStoreRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.delete_data_store(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.delete_data_store( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() -def test_delete_data_store_rest_bad_request(transport: str = 'rest', request_type=data_store_service.DeleteDataStoreRequest): +def test_delete_data_store_rest_bad_request( + transport: str = "rest", request_type=data_store_service.DeleteDataStoreRequest +): client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/dataStores/sample3'} + request_init = {"name": "projects/sample1/locations/sample2/dataStores/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): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 400 @@ -2993,16 +3416,18 @@ def test_delete_data_store_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: + with mock.patch.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 = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/dataStores/sample3'} + sample_request = { + "name": "projects/sample1/locations/sample2/dataStores/sample3" + } # get truthy value for each flattened field mock_args = dict( - name='name_value', + name="name_value", ) mock_args.update(sample_request) @@ -3010,7 +3435,7 @@ def test_delete_data_store_rest_flattened(): response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value client.delete_data_store(**mock_args) @@ -3019,10 +3444,14 @@ def test_delete_data_store_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1alpha/{name=projects/*/locations/*/dataStores/*}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/v1alpha/{name=projects/*/locations/*/dataStores/*}" + % client.transport._host, + args[1], + ) -def test_delete_data_store_rest_flattened_error(transport: str = 'rest'): +def test_delete_data_store_rest_flattened_error(transport: str = "rest"): client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3033,21 +3462,23 @@ def test_delete_data_store_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.delete_data_store( data_store_service.DeleteDataStoreRequest(), - name='name_value', + name="name_value", ) def test_delete_data_store_rest_error(): client = DataStoreServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) -@pytest.mark.parametrize("request_type", [ - data_store_service.UpdateDataStoreRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + data_store_service.UpdateDataStoreRequest, + dict, + ], +) def test_update_data_store_rest(request_type): client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3055,8 +3486,18 @@ def test_update_data_store_rest(request_type): ) # send a request that will satisfy transcoding - request_init = {'data_store': {'name': 'projects/sample1/locations/sample2/dataStores/sample3'}} - request_init["data_store"] = {'name': 'projects/sample1/locations/sample2/dataStores/sample3', 'display_name': 'display_name_value', 'industry_vertical': 1, 'solution_types': [1], 'default_schema_id': 'default_schema_id_value', 'content_config': 1, 'create_time': {'seconds': 751, 'nanos': 543}} + request_init = { + "data_store": {"name": "projects/sample1/locations/sample2/dataStores/sample3"} + } + request_init["data_store"] = { + "name": "projects/sample1/locations/sample2/dataStores/sample3", + "display_name": "display_name_value", + "industry_vertical": 1, + "solution_types": [1], + "default_schema_id": "default_schema_id_value", + "content_config": 1, + "create_time": {"seconds": 751, "nanos": 543}, + } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 @@ -3076,7 +3517,7 @@ def get_message_fields(field): 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 + else: # pragma: NO COVER message_fields = field.message.DESCRIPTOR.fields return message_fields @@ -3090,7 +3531,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["data_store"].items(): # pragma: NO COVER + for field, value in request_init["data_store"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -3105,12 +3546,16 @@ def get_message_fields(field): 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} + { + "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 + 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") @@ -3123,15 +3568,15 @@ def get_message_fields(field): request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = gcd_data_store.DataStore( - name='name_value', - display_name='display_name_value', - industry_vertical=common.IndustryVertical.GENERIC, - solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], - default_schema_id='default_schema_id_value', - content_config=gcd_data_store.DataStore.ContentConfig.NO_CONTENT, + name="name_value", + display_name="display_name_value", + industry_vertical=common.IndustryVertical.GENERIC, + solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION], + default_schema_id="default_schema_id_value", + content_config=gcd_data_store.DataStore.ContentConfig.NO_CONTENT, ) # Wrap the value into a proper Response obj @@ -3141,69 +3586,77 @@ def get_message_fields(field): return_value = gcd_data_store.DataStore.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.update_data_store(request) # Establish that the response is the type that we expect. assert isinstance(response, gcd_data_store.DataStore) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' + assert response.name == "name_value" + assert response.display_name == "display_name_value" assert response.industry_vertical == common.IndustryVertical.GENERIC assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION] - assert response.default_schema_id == 'default_schema_id_value' + assert response.default_schema_id == "default_schema_id_value" assert response.content_config == gcd_data_store.DataStore.ContentConfig.NO_CONTENT -def test_update_data_store_rest_required_fields(request_type=data_store_service.UpdateDataStoreRequest): +def test_update_data_store_rest_required_fields( + request_type=data_store_service.UpdateDataStoreRequest, +): transport_class = transports.DataStoreServiceRestTransport request_init = {} request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_data_store._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_data_store._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_data_store._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_data_store._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) + assert not set(unset_fields) - set(("update_mask",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = gcd_data_store.DataStore() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force 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, + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, } - transcode_result['body'] = pb_request + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -3213,39 +3666,48 @@ def test_update_data_store_rest_required_fields(request_type=data_store_service. return_value = gcd_data_store.DataStore.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.update_data_store(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_update_data_store_rest_unset_required_fields(): - transport = transports.DataStoreServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.DataStoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.update_data_store._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("dataStore", ))) + assert set(unset_fields) == (set(("updateMask",)) & set(("dataStore",))) @pytest.mark.parametrize("null_interceptor", [True, False]) def test_update_data_store_rest_interceptors(null_interceptor): transport = transports.DataStoreServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.DataStoreServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.DataStoreServiceRestInterceptor(), + ) client = DataStoreServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.DataStoreServiceRestInterceptor, "post_update_data_store") as post, \ - mock.patch.object(transports.DataStoreServiceRestInterceptor, "pre_update_data_store") as pre: + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.DataStoreServiceRestInterceptor, "post_update_data_store" + ) as post, mock.patch.object( + transports.DataStoreServiceRestInterceptor, "pre_update_data_store" + ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = data_store_service.UpdateDataStoreRequest.pb(data_store_service.UpdateDataStoreRequest()) + pb_message = data_store_service.UpdateDataStoreRequest.pb( + data_store_service.UpdateDataStoreRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -3256,34 +3718,48 @@ def test_update_data_store_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = gcd_data_store.DataStore.to_json(gcd_data_store.DataStore()) + req.return_value._content = gcd_data_store.DataStore.to_json( + gcd_data_store.DataStore() + ) request = data_store_service.UpdateDataStoreRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = gcd_data_store.DataStore() - client.update_data_store(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.update_data_store( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() -def test_update_data_store_rest_bad_request(transport: str = 'rest', request_type=data_store_service.UpdateDataStoreRequest): +def test_update_data_store_rest_bad_request( + transport: str = "rest", request_type=data_store_service.UpdateDataStoreRequest +): client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # send a request that will satisfy transcoding - request_init = {'data_store': {'name': 'projects/sample1/locations/sample2/dataStores/sample3'}} + request_init = { + "data_store": {"name": "projects/sample1/locations/sample2/dataStores/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): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 400 @@ -3299,17 +3775,21 @@ def test_update_data_store_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: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = gcd_data_store.DataStore() # get arguments that satisfy an http rule for this method - sample_request = {'data_store': {'name': 'projects/sample1/locations/sample2/dataStores/sample3'}} + sample_request = { + "data_store": { + "name": "projects/sample1/locations/sample2/dataStores/sample3" + } + } # get truthy value for each flattened field mock_args = dict( - data_store=gcd_data_store.DataStore(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + data_store=gcd_data_store.DataStore(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -3319,7 +3799,7 @@ def test_update_data_store_rest_flattened(): # Convert return value to protobuf type return_value = gcd_data_store.DataStore.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value client.update_data_store(**mock_args) @@ -3328,10 +3808,14 @@ def test_update_data_store_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1alpha/{data_store.name=projects/*/locations/*/dataStores/*}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/v1alpha/{data_store.name=projects/*/locations/*/dataStores/*}" + % client.transport._host, + args[1], + ) -def test_update_data_store_rest_flattened_error(transport: str = 'rest'): +def test_update_data_store_rest_flattened_error(transport: str = "rest"): client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3342,15 +3826,14 @@ def test_update_data_store_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.update_data_store( data_store_service.UpdateDataStoreRequest(), - data_store=gcd_data_store.DataStore(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + data_store=gcd_data_store.DataStore(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) def test_update_data_store_rest_error(): client = DataStoreServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -3392,8 +3875,7 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = DataStoreServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() + client_options=options, credentials=ga_credentials.AnonymousCredentials() ) # It is an error to provide scopes and a transport instance. @@ -3415,6 +3897,7 @@ def test_transport_instance(): client = DataStoreServiceClient(transport=transport) assert client.transport is transport + def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.DataStoreServiceGrpcTransport( @@ -3429,28 +3912,37 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel -@pytest.mark.parametrize("transport_class", [ - transports.DataStoreServiceGrpcTransport, - transports.DataStoreServiceGrpcAsyncIOTransport, - transports.DataStoreServiceRestTransport, -]) + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DataStoreServiceGrpcTransport, + transports.DataStoreServiceGrpcAsyncIOTransport, + transports.DataStoreServiceRestTransport, + ], +) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "rest", + ], +) def test_transport_kind(transport_name): transport = DataStoreServiceClient.get_transport_class(transport_name)( credentials=ga_credentials.AnonymousCredentials(), ) assert transport.kind == transport_name + def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = DataStoreServiceClient( @@ -3461,18 +3953,21 @@ def test_transport_grpc_default(): transports.DataStoreServiceGrpcTransport, ) + def test_data_store_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.DataStoreServiceTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" + credentials_file="credentials.json", ) def test_data_store_service_base_transport(): # Instantiate the base transport. - with mock.patch('google.cloud.discoveryengine_v1alpha.services.data_store_service.transports.DataStoreServiceTransport.__init__') as Transport: + with mock.patch( + "google.cloud.discoveryengine_v1alpha.services.data_store_service.transports.DataStoreServiceTransport.__init__" + ) as Transport: Transport.return_value = None transport = transports.DataStoreServiceTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -3481,13 +3976,13 @@ def test_data_store_service_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - 'create_data_store', - 'get_data_store', - 'list_data_stores', - 'delete_data_store', - 'update_data_store', - 'get_operation', - 'list_operations', + "create_data_store", + "get_data_store", + "list_data_stores", + "delete_data_store", + "update_data_store", + "get_operation", + "list_operations", ) for method in methods: with pytest.raises(NotImplementedError): @@ -3503,7 +3998,7 @@ def test_data_store_service_base_transport(): # Catch all for all remaining methods and properties remainder = [ - 'kind', + "kind", ] for r in remainder: with pytest.raises(NotImplementedError): @@ -3512,25 +4007,30 @@ def test_data_store_service_base_transport(): def test_data_store_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.discoveryengine_v1alpha.services.data_store_service.transports.DataStoreServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.discoveryengine_v1alpha.services.data_store_service.transports.DataStoreServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.DataStoreServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", ) - load_creds.assert_called_once_with("credentials.json", + load_creds.assert_called_once_with( + "credentials.json", scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id="octopus", ) def test_data_store_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.discoveryengine_v1alpha.services.data_store_service.transports.DataStoreServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.discoveryengine_v1alpha.services.data_store_service.transports.DataStoreServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.DataStoreServiceTransport() @@ -3539,14 +4039,12 @@ def test_data_store_service_base_transport_with_adc(): def test_data_store_service_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: + with mock.patch.object(google.auth, "default", autospec=True) as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) DataStoreServiceClient() adc.assert_called_once_with( scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id=None, ) @@ -3561,12 +4059,12 @@ def test_data_store_service_auth_adc(): def test_data_store_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: + 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',), + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id="octopus", ) @@ -3580,48 +4078,45 @@ def test_data_store_service_transport_auth_adc(transport_class): ], ) def test_data_store_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'] + 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: + 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) + 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 - ) + gdch_mock.with_gdch_audience.assert_called_once_with(e) @pytest.mark.parametrize( "transport_class,grpc_helpers", [ (transports.DataStoreServiceGrpcTransport, grpc_helpers), - (transports.DataStoreServiceGrpcAsyncIOTransport, grpc_helpers_async) + (transports.DataStoreServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) def test_data_store_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( + 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"] - ) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) create_channel.assert_called_with( "discoveryengine.googleapis.com:443", credentials=creds, credentials_file=None, quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), scopes=["1", "2"], default_host="discoveryengine.googleapis.com", ssl_credentials=None, @@ -3632,10 +4127,14 @@ def test_data_store_service_transport_create_channel(transport_class, grpc_helpe ) -@pytest.mark.parametrize("transport_class", [transports.DataStoreServiceGrpcTransport, transports.DataStoreServiceGrpcAsyncIOTransport]) -def test_data_store_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): +@pytest.mark.parametrize( + "transport_class", + [ + transports.DataStoreServiceGrpcTransport, + transports.DataStoreServiceGrpcAsyncIOTransport, + ], +) +def test_data_store_service_grpc_transport_client_cert_source_for_mtls(transport_class): cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. @@ -3644,7 +4143,7 @@ def test_data_store_service_grpc_transport_client_cert_source_for_mtls( transport_class( host="squid.clam.whelk", credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds + ssl_channel_credentials=mock_ssl_channel_creds, ) mock_create_channel.assert_called_once_with( "squid.clam.whelk:443", @@ -3665,20 +4164,21 @@ def test_data_store_service_grpc_transport_client_cert_source_for_mtls( with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: transport_class( credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback + 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 + certificate_chain=expected_cert, private_key=expected_key ) + def test_data_store_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.DataStoreServiceRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.DataStoreServiceRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback ) mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) @@ -3686,7 +4186,7 @@ def test_data_store_service_http_transport_client_cert_source_for_mtls(): def test_data_store_service_rest_lro_client(): client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) transport = client.transport @@ -3700,43 +4200,58 @@ def test_data_store_service_rest_lro_client(): assert transport.operations_client is transport.operations_client -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) def test_data_store_service_host_no_port(transport_name): client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), - transport=transport_name, + client_options=client_options.ClientOptions( + api_endpoint="discoveryengine.googleapis.com" + ), + transport=transport_name, ) assert client.transport._host == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com' + "discoveryengine.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://discoveryengine.googleapis.com" ) -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) def test_data_store_service_host_with_port(transport_name): client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), + client_options=client_options.ClientOptions( + api_endpoint="discoveryengine.googleapis.com:8000" + ), transport=transport_name, ) assert client.transport._host == ( - 'discoveryengine.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com:8000' + "discoveryengine.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://discoveryengine.googleapis.com:8000" ) -@pytest.mark.parametrize("transport_name", [ - "rest", -]) + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) def test_data_store_service_client_transport_session_collision(transport_name): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() @@ -3763,8 +4278,10 @@ def test_data_store_service_client_transport_session_collision(transport_name): session1 = client1.transport.update_data_store._session session2 = client2.transport.update_data_store._session assert session1 != session2 + + def test_data_store_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.DataStoreServiceGrpcTransport( @@ -3777,7 +4294,7 @@ def test_data_store_service_grpc_transport_channel(): def test_data_store_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.DataStoreServiceGrpcAsyncIOTransport( @@ -3791,12 +4308,22 @@ def test_data_store_service_grpc_asyncio_transport_channel(): # 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.DataStoreServiceGrpcTransport, transports.DataStoreServiceGrpcAsyncIOTransport]) +@pytest.mark.parametrize( + "transport_class", + [ + transports.DataStoreServiceGrpcTransport, + transports.DataStoreServiceGrpcAsyncIOTransport, + ], +) def test_data_store_service_transport_channel_mtls_with_client_cert_source( - transport_class + 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: + 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 @@ -3805,7 +4332,7 @@ def test_data_store_service_transport_channel_mtls_with_client_cert_source( cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -3835,17 +4362,23 @@ def test_data_store_service_transport_channel_mtls_with_client_cert_source( # 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.DataStoreServiceGrpcTransport, transports.DataStoreServiceGrpcAsyncIOTransport]) -def test_data_store_service_transport_channel_mtls_with_adc( - transport_class -): +@pytest.mark.parametrize( + "transport_class", + [ + transports.DataStoreServiceGrpcTransport, + transports.DataStoreServiceGrpcAsyncIOTransport, + ], +) +def test_data_store_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: + 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() @@ -3876,7 +4409,7 @@ def test_data_store_service_transport_channel_mtls_with_adc( def test_data_store_service_grpc_lro_client(): client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) transport = client.transport @@ -3893,7 +4426,7 @@ def test_data_store_service_grpc_lro_client(): def test_data_store_service_grpc_lro_async_client(): client = DataStoreServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', + transport="grpc_asyncio", ) transport = client.transport @@ -3911,7 +4444,13 @@ def test_collection_path(): project = "squid" location = "clam" collection = "whelk" - expected = "projects/{project}/locations/{location}/collections/{collection}".format(project=project, location=location, collection=collection, ) + expected = ( + "projects/{project}/locations/{location}/collections/{collection}".format( + project=project, + location=location, + collection=collection, + ) + ) actual = DataStoreServiceClient.collection_path(project, location, collection) assert expected == actual @@ -3928,11 +4467,16 @@ def test_parse_collection_path(): actual = DataStoreServiceClient.parse_collection_path(path) assert expected == actual + def test_data_store_path(): project = "cuttlefish" location = "mussel" data_store = "winkle" - expected = "projects/{project}/locations/{location}/dataStores/{data_store}".format(project=project, location=location, data_store=data_store, ) + expected = "projects/{project}/locations/{location}/dataStores/{data_store}".format( + project=project, + location=location, + data_store=data_store, + ) actual = DataStoreServiceClient.data_store_path(project, location, data_store) assert expected == actual @@ -3949,9 +4493,12 @@ def test_parse_data_store_path(): actual = DataStoreServiceClient.parse_data_store_path(path) assert expected == actual + def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) actual = DataStoreServiceClient.common_billing_account_path(billing_account) assert expected == actual @@ -3966,9 +4513,12 @@ def test_parse_common_billing_account_path(): actual = DataStoreServiceClient.parse_common_billing_account_path(path) assert expected == actual + def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) + expected = "folders/{folder}".format( + folder=folder, + ) actual = DataStoreServiceClient.common_folder_path(folder) assert expected == actual @@ -3983,9 +4533,12 @@ def test_parse_common_folder_path(): actual = DataStoreServiceClient.parse_common_folder_path(path) assert expected == actual + def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) + expected = "organizations/{organization}".format( + organization=organization, + ) actual = DataStoreServiceClient.common_organization_path(organization) assert expected == actual @@ -4000,9 +4553,12 @@ def test_parse_common_organization_path(): actual = DataStoreServiceClient.parse_common_organization_path(path) assert expected == actual + def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) + expected = "projects/{project}".format( + project=project, + ) actual = DataStoreServiceClient.common_project_path(project) assert expected == actual @@ -4017,10 +4573,14 @@ def test_parse_common_project_path(): actual = DataStoreServiceClient.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, ) + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) actual = DataStoreServiceClient.common_location_path(project, location) assert expected == actual @@ -4040,14 +4600,18 @@ def test_parse_common_location_path(): def test_client_with_default_client_info(): client_info = gapic_v1.client_info.ClientInfo() - with mock.patch.object(transports.DataStoreServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.DataStoreServiceTransport, "_prep_wrapped_messages" + ) as prep: client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object(transports.DataStoreServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.DataStoreServiceTransport, "_prep_wrapped_messages" + ) as prep: transport_class = DataStoreServiceClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -4055,29 +4619,41 @@ def test_client_with_default_client_info(): ) prep.assert_called_once_with(client_info) + @pytest.mark.asyncio async def test_transport_close_async(): client = DataStoreServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: async with client: close.assert_not_called() close.assert_called_once() -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): +def test_get_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.GetOperationRequest +): client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'}, request) + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6" + }, + 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): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 400 @@ -4085,19 +4661,25 @@ def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=op req.return_value = response_value client.get_operation(request) -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) def test_get_operation_rest(request_type): client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'} + request_init = { + "name": "projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = operations_pb2.Operation() @@ -4106,7 +4688,7 @@ def test_get_operation_rest(request_type): response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.get_operation(request) @@ -4114,17 +4696,27 @@ def test_get_operation_rest(request_type): # Establish that the response is the type that we expect. assert isinstance(response, operations_pb2.Operation) -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + +def test_list_operations_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.ListOperationsRequest +): client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'}, request) + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5" + }, + 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): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 400 @@ -4132,19 +4724,25 @@ def test_list_operations_rest_bad_request(transport: str = 'rest', request_type= req.return_value = response_value client.list_operations(request) -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) def test_list_operations_rest(request_type): client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'} + request_init = { + "name": "projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = operations_pb2.ListOperationsResponse() @@ -4153,7 +4751,7 @@ def test_list_operations_rest(request_type): response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.list_operations(request) @@ -4164,7 +4762,8 @@ def test_list_operations_rest(request_type): def test_get_operation(transport: str = "grpc"): client = DataStoreServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4183,10 +4782,13 @@ def test_get_operation(transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, operations_pb2.Operation) + + @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc"): client = DataStoreServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4208,6 +4810,7 @@ async def test_get_operation_async(transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, operations_pb2.Operation) + def test_get_operation_field_headers(): client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4230,7 +4833,12 @@ def test_get_operation_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = DataStoreServiceAsyncClient( @@ -4255,7 +4863,11 @@ async def test_get_operation_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + def test_get_operation_from_dict(): client = DataStoreServiceClient( @@ -4272,6 +4884,8 @@ def test_get_operation_from_dict(): } ) call.assert_called() + + @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = DataStoreServiceAsyncClient( @@ -4293,7 +4907,8 @@ async def test_get_operation_from_dict_async(): def test_list_operations(transport: str = "grpc"): client = DataStoreServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4312,10 +4927,13 @@ def test_list_operations(transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, operations_pb2.ListOperationsResponse) + + @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc"): client = DataStoreServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4337,6 +4955,7 @@ async def test_list_operations_async(transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, operations_pb2.ListOperationsResponse) + def test_list_operations_field_headers(): client = DataStoreServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4359,7 +4978,12 @@ def test_list_operations_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = DataStoreServiceAsyncClient( @@ -4384,7 +5008,11 @@ async def test_list_operations_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + def test_list_operations_from_dict(): client = DataStoreServiceClient( @@ -4401,6 +5029,8 @@ def test_list_operations_from_dict(): } ) call.assert_called() + + @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = DataStoreServiceAsyncClient( @@ -4428,23 +5058,24 @@ def test_transport_close(): for transport, close_name in transports.items(): client = DataStoreServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport + credentials=ga_credentials.AnonymousCredentials(), transport=transport ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with mock.patch.object( + type(getattr(client.transport, close_name)), "close" + ) as close: with client: close.assert_not_called() close.assert_called_once() + def test_client_ctx(): transports = [ - 'rest', - 'grpc', + "rest", + "grpc", ] for transport in transports: client = DataStoreServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport + credentials=ga_credentials.AnonymousCredentials(), transport=transport ) # Test client calls underlying transport. with mock.patch.object(type(client.transport), "close") as close: @@ -4453,10 +5084,14 @@ def test_client_ctx(): pass close.assert_called() -@pytest.mark.parametrize("client_class,transport_class", [ - (DataStoreServiceClient, transports.DataStoreServiceGrpcTransport), - (DataStoreServiceAsyncClient, transports.DataStoreServiceGrpcAsyncIOTransport), -]) + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (DataStoreServiceClient, transports.DataStoreServiceGrpcTransport), + (DataStoreServiceAsyncClient, transports.DataStoreServiceGrpcAsyncIOTransport), + ], +) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True diff --git a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_engine_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_engine_service.py similarity index 69% rename from owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_engine_service.py rename to packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_engine_service.py index 009616760cdc..b560a2231f3a 100644 --- a/owl-bot-staging/google-cloud-discoveryengine/v1alpha/tests/unit/gapic/discoveryengine_v1alpha/test_engine_service.py +++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1alpha/test_engine_service.py @@ -14,6 +14,7 @@ # limitations under the License. # import os + # try/except added for compatibility with python < 3.8 try: from unittest import mock @@ -21,47 +22,50 @@ except ImportError: # pragma: NO COVER import mock -import grpc -from grpc.experimental import aio from collections.abc import Iterable -from google.protobuf import json_format import json import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format +from google.api_core import ( + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + operation, + operations_v1, + path_template, +) from google.api_core import client_options from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template +import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError -from google.cloud.discoveryengine_v1alpha.services.engine_service import EngineServiceAsyncClient -from google.cloud.discoveryengine_v1alpha.services.engine_service import EngineServiceClient -from google.cloud.discoveryengine_v1alpha.services.engine_service import pagers -from google.cloud.discoveryengine_v1alpha.services.engine_service import transports -from google.cloud.discoveryengine_v1alpha.types import common -from google.cloud.discoveryengine_v1alpha.types import engine -from google.cloud.discoveryengine_v1alpha.types import engine as gcd_engine -from google.cloud.discoveryengine_v1alpha.types import engine_service from google.cloud.location import locations_pb2 -from google.longrunning import operations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore -import google.auth +import grpc +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +from google.cloud.discoveryengine_v1alpha.services.engine_service import ( + EngineServiceAsyncClient, + EngineServiceClient, + pagers, + transports, +) +from google.cloud.discoveryengine_v1alpha.types import common +from google.cloud.discoveryengine_v1alpha.types import engine +from google.cloud.discoveryengine_v1alpha.types import engine as gcd_engine +from google.cloud.discoveryengine_v1alpha.types import engine_service def client_cert_source_callback(): @@ -72,7 +76,11 @@ def client_cert_source_callback(): # 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 + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) def test__get_default_mtls_endpoint(): @@ -83,21 +91,40 @@ def test__get_default_mtls_endpoint(): non_googleapi = "api.example.com" assert EngineServiceClient._get_default_mtls_endpoint(None) is None - assert EngineServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert EngineServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert EngineServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert EngineServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert EngineServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (EngineServiceClient, "grpc"), - (EngineServiceAsyncClient, "grpc_asyncio"), - (EngineServiceClient, "rest"), -]) + assert ( + EngineServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + EngineServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + EngineServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + EngineServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + EngineServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + ) + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (EngineServiceClient, "grpc"), + (EngineServiceAsyncClient, "grpc_asyncio"), + (EngineServiceClient, "rest"), + ], +) def test_engine_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: + 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) @@ -105,52 +132,68 @@ def test_engine_service_client_from_service_account_info(client_class, transport assert isinstance(client, client_class) assert client.transport._host == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' + "discoveryengine.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://discoveryengine.googleapis.com" ) -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.EngineServiceGrpcTransport, "grpc"), - (transports.EngineServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.EngineServiceRestTransport, "rest"), -]) -def test_engine_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: +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.EngineServiceGrpcTransport, "grpc"), + (transports.EngineServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.EngineServiceRestTransport, "rest"), + ], +) +def test_engine_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: + 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", [ - (EngineServiceClient, "grpc"), - (EngineServiceAsyncClient, "grpc_asyncio"), - (EngineServiceClient, "rest"), -]) +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (EngineServiceClient, "grpc"), + (EngineServiceAsyncClient, "grpc_asyncio"), + (EngineServiceClient, "rest"), + ], +) def test_engine_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: + 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) + 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) + 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 == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://discoveryengine.googleapis.com' + "discoveryengine.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://discoveryengine.googleapis.com" ) @@ -166,30 +209,45 @@ def test_engine_service_client_get_transport_class(): assert transport == transports.EngineServiceGrpcTransport -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (EngineServiceClient, transports.EngineServiceGrpcTransport, "grpc"), - (EngineServiceAsyncClient, transports.EngineServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (EngineServiceClient, transports.EngineServiceRestTransport, "rest"), -]) -@mock.patch.object(EngineServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EngineServiceClient)) -@mock.patch.object(EngineServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EngineServiceAsyncClient)) -def test_engine_service_client_client_options(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (EngineServiceClient, transports.EngineServiceGrpcTransport, "grpc"), + ( + EngineServiceAsyncClient, + transports.EngineServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (EngineServiceClient, transports.EngineServiceRestTransport, "rest"), + ], +) +@mock.patch.object( + EngineServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(EngineServiceClient), +) +@mock.patch.object( + EngineServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(EngineServiceAsyncClient), +) +def test_engine_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(EngineServiceClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) + with mock.patch.object(EngineServiceClient, "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(EngineServiceClient, 'get_transport_class') as gtc: + with mock.patch.object(EngineServiceClient, "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: + 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( @@ -207,7 +265,7 @@ def test_engine_service_client_client_options(client_class, transport_class, tra # 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: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( @@ -225,7 +283,7 @@ def test_engine_service_client_client_options(client_class, transport_class, tra # 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: + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( @@ -247,13 +305,15 @@ def test_engine_service_client_client_options(client_class, transport_class, tra client = client_class(transport=transport_name) # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): with pytest.raises(ValueError): client = client_class(transport=transport_name) # Check the case quota_project_id is provided options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: + 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( @@ -268,8 +328,10 @@ def test_engine_service_client_client_options(client_class, transport_class, tra 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: + 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( @@ -281,29 +343,57 @@ def test_engine_service_client_client_options(client_class, transport_class, tra 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", [ - (EngineServiceClient, transports.EngineServiceGrpcTransport, "grpc", "true"), - (EngineServiceAsyncClient, transports.EngineServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (EngineServiceClient, transports.EngineServiceGrpcTransport, "grpc", "false"), - (EngineServiceAsyncClient, transports.EngineServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (EngineServiceClient, transports.EngineServiceRestTransport, "rest", "true"), - (EngineServiceClient, transports.EngineServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(EngineServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EngineServiceClient)) -@mock.patch.object(EngineServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EngineServiceAsyncClient)) + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (EngineServiceClient, transports.EngineServiceGrpcTransport, "grpc", "true"), + ( + EngineServiceAsyncClient, + transports.EngineServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (EngineServiceClient, transports.EngineServiceGrpcTransport, "grpc", "false"), + ( + EngineServiceAsyncClient, + transports.EngineServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + (EngineServiceClient, transports.EngineServiceRestTransport, "rest", "true"), + (EngineServiceClient, transports.EngineServiceRestTransport, "rest", "false"), + ], +) +@mock.patch.object( + EngineServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(EngineServiceClient), +) +@mock.patch.object( + EngineServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(EngineServiceAsyncClient), +) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_engine_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): +def test_engine_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: + 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) @@ -328,10 +418,18 @@ def test_engine_service_client_mtls_env_auto(client_class, transport_class, tran # 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): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): if use_client_cert_env == "false": expected_host = client.DEFAULT_ENDPOINT expected_client_cert_source = None @@ -354,9 +452,14 @@ def test_engine_service_client_mtls_env_auto(client_class, transport_class, tran ) # 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): + 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( @@ -372,19 +475,31 @@ def test_engine_service_client_mtls_env_auto(client_class, transport_class, tran ) -@pytest.mark.parametrize("client_class", [ - EngineServiceClient, EngineServiceAsyncClient -]) -@mock.patch.object(EngineServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EngineServiceClient)) -@mock.patch.object(EngineServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EngineServiceAsyncClient)) +@pytest.mark.parametrize( + "client_class", [EngineServiceClient, EngineServiceAsyncClient] +) +@mock.patch.object( + EngineServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(EngineServiceClient), +) +@mock.patch.object( + EngineServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(EngineServiceAsyncClient), +) def test_engine_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) + 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 @@ -392,8 +507,12 @@ def test_engine_service_client_get_mtls_endpoint_and_cert_source(client_class): 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) + 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 @@ -411,31 +530,52 @@ def test_engine_service_client_get_mtls_endpoint_and_cert_source(client_class): # 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): + 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() + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (EngineServiceClient, transports.EngineServiceGrpcTransport, "grpc"), - (EngineServiceAsyncClient, transports.EngineServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (EngineServiceClient, transports.EngineServiceRestTransport, "rest"), -]) -def test_engine_service_client_client_options_scopes(client_class, transport_class, transport_name): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (EngineServiceClient, transports.EngineServiceGrpcTransport, "grpc"), + ( + EngineServiceAsyncClient, + transports.EngineServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (EngineServiceClient, transports.EngineServiceRestTransport, "rest"), + ], +) +def test_engine_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: + 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( @@ -450,18 +590,32 @@ def test_engine_service_client_client_options_scopes(client_class, transport_cla api_audience=None, ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (EngineServiceClient, transports.EngineServiceGrpcTransport, "grpc", grpc_helpers), - (EngineServiceAsyncClient, transports.EngineServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (EngineServiceClient, transports.EngineServiceRestTransport, "rest", None), -]) -def test_engine_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + EngineServiceClient, + transports.EngineServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + EngineServiceAsyncClient, + transports.EngineServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + (EngineServiceClient, transports.EngineServiceRestTransport, "rest", None), + ], +) +def test_engine_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" - ) + options = client_options.ClientOptions(credentials_file="credentials.json") - with mock.patch.object(transport_class, '__init__') as patched: + 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( @@ -476,11 +630,14 @@ def test_engine_service_client_client_options_credentials_file(client_class, tra api_audience=None, ) + def test_engine_service_client_client_options_from_dict(): - with mock.patch('google.cloud.discoveryengine_v1alpha.services.engine_service.transports.EngineServiceGrpcTransport.__init__') as grpc_transport: + with mock.patch( + "google.cloud.discoveryengine_v1alpha.services.engine_service.transports.EngineServiceGrpcTransport.__init__" + ) as grpc_transport: grpc_transport.return_value = None client = EngineServiceClient( - client_options={'api_endpoint': 'squid.clam.whelk'} + client_options={"api_endpoint": "squid.clam.whelk"} ) grpc_transport.assert_called_once_with( credentials=None, @@ -495,17 +652,30 @@ def test_engine_service_client_client_options_from_dict(): ) -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (EngineServiceClient, transports.EngineServiceGrpcTransport, "grpc", grpc_helpers), - (EngineServiceAsyncClient, transports.EngineServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_engine_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + EngineServiceClient, + transports.EngineServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + EngineServiceAsyncClient, + transports.EngineServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_engine_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" - ) + options = client_options.ClientOptions(credentials_file="credentials.json") - with mock.patch.object(transport_class, '__init__') as patched: + 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( @@ -538,9 +708,7 @@ def test_engine_service_client_create_channel_credentials_file(client_class, tra credentials=file_creds, credentials_file=None, quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), scopes=None, default_host="discoveryengine.googleapis.com", ssl_credentials=None, @@ -551,11 +719,14 @@ def test_engine_service_client_create_channel_credentials_file(client_class, tra ) -@pytest.mark.parametrize("request_type", [ - engine_service.CreateEngineRequest, - dict, -]) -def test_create_engine(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + engine_service.CreateEngineRequest, + dict, + ], +) +def test_create_engine(request_type, transport: str = "grpc"): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -566,11 +737,9 @@ def test_create_engine(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.create_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.create_engine), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') + call.return_value = operations_pb2.Operation(name="operations/spam") response = client.create_engine(request) # Establish that the underlying gRPC stub method was called. @@ -587,20 +756,21 @@ def test_create_engine_empty_call(): # i.e. request == None and no flattened fields passed, work. client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.create_engine), "__call__") as call: client.create_engine() call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == engine_service.CreateEngineRequest() + @pytest.mark.asyncio -async def test_create_engine_async(transport: str = 'grpc_asyncio', request_type=engine_service.CreateEngineRequest): +async def test_create_engine_async( + transport: str = "grpc_asyncio", request_type=engine_service.CreateEngineRequest +): client = EngineServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -611,12 +781,10 @@ async def test_create_engine_async(transport: str = 'grpc_asyncio', request_type request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.create_engine), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) response = await client.create_engine(request) @@ -643,13 +811,11 @@ def test_create_engine_field_headers(): # a field header. Set these to a non-empty value. request = engine_service.CreateEngineRequest() - request.parent = 'parent_value' + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_engine), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') + with mock.patch.object(type(client.transport.create_engine), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") client.create_engine(request) # Establish that the underlying gRPC stub method was called. @@ -660,9 +826,9 @@ def test_create_engine_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -675,13 +841,13 @@ async def test_create_engine_field_headers_async(): # a field header. Set these to a non-empty value. request = engine_service.CreateEngineRequest() - request.parent = 'parent_value' + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_engine), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + with mock.patch.object(type(client.transport.create_engine), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) await client.create_engine(request) # Establish that the underlying gRPC stub method was called. @@ -692,9 +858,9 @@ async def test_create_engine_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] def test_create_engine_flattened(): @@ -703,17 +869,15 @@ def test_create_engine_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.create_engine), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + 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_engine( - parent='parent_value', + parent="parent_value", engine=gcd_engine.Engine(similar_documents_config=None), - engine_id='engine_id_value', + engine_id="engine_id_value", ) # Establish that the underlying call was made with the expected @@ -721,13 +885,13 @@ def test_create_engine_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val arg = args[0].engine mock_val = gcd_engine.Engine(similar_documents_config=None) assert arg == mock_val arg = args[0].engine_id - mock_val = 'engine_id_value' + mock_val = "engine_id_value" assert arg == mock_val @@ -741,11 +905,12 @@ def test_create_engine_flattened_error(): with pytest.raises(ValueError): client.create_engine( engine_service.CreateEngineRequest(), - parent='parent_value', + parent="parent_value", engine=gcd_engine.Engine(similar_documents_config=None), - engine_id='engine_id_value', + engine_id="engine_id_value", ) + @pytest.mark.asyncio async def test_create_engine_flattened_async(): client = EngineServiceAsyncClient( @@ -753,21 +918,19 @@ async def test_create_engine_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.create_engine), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + 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_engine( - parent='parent_value', + parent="parent_value", engine=gcd_engine.Engine(similar_documents_config=None), - engine_id='engine_id_value', + engine_id="engine_id_value", ) # Establish that the underlying call was made with the expected @@ -775,15 +938,16 @@ async def test_create_engine_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val arg = args[0].engine mock_val = gcd_engine.Engine(similar_documents_config=None) assert arg == mock_val arg = args[0].engine_id - mock_val = 'engine_id_value' + mock_val = "engine_id_value" assert arg == mock_val + @pytest.mark.asyncio async def test_create_engine_flattened_error_async(): client = EngineServiceAsyncClient( @@ -795,17 +959,20 @@ async def test_create_engine_flattened_error_async(): with pytest.raises(ValueError): await client.create_engine( engine_service.CreateEngineRequest(), - parent='parent_value', + parent="parent_value", engine=gcd_engine.Engine(similar_documents_config=None), - engine_id='engine_id_value', + engine_id="engine_id_value", ) -@pytest.mark.parametrize("request_type", [ - engine_service.DeleteEngineRequest, - dict, -]) -def test_delete_engine(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + engine_service.DeleteEngineRequest, + dict, + ], +) +def test_delete_engine(request_type, transport: str = "grpc"): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -816,11 +983,9 @@ def test_delete_engine(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_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.delete_engine), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') + call.return_value = operations_pb2.Operation(name="operations/spam") response = client.delete_engine(request) # Establish that the underlying gRPC stub method was called. @@ -837,20 +1002,21 @@ def test_delete_engine_empty_call(): # i.e. request == None and no flattened fields passed, work. client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.delete_engine), "__call__") as call: client.delete_engine() call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == engine_service.DeleteEngineRequest() + @pytest.mark.asyncio -async def test_delete_engine_async(transport: str = 'grpc_asyncio', request_type=engine_service.DeleteEngineRequest): +async def test_delete_engine_async( + transport: str = "grpc_asyncio", request_type=engine_service.DeleteEngineRequest +): client = EngineServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -861,12 +1027,10 @@ async def test_delete_engine_async(transport: str = 'grpc_asyncio', request_type request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.delete_engine), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) response = await client.delete_engine(request) @@ -893,13 +1057,11 @@ def test_delete_engine_field_headers(): # a field header. Set these to a non-empty value. request = engine_service.DeleteEngineRequest() - request.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.delete_engine), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') + with mock.patch.object(type(client.transport.delete_engine), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") client.delete_engine(request) # Establish that the underlying gRPC stub method was called. @@ -910,9 +1072,9 @@ def test_delete_engine_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -925,13 +1087,13 @@ async def test_delete_engine_field_headers_async(): # a field header. Set these to a non-empty value. request = engine_service.DeleteEngineRequest() - request.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.delete_engine), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + with mock.patch.object(type(client.transport.delete_engine), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) await client.delete_engine(request) # Establish that the underlying gRPC stub method was called. @@ -942,9 +1104,9 @@ async def test_delete_engine_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] def test_delete_engine_flattened(): @@ -953,15 +1115,13 @@ def test_delete_engine_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.delete_engine), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + 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_engine( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -969,7 +1129,7 @@ def test_delete_engine_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val @@ -983,9 +1143,10 @@ def test_delete_engine_flattened_error(): with pytest.raises(ValueError): client.delete_engine( engine_service.DeleteEngineRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_delete_engine_flattened_async(): client = EngineServiceAsyncClient( @@ -993,19 +1154,17 @@ async def test_delete_engine_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.delete_engine), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + 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_engine( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1013,9 +1172,10 @@ async def test_delete_engine_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val + @pytest.mark.asyncio async def test_delete_engine_flattened_error_async(): client = EngineServiceAsyncClient( @@ -1027,15 +1187,18 @@ async def test_delete_engine_flattened_error_async(): with pytest.raises(ValueError): await client.delete_engine( engine_service.DeleteEngineRequest(), - name='name_value', + name="name_value", ) -@pytest.mark.parametrize("request_type", [ - engine_service.UpdateEngineRequest, - dict, -]) -def test_update_engine(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + engine_service.UpdateEngineRequest, + dict, + ], +) +def test_update_engine(request_type, transport: str = "grpc"): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1046,14 +1209,12 @@ def test_update_engine(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_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.update_engine), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcd_engine.Engine( - name='name_value', - display_name='display_name_value', - data_store_ids=['data_store_ids_value'], + name="name_value", + display_name="display_name_value", + data_store_ids=["data_store_ids_value"], solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, industry_vertical=common.IndustryVertical.GENERIC, ) @@ -1066,9 +1227,9 @@ def test_update_engine(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, gcd_engine.Engine) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.data_store_ids == ['data_store_ids_value'] + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.data_store_ids == ["data_store_ids_value"] assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION assert response.industry_vertical == common.IndustryVertical.GENERIC @@ -1078,20 +1239,21 @@ def test_update_engine_empty_call(): # i.e. request == None and no flattened fields passed, work. client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.update_engine), "__call__") as call: client.update_engine() call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == engine_service.UpdateEngineRequest() + @pytest.mark.asyncio -async def test_update_engine_async(transport: str = 'grpc_asyncio', request_type=engine_service.UpdateEngineRequest): +async def test_update_engine_async( + transport: str = "grpc_asyncio", request_type=engine_service.UpdateEngineRequest +): client = EngineServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1102,17 +1264,17 @@ async def test_update_engine_async(transport: str = 'grpc_asyncio', request_type request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.update_engine), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gcd_engine.Engine( - name='name_value', - display_name='display_name_value', - data_store_ids=['data_store_ids_value'], - solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, - industry_vertical=common.IndustryVertical.GENERIC, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_engine.Engine( + name="name_value", + display_name="display_name_value", + data_store_ids=["data_store_ids_value"], + solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, + industry_vertical=common.IndustryVertical.GENERIC, + ) + ) response = await client.update_engine(request) # Establish that the underlying gRPC stub method was called. @@ -1122,9 +1284,9 @@ async def test_update_engine_async(transport: str = 'grpc_asyncio', request_type # Establish that the response is the type that we expect. assert isinstance(response, gcd_engine.Engine) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.data_store_ids == ['data_store_ids_value'] + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.data_store_ids == ["data_store_ids_value"] assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION assert response.industry_vertical == common.IndustryVertical.GENERIC @@ -1143,12 +1305,10 @@ def test_update_engine_field_headers(): # a field header. Set these to a non-empty value. request = engine_service.UpdateEngineRequest() - request.engine.name = 'name_value' + request.engine.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.update_engine), "__call__") as call: call.return_value = gcd_engine.Engine() client.update_engine(request) @@ -1160,9 +1320,9 @@ def test_update_engine_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'engine.name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "engine.name=name_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -1175,12 +1335,10 @@ async def test_update_engine_field_headers_async(): # a field header. Set these to a non-empty value. request = engine_service.UpdateEngineRequest() - request.engine.name = 'name_value' + request.engine.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.update_engine), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_engine.Engine()) await client.update_engine(request) @@ -1192,9 +1350,9 @@ async def test_update_engine_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'engine.name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "engine.name=name_value", + ) in kw["metadata"] def test_update_engine_flattened(): @@ -1203,16 +1361,14 @@ def test_update_engine_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.update_engine), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcd_engine.Engine() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_engine( engine=gcd_engine.Engine(similar_documents_config=None), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -1223,7 +1379,7 @@ def test_update_engine_flattened(): mock_val = gcd_engine.Engine(similar_documents_config=None) assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @@ -1238,9 +1394,10 @@ def test_update_engine_flattened_error(): client.update_engine( engine_service.UpdateEngineRequest(), engine=gcd_engine.Engine(similar_documents_config=None), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) + @pytest.mark.asyncio async def test_update_engine_flattened_async(): client = EngineServiceAsyncClient( @@ -1248,9 +1405,7 @@ async def test_update_engine_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.update_engine), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = gcd_engine.Engine() @@ -1259,7 +1414,7 @@ async def test_update_engine_flattened_async(): # using the keyword arguments to the method. response = await client.update_engine( engine=gcd_engine.Engine(similar_documents_config=None), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected @@ -1270,9 +1425,10 @@ async def test_update_engine_flattened_async(): mock_val = gcd_engine.Engine(similar_documents_config=None) assert arg == mock_val arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val + @pytest.mark.asyncio async def test_update_engine_flattened_error_async(): client = EngineServiceAsyncClient( @@ -1285,15 +1441,18 @@ async def test_update_engine_flattened_error_async(): await client.update_engine( engine_service.UpdateEngineRequest(), engine=gcd_engine.Engine(similar_documents_config=None), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -@pytest.mark.parametrize("request_type", [ - engine_service.GetEngineRequest, - dict, -]) -def test_get_engine(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + engine_service.GetEngineRequest, + dict, + ], +) +def test_get_engine(request_type, transport: str = "grpc"): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1304,14 +1463,12 @@ def test_get_engine(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_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.get_engine), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = engine.Engine( - name='name_value', - display_name='display_name_value', - data_store_ids=['data_store_ids_value'], + name="name_value", + display_name="display_name_value", + data_store_ids=["data_store_ids_value"], solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, industry_vertical=common.IndustryVertical.GENERIC, ) @@ -1324,9 +1481,9 @@ def test_get_engine(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, engine.Engine) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.data_store_ids == ['data_store_ids_value'] + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.data_store_ids == ["data_store_ids_value"] assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION assert response.industry_vertical == common.IndustryVertical.GENERIC @@ -1336,20 +1493,21 @@ def test_get_engine_empty_call(): # i.e. request == None and no flattened fields passed, work. client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.get_engine), "__call__") as call: client.get_engine() call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == engine_service.GetEngineRequest() + @pytest.mark.asyncio -async def test_get_engine_async(transport: str = 'grpc_asyncio', request_type=engine_service.GetEngineRequest): +async def test_get_engine_async( + transport: str = "grpc_asyncio", request_type=engine_service.GetEngineRequest +): client = EngineServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1360,17 +1518,17 @@ async def test_get_engine_async(transport: str = 'grpc_asyncio', request_type=en request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.get_engine), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(engine.Engine( - name='name_value', - display_name='display_name_value', - data_store_ids=['data_store_ids_value'], - solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, - industry_vertical=common.IndustryVertical.GENERIC, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + engine.Engine( + name="name_value", + display_name="display_name_value", + data_store_ids=["data_store_ids_value"], + solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, + industry_vertical=common.IndustryVertical.GENERIC, + ) + ) response = await client.get_engine(request) # Establish that the underlying gRPC stub method was called. @@ -1380,9 +1538,9 @@ async def test_get_engine_async(transport: str = 'grpc_asyncio', request_type=en # Establish that the response is the type that we expect. assert isinstance(response, engine.Engine) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.data_store_ids == ['data_store_ids_value'] + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.data_store_ids == ["data_store_ids_value"] assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION assert response.industry_vertical == common.IndustryVertical.GENERIC @@ -1401,12 +1559,10 @@ def test_get_engine_field_headers(): # a field header. Set these to a non-empty value. request = engine_service.GetEngineRequest() - request.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.get_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.get_engine), "__call__") as call: call.return_value = engine.Engine() client.get_engine(request) @@ -1418,9 +1574,9 @@ def test_get_engine_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -1433,12 +1589,10 @@ async def test_get_engine_field_headers_async(): # a field header. Set these to a non-empty value. request = engine_service.GetEngineRequest() - request.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.get_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.get_engine), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(engine.Engine()) await client.get_engine(request) @@ -1450,9 +1604,9 @@ async def test_get_engine_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] def test_get_engine_flattened(): @@ -1461,15 +1615,13 @@ def test_get_engine_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.get_engine), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = engine.Engine() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_engine( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1477,7 +1629,7 @@ def test_get_engine_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val @@ -1491,9 +1643,10 @@ def test_get_engine_flattened_error(): with pytest.raises(ValueError): client.get_engine( engine_service.GetEngineRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_get_engine_flattened_async(): client = EngineServiceAsyncClient( @@ -1501,9 +1654,7 @@ async def test_get_engine_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.get_engine), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = engine.Engine() @@ -1511,7 +1662,7 @@ async def test_get_engine_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_engine( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -1519,9 +1670,10 @@ async def test_get_engine_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val + @pytest.mark.asyncio async def test_get_engine_flattened_error_async(): client = EngineServiceAsyncClient( @@ -1533,15 +1685,18 @@ async def test_get_engine_flattened_error_async(): with pytest.raises(ValueError): await client.get_engine( engine_service.GetEngineRequest(), - name='name_value', + name="name_value", ) -@pytest.mark.parametrize("request_type", [ - engine_service.ListEnginesRequest, - dict, -]) -def test_list_engines(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + engine_service.ListEnginesRequest, + dict, + ], +) +def test_list_engines(request_type, transport: str = "grpc"): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1552,12 +1707,10 @@ def test_list_engines(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_engines), - '__call__') as call: + with mock.patch.object(type(client.transport.list_engines), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = engine_service.ListEnginesResponse( - next_page_token='next_page_token_value', + next_page_token="next_page_token_value", ) response = client.list_engines(request) @@ -1568,7 +1721,7 @@ def test_list_engines(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListEnginesPager) - assert response.next_page_token == 'next_page_token_value' + assert response.next_page_token == "next_page_token_value" def test_list_engines_empty_call(): @@ -1576,20 +1729,21 @@ def test_list_engines_empty_call(): # i.e. request == None and no flattened fields passed, work. client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_engines), - '__call__') as call: + with mock.patch.object(type(client.transport.list_engines), "__call__") as call: client.list_engines() call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == engine_service.ListEnginesRequest() + @pytest.mark.asyncio -async def test_list_engines_async(transport: str = 'grpc_asyncio', request_type=engine_service.ListEnginesRequest): +async def test_list_engines_async( + transport: str = "grpc_asyncio", request_type=engine_service.ListEnginesRequest +): client = EngineServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1600,13 +1754,13 @@ async def test_list_engines_async(transport: str = 'grpc_asyncio', request_type= request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_engines), - '__call__') as call: + with mock.patch.object(type(client.transport.list_engines), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(engine_service.ListEnginesResponse( - next_page_token='next_page_token_value', - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + engine_service.ListEnginesResponse( + next_page_token="next_page_token_value", + ) + ) response = await client.list_engines(request) # Establish that the underlying gRPC stub method was called. @@ -1616,7 +1770,7 @@ async def test_list_engines_async(transport: str = 'grpc_asyncio', request_type= # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListEnginesAsyncPager) - assert response.next_page_token == 'next_page_token_value' + assert response.next_page_token == "next_page_token_value" @pytest.mark.asyncio @@ -1633,12 +1787,10 @@ def test_list_engines_field_headers(): # a field header. Set these to a non-empty value. request = engine_service.ListEnginesRequest() - request.parent = 'parent_value' + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_engines), - '__call__') as call: + with mock.patch.object(type(client.transport.list_engines), "__call__") as call: call.return_value = engine_service.ListEnginesResponse() client.list_engines(request) @@ -1650,9 +1802,9 @@ def test_list_engines_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -1665,13 +1817,13 @@ async def test_list_engines_field_headers_async(): # a field header. Set these to a non-empty value. request = engine_service.ListEnginesRequest() - request.parent = 'parent_value' + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_engines), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(engine_service.ListEnginesResponse()) + with mock.patch.object(type(client.transport.list_engines), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + engine_service.ListEnginesResponse() + ) await client.list_engines(request) # Establish that the underlying gRPC stub method was called. @@ -1682,9 +1834,9 @@ async def test_list_engines_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] def test_list_engines_flattened(): @@ -1693,15 +1845,13 @@ def test_list_engines_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_engines), - '__call__') as call: + with mock.patch.object(type(client.transport.list_engines), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = engine_service.ListEnginesResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_engines( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -1709,7 +1859,7 @@ def test_list_engines_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val @@ -1723,9 +1873,10 @@ def test_list_engines_flattened_error(): with pytest.raises(ValueError): client.list_engines( engine_service.ListEnginesRequest(), - parent='parent_value', + parent="parent_value", ) + @pytest.mark.asyncio async def test_list_engines_flattened_async(): client = EngineServiceAsyncClient( @@ -1733,17 +1884,17 @@ async def test_list_engines_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_engines), - '__call__') as call: + with mock.patch.object(type(client.transport.list_engines), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = engine_service.ListEnginesResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(engine_service.ListEnginesResponse()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + engine_service.ListEnginesResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.list_engines( - parent='parent_value', + parent="parent_value", ) # Establish that the underlying call was made with the expected @@ -1751,9 +1902,10 @@ async def test_list_engines_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].parent - mock_val = 'parent_value' + mock_val = "parent_value" assert arg == mock_val + @pytest.mark.asyncio async def test_list_engines_flattened_error_async(): client = EngineServiceAsyncClient( @@ -1765,7 +1917,7 @@ async def test_list_engines_flattened_error_async(): with pytest.raises(ValueError): await client.list_engines( engine_service.ListEnginesRequest(), - parent='parent_value', + parent="parent_value", ) @@ -1776,9 +1928,7 @@ def test_list_engines_pager(transport_name: str = "grpc"): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_engines), - '__call__') as call: + with mock.patch.object(type(client.transport.list_engines), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( engine_service.ListEnginesResponse( @@ -1787,17 +1937,17 @@ def test_list_engines_pager(transport_name: str = "grpc"): engine.Engine(), engine.Engine(), ], - next_page_token='abc', + next_page_token="abc", ), engine_service.ListEnginesResponse( engines=[], - next_page_token='def', + next_page_token="def", ), engine_service.ListEnginesResponse( engines=[ engine.Engine(), ], - next_page_token='ghi', + next_page_token="ghi", ), engine_service.ListEnginesResponse( engines=[ @@ -1810,9 +1960,7 @@ def test_list_engines_pager(transport_name: str = "grpc"): metadata = () metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), ) pager = client.list_engines(request={}) @@ -1820,8 +1968,9 @@ def test_list_engines_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, engine.Engine) - for i in results) + assert all(isinstance(i, engine.Engine) for i in results) + + def test_list_engines_pages(transport_name: str = "grpc"): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials, @@ -1829,9 +1978,7 @@ def test_list_engines_pages(transport_name: str = "grpc"): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_engines), - '__call__') as call: + with mock.patch.object(type(client.transport.list_engines), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( engine_service.ListEnginesResponse( @@ -1840,17 +1987,17 @@ def test_list_engines_pages(transport_name: str = "grpc"): engine.Engine(), engine.Engine(), ], - next_page_token='abc', + next_page_token="abc", ), engine_service.ListEnginesResponse( engines=[], - next_page_token='def', + next_page_token="def", ), engine_service.ListEnginesResponse( engines=[ engine.Engine(), ], - next_page_token='ghi', + next_page_token="ghi", ), engine_service.ListEnginesResponse( engines=[ @@ -1861,9 +2008,10 @@ def test_list_engines_pages(transport_name: str = "grpc"): RuntimeError, ) pages = list(client.list_engines(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token + @pytest.mark.asyncio async def test_list_engines_async_pager(): client = EngineServiceAsyncClient( @@ -1872,8 +2020,8 @@ async def test_list_engines_async_pager(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_engines), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_engines), "__call__", new_callable=mock.AsyncMock + ) as call: # Set the response to a series of pages. call.side_effect = ( engine_service.ListEnginesResponse( @@ -1882,17 +2030,17 @@ async def test_list_engines_async_pager(): engine.Engine(), engine.Engine(), ], - next_page_token='abc', + next_page_token="abc", ), engine_service.ListEnginesResponse( engines=[], - next_page_token='def', + next_page_token="def", ), engine_service.ListEnginesResponse( engines=[ engine.Engine(), ], - next_page_token='ghi', + next_page_token="ghi", ), engine_service.ListEnginesResponse( engines=[ @@ -1902,15 +2050,16 @@ async def test_list_engines_async_pager(): ), RuntimeError, ) - async_pager = await client.list_engines(request={},) - assert async_pager.next_page_token == 'abc' + async_pager = await client.list_engines( + request={}, + ) + assert async_pager.next_page_token == "abc" responses = [] - async for response in async_pager: # pragma: no branch + async for response in async_pager: # pragma: no branch responses.append(response) assert len(responses) == 6 - assert all(isinstance(i, engine.Engine) - for i in responses) + assert all(isinstance(i, engine.Engine) for i in responses) @pytest.mark.asyncio @@ -1921,8 +2070,8 @@ async def test_list_engines_async_pages(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_engines), - '__call__', new_callable=mock.AsyncMock) as call: + type(client.transport.list_engines), "__call__", new_callable=mock.AsyncMock + ) as call: # Set the response to a series of pages. call.side_effect = ( engine_service.ListEnginesResponse( @@ -1931,17 +2080,17 @@ async def test_list_engines_async_pages(): engine.Engine(), engine.Engine(), ], - next_page_token='abc', + next_page_token="abc", ), engine_service.ListEnginesResponse( engines=[], - next_page_token='def', + next_page_token="def", ), engine_service.ListEnginesResponse( engines=[ engine.Engine(), ], - next_page_token='ghi', + next_page_token="ghi", ), engine_service.ListEnginesResponse( engines=[ @@ -1954,18 +2103,22 @@ async def test_list_engines_async_pages(): pages = [] # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch + async for page_ in ( # pragma: no branch await client.list_engines(request={}) ).pages: pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize("request_type", [ - engine_service.PauseEngineRequest, - dict, -]) -def test_pause_engine(request_type, transport: str = 'grpc'): + +@pytest.mark.parametrize( + "request_type", + [ + engine_service.PauseEngineRequest, + dict, + ], +) +def test_pause_engine(request_type, transport: str = "grpc"): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1976,14 +2129,12 @@ def test_pause_engine(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.pause_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.pause_engine), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = engine.Engine( - name='name_value', - display_name='display_name_value', - data_store_ids=['data_store_ids_value'], + name="name_value", + display_name="display_name_value", + data_store_ids=["data_store_ids_value"], solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, industry_vertical=common.IndustryVertical.GENERIC, ) @@ -1996,9 +2147,9 @@ def test_pause_engine(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, engine.Engine) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.data_store_ids == ['data_store_ids_value'] + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.data_store_ids == ["data_store_ids_value"] assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION assert response.industry_vertical == common.IndustryVertical.GENERIC @@ -2008,20 +2159,21 @@ def test_pause_engine_empty_call(): # i.e. request == None and no flattened fields passed, work. client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.pause_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.pause_engine), "__call__") as call: client.pause_engine() call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == engine_service.PauseEngineRequest() + @pytest.mark.asyncio -async def test_pause_engine_async(transport: str = 'grpc_asyncio', request_type=engine_service.PauseEngineRequest): +async def test_pause_engine_async( + transport: str = "grpc_asyncio", request_type=engine_service.PauseEngineRequest +): client = EngineServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2032,17 +2184,17 @@ async def test_pause_engine_async(transport: str = 'grpc_asyncio', request_type= request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.pause_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.pause_engine), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(engine.Engine( - name='name_value', - display_name='display_name_value', - data_store_ids=['data_store_ids_value'], - solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, - industry_vertical=common.IndustryVertical.GENERIC, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + engine.Engine( + name="name_value", + display_name="display_name_value", + data_store_ids=["data_store_ids_value"], + solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, + industry_vertical=common.IndustryVertical.GENERIC, + ) + ) response = await client.pause_engine(request) # Establish that the underlying gRPC stub method was called. @@ -2052,9 +2204,9 @@ async def test_pause_engine_async(transport: str = 'grpc_asyncio', request_type= # Establish that the response is the type that we expect. assert isinstance(response, engine.Engine) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.data_store_ids == ['data_store_ids_value'] + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.data_store_ids == ["data_store_ids_value"] assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION assert response.industry_vertical == common.IndustryVertical.GENERIC @@ -2073,12 +2225,10 @@ def test_pause_engine_field_headers(): # a field header. Set these to a non-empty value. request = engine_service.PauseEngineRequest() - request.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.pause_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.pause_engine), "__call__") as call: call.return_value = engine.Engine() client.pause_engine(request) @@ -2090,9 +2240,9 @@ def test_pause_engine_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -2105,12 +2255,10 @@ async def test_pause_engine_field_headers_async(): # a field header. Set these to a non-empty value. request = engine_service.PauseEngineRequest() - request.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.pause_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.pause_engine), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(engine.Engine()) await client.pause_engine(request) @@ -2122,9 +2270,9 @@ async def test_pause_engine_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] def test_pause_engine_flattened(): @@ -2133,15 +2281,13 @@ def test_pause_engine_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.pause_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.pause_engine), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = engine.Engine() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.pause_engine( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -2149,7 +2295,7 @@ def test_pause_engine_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val @@ -2163,9 +2309,10 @@ def test_pause_engine_flattened_error(): with pytest.raises(ValueError): client.pause_engine( engine_service.PauseEngineRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_pause_engine_flattened_async(): client = EngineServiceAsyncClient( @@ -2173,9 +2320,7 @@ async def test_pause_engine_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.pause_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.pause_engine), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = engine.Engine() @@ -2183,7 +2328,7 @@ async def test_pause_engine_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.pause_engine( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -2191,9 +2336,10 @@ async def test_pause_engine_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val + @pytest.mark.asyncio async def test_pause_engine_flattened_error_async(): client = EngineServiceAsyncClient( @@ -2205,15 +2351,18 @@ async def test_pause_engine_flattened_error_async(): with pytest.raises(ValueError): await client.pause_engine( engine_service.PauseEngineRequest(), - name='name_value', + name="name_value", ) -@pytest.mark.parametrize("request_type", [ - engine_service.ResumeEngineRequest, - dict, -]) -def test_resume_engine(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + engine_service.ResumeEngineRequest, + dict, + ], +) +def test_resume_engine(request_type, transport: str = "grpc"): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2224,14 +2373,12 @@ def test_resume_engine(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.resume_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.resume_engine), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = engine.Engine( - name='name_value', - display_name='display_name_value', - data_store_ids=['data_store_ids_value'], + name="name_value", + display_name="display_name_value", + data_store_ids=["data_store_ids_value"], solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, industry_vertical=common.IndustryVertical.GENERIC, ) @@ -2244,9 +2391,9 @@ def test_resume_engine(request_type, transport: str = 'grpc'): # Establish that the response is the type that we expect. assert isinstance(response, engine.Engine) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.data_store_ids == ['data_store_ids_value'] + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.data_store_ids == ["data_store_ids_value"] assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION assert response.industry_vertical == common.IndustryVertical.GENERIC @@ -2256,20 +2403,21 @@ def test_resume_engine_empty_call(): # i.e. request == None and no flattened fields passed, work. client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.resume_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.resume_engine), "__call__") as call: client.resume_engine() call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == engine_service.ResumeEngineRequest() + @pytest.mark.asyncio -async def test_resume_engine_async(transport: str = 'grpc_asyncio', request_type=engine_service.ResumeEngineRequest): +async def test_resume_engine_async( + transport: str = "grpc_asyncio", request_type=engine_service.ResumeEngineRequest +): client = EngineServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2280,17 +2428,17 @@ async def test_resume_engine_async(transport: str = 'grpc_asyncio', request_type request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.resume_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.resume_engine), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(engine.Engine( - name='name_value', - display_name='display_name_value', - data_store_ids=['data_store_ids_value'], - solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, - industry_vertical=common.IndustryVertical.GENERIC, - )) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + engine.Engine( + name="name_value", + display_name="display_name_value", + data_store_ids=["data_store_ids_value"], + solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, + industry_vertical=common.IndustryVertical.GENERIC, + ) + ) response = await client.resume_engine(request) # Establish that the underlying gRPC stub method was called. @@ -2300,9 +2448,9 @@ async def test_resume_engine_async(transport: str = 'grpc_asyncio', request_type # Establish that the response is the type that we expect. assert isinstance(response, engine.Engine) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.data_store_ids == ['data_store_ids_value'] + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.data_store_ids == ["data_store_ids_value"] assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION assert response.industry_vertical == common.IndustryVertical.GENERIC @@ -2321,12 +2469,10 @@ def test_resume_engine_field_headers(): # a field header. Set these to a non-empty value. request = engine_service.ResumeEngineRequest() - request.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.resume_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.resume_engine), "__call__") as call: call.return_value = engine.Engine() client.resume_engine(request) @@ -2338,9 +2484,9 @@ def test_resume_engine_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -2353,12 +2499,10 @@ async def test_resume_engine_field_headers_async(): # a field header. Set these to a non-empty value. request = engine_service.ResumeEngineRequest() - request.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.resume_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.resume_engine), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(engine.Engine()) await client.resume_engine(request) @@ -2370,9 +2514,9 @@ async def test_resume_engine_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] def test_resume_engine_flattened(): @@ -2381,15 +2525,13 @@ def test_resume_engine_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.resume_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.resume_engine), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = engine.Engine() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.resume_engine( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -2397,7 +2539,7 @@ def test_resume_engine_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val @@ -2411,9 +2553,10 @@ def test_resume_engine_flattened_error(): with pytest.raises(ValueError): client.resume_engine( engine_service.ResumeEngineRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_resume_engine_flattened_async(): client = EngineServiceAsyncClient( @@ -2421,9 +2564,7 @@ async def test_resume_engine_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.resume_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.resume_engine), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = engine.Engine() @@ -2431,7 +2572,7 @@ async def test_resume_engine_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.resume_engine( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -2439,9 +2580,10 @@ async def test_resume_engine_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val + @pytest.mark.asyncio async def test_resume_engine_flattened_error_async(): client = EngineServiceAsyncClient( @@ -2453,15 +2595,18 @@ async def test_resume_engine_flattened_error_async(): with pytest.raises(ValueError): await client.resume_engine( engine_service.ResumeEngineRequest(), - name='name_value', + name="name_value", ) -@pytest.mark.parametrize("request_type", [ - engine_service.TuneEngineRequest, - dict, -]) -def test_tune_engine(request_type, transport: str = 'grpc'): +@pytest.mark.parametrize( + "request_type", + [ + engine_service.TuneEngineRequest, + dict, + ], +) +def test_tune_engine(request_type, transport: str = "grpc"): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2472,11 +2617,9 @@ def test_tune_engine(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.tune_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.tune_engine), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') + call.return_value = operations_pb2.Operation(name="operations/spam") response = client.tune_engine(request) # Establish that the underlying gRPC stub method was called. @@ -2493,20 +2636,21 @@ def test_tune_engine_empty_call(): # i.e. request == None and no flattened fields passed, work. client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.tune_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.tune_engine), "__call__") as call: client.tune_engine() call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == engine_service.TuneEngineRequest() + @pytest.mark.asyncio -async def test_tune_engine_async(transport: str = 'grpc_asyncio', request_type=engine_service.TuneEngineRequest): +async def test_tune_engine_async( + transport: str = "grpc_asyncio", request_type=engine_service.TuneEngineRequest +): client = EngineServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2517,12 +2661,10 @@ async def test_tune_engine_async(transport: str = 'grpc_asyncio', request_type=e request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.tune_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.tune_engine), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + operations_pb2.Operation(name="operations/spam") ) response = await client.tune_engine(request) @@ -2549,13 +2691,11 @@ def test_tune_engine_field_headers(): # a field header. Set these to a non-empty value. request = engine_service.TuneEngineRequest() - request.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.tune_engine), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') + with mock.patch.object(type(client.transport.tune_engine), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") client.tune_engine(request) # Establish that the underlying gRPC stub method was called. @@ -2566,9 +2706,9 @@ def test_tune_engine_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] @pytest.mark.asyncio @@ -2581,13 +2721,13 @@ async def test_tune_engine_field_headers_async(): # a field header. Set these to a non-empty value. request = engine_service.TuneEngineRequest() - request.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.tune_engine), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + with mock.patch.object(type(client.transport.tune_engine), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) await client.tune_engine(request) # Establish that the underlying gRPC stub method was called. @@ -2598,9 +2738,9 @@ async def test_tune_engine_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] def test_tune_engine_flattened(): @@ -2609,15 +2749,13 @@ def test_tune_engine_flattened(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.tune_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.tune_engine), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + 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.tune_engine( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -2625,7 +2763,7 @@ def test_tune_engine_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val @@ -2639,9 +2777,10 @@ def test_tune_engine_flattened_error(): with pytest.raises(ValueError): client.tune_engine( engine_service.TuneEngineRequest(), - name='name_value', + name="name_value", ) + @pytest.mark.asyncio async def test_tune_engine_flattened_async(): client = EngineServiceAsyncClient( @@ -2649,19 +2788,17 @@ async def test_tune_engine_flattened_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.tune_engine), - '__call__') as call: + with mock.patch.object(type(client.transport.tune_engine), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') + 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.tune_engine( - name='name_value', + name="name_value", ) # Establish that the underlying call was made with the expected @@ -2669,9 +2806,10 @@ async def test_tune_engine_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].name - mock_val = 'name_value' + mock_val = "name_value" assert arg == mock_val + @pytest.mark.asyncio async def test_tune_engine_flattened_error_async(): client = EngineServiceAsyncClient( @@ -2683,14 +2821,17 @@ async def test_tune_engine_flattened_error_async(): with pytest.raises(ValueError): await client.tune_engine( engine_service.TuneEngineRequest(), - name='name_value', + name="name_value", ) -@pytest.mark.parametrize("request_type", [ - engine_service.CreateEngineRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + engine_service.CreateEngineRequest, + dict, + ], +) def test_create_engine_rest(request_type): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2698,8 +2839,43 @@ def test_create_engine_rest(request_type): ) # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/collections/sample3'} - request_init["engine"] = {'similar_documents_config': {}, 'chat_engine_config': {'agent_creation_config': {'business': 'business_value', 'default_language_code': 'default_language_code_value', 'time_zone': 'time_zone_value'}, 'dialogflow_agent_to_link': 'dialogflow_agent_to_link_value'}, 'search_engine_config': {'search_tier': 1, 'search_add_ons': [1]}, 'media_recommendation_engine_config': {'type_': 'type__value', 'optimization_objective': 'optimization_objective_value', 'optimization_objective_config': {'target_field': 'target_field_value', 'target_field_value_float': 0.2523}, 'training_state': 1}, 'recommendation_metadata': {'serving_state': 1, 'data_state': 1, 'last_tune_time': {'seconds': 751, 'nanos': 543}, 'tuning_operation': 'tuning_operation_value'}, 'chat_engine_metadata': {'dialogflow_agent': 'dialogflow_agent_value'}, 'name': 'name_value', 'display_name': 'display_name_value', 'create_time': {}, 'update_time': {}, 'data_store_ids': ['data_store_ids_value1', 'data_store_ids_value2'], 'solution_type': 1, 'industry_vertical': 1, 'common_config': {'company_name': 'company_name_value'}} + request_init = {"parent": "projects/sample1/locations/sample2/collections/sample3"} + request_init["engine"] = { + "similar_documents_config": {}, + "chat_engine_config": { + "agent_creation_config": { + "business": "business_value", + "default_language_code": "default_language_code_value", + "time_zone": "time_zone_value", + }, + "dialogflow_agent_to_link": "dialogflow_agent_to_link_value", + }, + "search_engine_config": {"search_tier": 1, "search_add_ons": [1]}, + "media_recommendation_engine_config": { + "type_": "type__value", + "optimization_objective": "optimization_objective_value", + "optimization_objective_config": { + "target_field": "target_field_value", + "target_field_value_float": 0.2523, + }, + "training_state": 1, + }, + "recommendation_metadata": { + "serving_state": 1, + "data_state": 1, + "last_tune_time": {"seconds": 751, "nanos": 543}, + "tuning_operation": "tuning_operation_value", + }, + "chat_engine_metadata": {"dialogflow_agent": "dialogflow_agent_value"}, + "name": "name_value", + "display_name": "display_name_value", + "create_time": {}, + "update_time": {}, + "data_store_ids": ["data_store_ids_value1", "data_store_ids_value2"], + "solution_type": 1, + "industry_vertical": 1, + "common_config": {"company_name": "company_name_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 @@ -2719,7 +2895,7 @@ def get_message_fields(field): 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 + else: # pragma: NO COVER message_fields = field.message.DESCRIPTOR.fields return message_fields @@ -2733,7 +2909,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["engine"].items(): # pragma: NO COVER + for field, value in request_init["engine"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -2748,12 +2924,16 @@ def get_message_fields(field): 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} + { + "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 + 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") @@ -2766,16 +2946,16 @@ def get_message_fields(field): request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.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 = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.create_engine(request) @@ -2783,7 +2963,9 @@ def get_message_fields(field): assert response.operation.name == "operations/spam" -def test_create_engine_rest_required_fields(request_type=engine_service.CreateEngineRequest): +def test_create_engine_rest_required_fields( + request_type=engine_service.CreateEngineRequest, +): transport_class = transports.EngineServiceRestTransport request_init = {} @@ -2791,66 +2973,72 @@ def test_create_engine_rest_required_fields(request_type=engine_service.CreateEn request_init["engine_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) # verify fields with default values are dropped assert "engineId" not in jsonified_request - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_engine._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_engine._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present assert "engineId" in jsonified_request assert jsonified_request["engineId"] == request_init["engine_id"] - jsonified_request["parent"] = 'parent_value' - jsonified_request["engineId"] = 'engine_id_value' + jsonified_request["parent"] = "parent_value" + jsonified_request["engineId"] = "engine_id_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_engine._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_engine._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("engine_id", )) + assert not set(unset_fields) - set(("engine_id",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' + assert jsonified_request["parent"] == "parent_value" assert "engineId" in jsonified_request - assert jsonified_request["engineId"] == 'engine_id_value' + assert jsonified_request["engineId"] == "engine_id_value" client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + 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: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force 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, + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, } - transcode_result['body'] = 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') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.create_engine(request) @@ -2860,34 +3048,55 @@ def test_create_engine_rest_required_fields(request_type=engine_service.CreateEn "engineId", "", ), - ('$alt', 'json;enum-encoding=int') + ("$alt", "json;enum-encoding=int"), ] - actual_params = req.call_args.kwargs['params'] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_create_engine_rest_unset_required_fields(): - transport = transports.EngineServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.EngineServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.create_engine._get_unset_required_fields({}) - assert set(unset_fields) == (set(("engineId", )) & set(("parent", "engine", "engineId", ))) + assert set(unset_fields) == ( + set(("engineId",)) + & set( + ( + "parent", + "engine", + "engineId", + ) + ) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) def test_create_engine_rest_interceptors(null_interceptor): transport = transports.EngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EngineServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.EngineServiceRestInterceptor(), + ) client = EngineServiceClient(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.EngineServiceRestInterceptor, "post_create_engine") as post, \ - mock.patch.object(transports.EngineServiceRestInterceptor, "pre_create_engine") as pre: + 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.EngineServiceRestInterceptor, "post_create_engine" + ) as post, mock.patch.object( + transports.EngineServiceRestInterceptor, "pre_create_engine" + ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = engine_service.CreateEngineRequest.pb(engine_service.CreateEngineRequest()) + pb_message = engine_service.CreateEngineRequest.pb( + engine_service.CreateEngineRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2898,34 +3107,46 @@ def test_create_engine_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) request = engine_service.CreateEngineRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.create_engine(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.create_engine( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() -def test_create_engine_rest_bad_request(transport: str = 'rest', request_type=engine_service.CreateEngineRequest): +def test_create_engine_rest_bad_request( + transport: str = "rest", request_type=engine_service.CreateEngineRequest +): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/collections/sample3'} + request_init = {"parent": "projects/sample1/locations/sample2/collections/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): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 400 @@ -2941,18 +3162,20 @@ def test_create_engine_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: + with mock.patch.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 = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/collections/sample3'} + sample_request = { + "parent": "projects/sample1/locations/sample2/collections/sample3" + } # get truthy value for each flattened field mock_args = dict( - parent='parent_value', + parent="parent_value", engine=gcd_engine.Engine(similar_documents_config=None), - engine_id='engine_id_value', + engine_id="engine_id_value", ) mock_args.update(sample_request) @@ -2960,7 +3183,7 @@ def test_create_engine_rest_flattened(): response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value client.create_engine(**mock_args) @@ -2969,10 +3192,14 @@ def test_create_engine_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1alpha/{parent=projects/*/locations/*/collections/*}/engines" % client.transport._host, args[1]) + assert path_template.validate( + "%s/v1alpha/{parent=projects/*/locations/*/collections/*}/engines" + % client.transport._host, + args[1], + ) -def test_create_engine_rest_flattened_error(transport: str = 'rest'): +def test_create_engine_rest_flattened_error(transport: str = "rest"): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2983,23 +3210,25 @@ def test_create_engine_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.create_engine( engine_service.CreateEngineRequest(), - parent='parent_value', + parent="parent_value", engine=gcd_engine.Engine(similar_documents_config=None), - engine_id='engine_id_value', + engine_id="engine_id_value", ) def test_create_engine_rest_error(): client = EngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) -@pytest.mark.parametrize("request_type", [ - engine_service.DeleteEngineRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + engine_service.DeleteEngineRequest, + dict, + ], +) def test_delete_engine_rest(request_type): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3007,20 +3236,22 @@ def test_delete_engine_rest(request_type): ) # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/engines/sample4'} + request_init = { + "name": "projects/sample1/locations/sample2/collections/sample3/engines/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: + with mock.patch.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 = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.delete_engine(request) @@ -3028,56 +3259,64 @@ def test_delete_engine_rest(request_type): assert response.operation.name == "operations/spam" -def test_delete_engine_rest_required_fields(request_type=engine_service.DeleteEngineRequest): +def test_delete_engine_rest_required_fields( + request_type=engine_service.DeleteEngineRequest, +): transport_class = transports.EngineServiceRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_engine._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_engine._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = 'name_value' + jsonified_request["name"] = "name_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_engine._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_engine._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' + assert jsonified_request["name"] == "name_value" client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + 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: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force 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, + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, } transcode.return_value = transcode_result @@ -3085,40 +3324,50 @@ def test_delete_engine_rest_required_fields(request_type=engine_service.DeleteEn response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.delete_engine(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_delete_engine_rest_unset_required_fields(): - transport = transports.EngineServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.EngineServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.delete_engine._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) def test_delete_engine_rest_interceptors(null_interceptor): transport = transports.EngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EngineServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.EngineServiceRestInterceptor(), + ) client = EngineServiceClient(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.EngineServiceRestInterceptor, "post_delete_engine") as post, \ - mock.patch.object(transports.EngineServiceRestInterceptor, "pre_delete_engine") as pre: + 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.EngineServiceRestInterceptor, "post_delete_engine" + ) as post, mock.patch.object( + transports.EngineServiceRestInterceptor, "pre_delete_engine" + ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = engine_service.DeleteEngineRequest.pb(engine_service.DeleteEngineRequest()) + pb_message = engine_service.DeleteEngineRequest.pb( + engine_service.DeleteEngineRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -3129,34 +3378,48 @@ def test_delete_engine_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) request = engine_service.DeleteEngineRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.delete_engine(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.delete_engine( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() -def test_delete_engine_rest_bad_request(transport: str = 'rest', request_type=engine_service.DeleteEngineRequest): +def test_delete_engine_rest_bad_request( + transport: str = "rest", request_type=engine_service.DeleteEngineRequest +): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/engines/sample4'} + request_init = { + "name": "projects/sample1/locations/sample2/collections/sample3/engines/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): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 400 @@ -3172,16 +3435,18 @@ def test_delete_engine_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: + with mock.patch.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 = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/collections/sample3/engines/sample4'} + sample_request = { + "name": "projects/sample1/locations/sample2/collections/sample3/engines/sample4" + } # get truthy value for each flattened field mock_args = dict( - name='name_value', + name="name_value", ) mock_args.update(sample_request) @@ -3189,7 +3454,7 @@ def test_delete_engine_rest_flattened(): response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value client.delete_engine(**mock_args) @@ -3198,10 +3463,14 @@ def test_delete_engine_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}" + % client.transport._host, + args[1], + ) -def test_delete_engine_rest_flattened_error(transport: str = 'rest'): +def test_delete_engine_rest_flattened_error(transport: str = "rest"): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3212,21 +3481,23 @@ def test_delete_engine_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.delete_engine( engine_service.DeleteEngineRequest(), - name='name_value', + name="name_value", ) def test_delete_engine_rest_error(): client = EngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) -@pytest.mark.parametrize("request_type", [ - engine_service.UpdateEngineRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + engine_service.UpdateEngineRequest, + dict, + ], +) def test_update_engine_rest(request_type): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3234,8 +3505,47 @@ def test_update_engine_rest(request_type): ) # send a request that will satisfy transcoding - request_init = {'engine': {'name': 'projects/sample1/locations/sample2/collections/sample3/engines/sample4'}} - request_init["engine"] = {'similar_documents_config': {}, 'chat_engine_config': {'agent_creation_config': {'business': 'business_value', 'default_language_code': 'default_language_code_value', 'time_zone': 'time_zone_value'}, 'dialogflow_agent_to_link': 'dialogflow_agent_to_link_value'}, 'search_engine_config': {'search_tier': 1, 'search_add_ons': [1]}, 'media_recommendation_engine_config': {'type_': 'type__value', 'optimization_objective': 'optimization_objective_value', 'optimization_objective_config': {'target_field': 'target_field_value', 'target_field_value_float': 0.2523}, 'training_state': 1}, 'recommendation_metadata': {'serving_state': 1, 'data_state': 1, 'last_tune_time': {'seconds': 751, 'nanos': 543}, 'tuning_operation': 'tuning_operation_value'}, 'chat_engine_metadata': {'dialogflow_agent': 'dialogflow_agent_value'}, 'name': 'projects/sample1/locations/sample2/collections/sample3/engines/sample4', 'display_name': 'display_name_value', 'create_time': {}, 'update_time': {}, 'data_store_ids': ['data_store_ids_value1', 'data_store_ids_value2'], 'solution_type': 1, 'industry_vertical': 1, 'common_config': {'company_name': 'company_name_value'}} + request_init = { + "engine": { + "name": "projects/sample1/locations/sample2/collections/sample3/engines/sample4" + } + } + request_init["engine"] = { + "similar_documents_config": {}, + "chat_engine_config": { + "agent_creation_config": { + "business": "business_value", + "default_language_code": "default_language_code_value", + "time_zone": "time_zone_value", + }, + "dialogflow_agent_to_link": "dialogflow_agent_to_link_value", + }, + "search_engine_config": {"search_tier": 1, "search_add_ons": [1]}, + "media_recommendation_engine_config": { + "type_": "type__value", + "optimization_objective": "optimization_objective_value", + "optimization_objective_config": { + "target_field": "target_field_value", + "target_field_value_float": 0.2523, + }, + "training_state": 1, + }, + "recommendation_metadata": { + "serving_state": 1, + "data_state": 1, + "last_tune_time": {"seconds": 751, "nanos": 543}, + "tuning_operation": "tuning_operation_value", + }, + "chat_engine_metadata": {"dialogflow_agent": "dialogflow_agent_value"}, + "name": "projects/sample1/locations/sample2/collections/sample3/engines/sample4", + "display_name": "display_name_value", + "create_time": {}, + "update_time": {}, + "data_store_ids": ["data_store_ids_value1", "data_store_ids_value2"], + "solution_type": 1, + "industry_vertical": 1, + "common_config": {"company_name": "company_name_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 @@ -3255,7 +3565,7 @@ def get_message_fields(field): 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 + else: # pragma: NO COVER message_fields = field.message.DESCRIPTOR.fields return message_fields @@ -3269,7 +3579,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["engine"].items(): # pragma: NO COVER + for field, value in request_init["engine"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -3284,12 +3594,16 @@ def get_message_fields(field): 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} + { + "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 + 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") @@ -3302,14 +3616,14 @@ def get_message_fields(field): request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = gcd_engine.Engine( - name='name_value', - display_name='display_name_value', - data_store_ids=['data_store_ids_value'], - solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, - industry_vertical=common.IndustryVertical.GENERIC, + name="name_value", + display_name="display_name_value", + data_store_ids=["data_store_ids_value"], + solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, + industry_vertical=common.IndustryVertical.GENERIC, ) # Wrap the value into a proper Response obj @@ -3319,68 +3633,76 @@ def get_message_fields(field): return_value = gcd_engine.Engine.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.update_engine(request) # Establish that the response is the type that we expect. assert isinstance(response, gcd_engine.Engine) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.data_store_ids == ['data_store_ids_value'] + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.data_store_ids == ["data_store_ids_value"] assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION assert response.industry_vertical == common.IndustryVertical.GENERIC -def test_update_engine_rest_required_fields(request_type=engine_service.UpdateEngineRequest): +def test_update_engine_rest_required_fields( + request_type=engine_service.UpdateEngineRequest, +): transport_class = transports.EngineServiceRestTransport request_init = {} request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_engine._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_engine._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_engine._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_engine._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) + assert not set(unset_fields) - set(("update_mask",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = gcd_engine.Engine() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force 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, + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, } - transcode_result['body'] = pb_request + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -3390,39 +3712,48 @@ def test_update_engine_rest_required_fields(request_type=engine_service.UpdateEn return_value = gcd_engine.Engine.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.update_engine(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_update_engine_rest_unset_required_fields(): - transport = transports.EngineServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.EngineServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.update_engine._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("engine", ))) + assert set(unset_fields) == (set(("updateMask",)) & set(("engine",))) @pytest.mark.parametrize("null_interceptor", [True, False]) def test_update_engine_rest_interceptors(null_interceptor): transport = transports.EngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EngineServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.EngineServiceRestInterceptor(), + ) client = EngineServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.EngineServiceRestInterceptor, "post_update_engine") as post, \ - mock.patch.object(transports.EngineServiceRestInterceptor, "pre_update_engine") as pre: + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EngineServiceRestInterceptor, "post_update_engine" + ) as post, mock.patch.object( + transports.EngineServiceRestInterceptor, "pre_update_engine" + ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = engine_service.UpdateEngineRequest.pb(engine_service.UpdateEngineRequest()) + pb_message = engine_service.UpdateEngineRequest.pb( + engine_service.UpdateEngineRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -3436,31 +3767,45 @@ def test_update_engine_rest_interceptors(null_interceptor): req.return_value._content = gcd_engine.Engine.to_json(gcd_engine.Engine()) request = engine_service.UpdateEngineRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = gcd_engine.Engine() - client.update_engine(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.update_engine( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() -def test_update_engine_rest_bad_request(transport: str = 'rest', request_type=engine_service.UpdateEngineRequest): +def test_update_engine_rest_bad_request( + transport: str = "rest", request_type=engine_service.UpdateEngineRequest +): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # send a request that will satisfy transcoding - request_init = {'engine': {'name': 'projects/sample1/locations/sample2/collections/sample3/engines/sample4'}} + request_init = { + "engine": { + "name": "projects/sample1/locations/sample2/collections/sample3/engines/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): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 400 @@ -3476,17 +3821,21 @@ def test_update_engine_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: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = gcd_engine.Engine() # get arguments that satisfy an http rule for this method - sample_request = {'engine': {'name': 'projects/sample1/locations/sample2/collections/sample3/engines/sample4'}} + sample_request = { + "engine": { + "name": "projects/sample1/locations/sample2/collections/sample3/engines/sample4" + } + } # get truthy value for each flattened field mock_args = dict( engine=gcd_engine.Engine(similar_documents_config=None), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -3496,7 +3845,7 @@ def test_update_engine_rest_flattened(): # Convert return value to protobuf type return_value = gcd_engine.Engine.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value client.update_engine(**mock_args) @@ -3505,10 +3854,14 @@ def test_update_engine_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1alpha/{engine.name=projects/*/locations/*/collections/*/engines/*}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/v1alpha/{engine.name=projects/*/locations/*/collections/*/engines/*}" + % client.transport._host, + args[1], + ) -def test_update_engine_rest_flattened_error(transport: str = 'rest'): +def test_update_engine_rest_flattened_error(transport: str = "rest"): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3520,21 +3873,23 @@ def test_update_engine_rest_flattened_error(transport: str = 'rest'): client.update_engine( engine_service.UpdateEngineRequest(), engine=gcd_engine.Engine(similar_documents_config=None), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) def test_update_engine_rest_error(): client = EngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) -@pytest.mark.parametrize("request_type", [ - engine_service.GetEngineRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + engine_service.GetEngineRequest, + dict, + ], +) def test_get_engine_rest(request_type): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3542,18 +3897,20 @@ def test_get_engine_rest(request_type): ) # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/engines/sample4'} + request_init = { + "name": "projects/sample1/locations/sample2/collections/sample3/engines/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: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = engine.Engine( - name='name_value', - display_name='display_name_value', - data_store_ids=['data_store_ids_value'], - solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, - industry_vertical=common.IndustryVertical.GENERIC, + name="name_value", + display_name="display_name_value", + data_store_ids=["data_store_ids_value"], + solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, + industry_vertical=common.IndustryVertical.GENERIC, ) # Wrap the value into a proper Response obj @@ -3563,15 +3920,15 @@ def test_get_engine_rest(request_type): return_value = engine.Engine.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.get_engine(request) # Establish that the response is the type that we expect. assert isinstance(response, engine.Engine) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.data_store_ids == ['data_store_ids_value'] + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.data_store_ids == ["data_store_ids_value"] assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION assert response.industry_vertical == common.IndustryVertical.GENERIC @@ -3583,49 +3940,55 @@ def test_get_engine_rest_required_fields(request_type=engine_service.GetEngineRe request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_engine._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_engine._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = 'name_value' + jsonified_request["name"] = "name_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_engine._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_engine._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' + assert jsonified_request["name"] == "name_value" client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = engine.Engine() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force 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, + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, } transcode.return_value = transcode_result @@ -3636,39 +3999,48 @@ def test_get_engine_rest_required_fields(request_type=engine_service.GetEngineRe return_value = engine.Engine.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.get_engine(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_get_engine_rest_unset_required_fields(): - transport = transports.EngineServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.EngineServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.get_engine._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) def test_get_engine_rest_interceptors(null_interceptor): transport = transports.EngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EngineServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.EngineServiceRestInterceptor(), + ) client = EngineServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.EngineServiceRestInterceptor, "post_get_engine") as post, \ - mock.patch.object(transports.EngineServiceRestInterceptor, "pre_get_engine") as pre: + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EngineServiceRestInterceptor, "post_get_engine" + ) as post, mock.patch.object( + transports.EngineServiceRestInterceptor, "pre_get_engine" + ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = engine_service.GetEngineRequest.pb(engine_service.GetEngineRequest()) + pb_message = engine_service.GetEngineRequest.pb( + engine_service.GetEngineRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -3682,31 +4054,43 @@ def test_get_engine_rest_interceptors(null_interceptor): req.return_value._content = engine.Engine.to_json(engine.Engine()) request = engine_service.GetEngineRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = engine.Engine() - client.get_engine(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.get_engine( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() -def test_get_engine_rest_bad_request(transport: str = 'rest', request_type=engine_service.GetEngineRequest): +def test_get_engine_rest_bad_request( + transport: str = "rest", request_type=engine_service.GetEngineRequest +): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/engines/sample4'} + request_init = { + "name": "projects/sample1/locations/sample2/collections/sample3/engines/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): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 400 @@ -3722,16 +4106,18 @@ def test_get_engine_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: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = engine.Engine() # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/collections/sample3/engines/sample4'} + sample_request = { + "name": "projects/sample1/locations/sample2/collections/sample3/engines/sample4" + } # get truthy value for each flattened field mock_args = dict( - name='name_value', + name="name_value", ) mock_args.update(sample_request) @@ -3741,7 +4127,7 @@ def test_get_engine_rest_flattened(): # Convert return value to protobuf type return_value = engine.Engine.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value client.get_engine(**mock_args) @@ -3750,10 +4136,14 @@ def test_get_engine_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}" % client.transport._host, args[1]) + assert path_template.validate( + "%s/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}" + % client.transport._host, + args[1], + ) -def test_get_engine_rest_flattened_error(transport: str = 'rest'): +def test_get_engine_rest_flattened_error(transport: str = "rest"): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3764,21 +4154,23 @@ def test_get_engine_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.get_engine( engine_service.GetEngineRequest(), - name='name_value', + name="name_value", ) def test_get_engine_rest_error(): client = EngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) -@pytest.mark.parametrize("request_type", [ - engine_service.ListEnginesRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + engine_service.ListEnginesRequest, + dict, + ], +) def test_list_engines_rest(request_type): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3786,14 +4178,14 @@ def test_list_engines_rest(request_type): ) # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/collections/sample3'} + request_init = {"parent": "projects/sample1/locations/sample2/collections/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: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = engine_service.ListEnginesResponse( - next_page_token='next_page_token_value', + next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj @@ -3803,67 +4195,81 @@ def test_list_engines_rest(request_type): return_value = engine_service.ListEnginesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.list_engines(request) # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListEnginesPager) - assert response.next_page_token == 'next_page_token_value' + assert response.next_page_token == "next_page_token_value" -def test_list_engines_rest_required_fields(request_type=engine_service.ListEnginesRequest): +def test_list_engines_rest_required_fields( + request_type=engine_service.ListEnginesRequest, +): transport_class = transports.EngineServiceRestTransport request_init = {} request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_engines._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_engines._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = 'parent_value' + jsonified_request["parent"] = "parent_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_engines._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_engines._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) + assert not set(unset_fields) - set( + ( + "filter", + "page_size", + "page_token", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' + assert jsonified_request["parent"] == "parent_value" client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = engine_service.ListEnginesResponse() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force 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, + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, } transcode.return_value = transcode_result @@ -3874,39 +4280,57 @@ def test_list_engines_rest_required_fields(request_type=engine_service.ListEngin return_value = engine_service.ListEnginesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.list_engines(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_list_engines_rest_unset_required_fields(): - transport = transports.EngineServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.EngineServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.list_engines._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) def test_list_engines_rest_interceptors(null_interceptor): transport = transports.EngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EngineServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.EngineServiceRestInterceptor(), + ) client = EngineServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.EngineServiceRestInterceptor, "post_list_engines") as post, \ - mock.patch.object(transports.EngineServiceRestInterceptor, "pre_list_engines") as pre: + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EngineServiceRestInterceptor, "post_list_engines" + ) as post, mock.patch.object( + transports.EngineServiceRestInterceptor, "pre_list_engines" + ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = engine_service.ListEnginesRequest.pb(engine_service.ListEnginesRequest()) + pb_message = engine_service.ListEnginesRequest.pb( + engine_service.ListEnginesRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -3917,34 +4341,46 @@ def test_list_engines_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = engine_service.ListEnginesResponse.to_json(engine_service.ListEnginesResponse()) + req.return_value._content = engine_service.ListEnginesResponse.to_json( + engine_service.ListEnginesResponse() + ) request = engine_service.ListEnginesRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = engine_service.ListEnginesResponse() - client.list_engines(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.list_engines( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() -def test_list_engines_rest_bad_request(transport: str = 'rest', request_type=engine_service.ListEnginesRequest): +def test_list_engines_rest_bad_request( + transport: str = "rest", request_type=engine_service.ListEnginesRequest +): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/collections/sample3'} + request_init = {"parent": "projects/sample1/locations/sample2/collections/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): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 400 @@ -3960,16 +4396,18 @@ def test_list_engines_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: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = engine_service.ListEnginesResponse() # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/collections/sample3'} + sample_request = { + "parent": "projects/sample1/locations/sample2/collections/sample3" + } # get truthy value for each flattened field mock_args = dict( - parent='parent_value', + parent="parent_value", ) mock_args.update(sample_request) @@ -3979,7 +4417,7 @@ def test_list_engines_rest_flattened(): # Convert return value to protobuf type return_value = engine_service.ListEnginesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value client.list_engines(**mock_args) @@ -3988,10 +4426,14 @@ def test_list_engines_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1alpha/{parent=projects/*/locations/*/collections/*}/engines" % client.transport._host, args[1]) + assert path_template.validate( + "%s/v1alpha/{parent=projects/*/locations/*/collections/*}/engines" + % client.transport._host, + args[1], + ) -def test_list_engines_rest_flattened_error(transport: str = 'rest'): +def test_list_engines_rest_flattened_error(transport: str = "rest"): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4002,20 +4444,20 @@ def test_list_engines_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.list_engines( engine_service.ListEnginesRequest(), - parent='parent_value', + parent="parent_value", ) -def test_list_engines_rest_pager(transport: str = 'rest'): +def test_list_engines_rest_pager(transport: str = "rest"): client = EngineServiceClient( 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: + 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: + # with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( engine_service.ListEnginesResponse( @@ -4024,17 +4466,17 @@ def test_list_engines_rest_pager(transport: str = 'rest'): engine.Engine(), engine.Engine(), ], - next_page_token='abc', + next_page_token="abc", ), engine_service.ListEnginesResponse( engines=[], - next_page_token='def', + next_page_token="def", ), engine_service.ListEnginesResponse( engines=[ engine.Engine(), ], - next_page_token='ghi', + next_page_token="ghi", ), engine_service.ListEnginesResponse( engines=[ @@ -4047,31 +4489,37 @@ def test_list_engines_rest_pager(transport: str = 'rest'): response = response + response # Wrap the values into proper Response objs - response = tuple(engine_service.ListEnginesResponse.to_json(x) for x in response) + response = tuple( + engine_service.ListEnginesResponse.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._content = response_val.encode("UTF-8") return_val.status_code = 200 req.side_effect = return_values - sample_request = {'parent': 'projects/sample1/locations/sample2/collections/sample3'} + sample_request = { + "parent": "projects/sample1/locations/sample2/collections/sample3" + } pager = client.list_engines(request=sample_request) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, engine.Engine) - for i in results) + assert all(isinstance(i, engine.Engine) for i in results) pages = list(client.list_engines(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize("request_type", [ - engine_service.PauseEngineRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + engine_service.PauseEngineRequest, + dict, + ], +) def test_pause_engine_rest(request_type): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4079,18 +4527,20 @@ def test_pause_engine_rest(request_type): ) # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/engines/sample4'} + request_init = { + "name": "projects/sample1/locations/sample2/collections/sample3/engines/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: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = engine.Engine( - name='name_value', - display_name='display_name_value', - data_store_ids=['data_store_ids_value'], - solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, - industry_vertical=common.IndustryVertical.GENERIC, + name="name_value", + display_name="display_name_value", + data_store_ids=["data_store_ids_value"], + solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, + industry_vertical=common.IndustryVertical.GENERIC, ) # Wrap the value into a proper Response obj @@ -4100,71 +4550,79 @@ def test_pause_engine_rest(request_type): return_value = engine.Engine.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.pause_engine(request) # Establish that the response is the type that we expect. assert isinstance(response, engine.Engine) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.data_store_ids == ['data_store_ids_value'] + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.data_store_ids == ["data_store_ids_value"] assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION assert response.industry_vertical == common.IndustryVertical.GENERIC -def test_pause_engine_rest_required_fields(request_type=engine_service.PauseEngineRequest): +def test_pause_engine_rest_required_fields( + request_type=engine_service.PauseEngineRequest, +): transport_class = transports.EngineServiceRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).pause_engine._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).pause_engine._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = 'name_value' + jsonified_request["name"] = "name_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).pause_engine._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).pause_engine._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' + assert jsonified_request["name"] == "name_value" client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = engine.Engine() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force 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, + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, } - transcode_result['body'] = pb_request + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -4174,39 +4632,48 @@ def test_pause_engine_rest_required_fields(request_type=engine_service.PauseEngi return_value = engine.Engine.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.pause_engine(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_pause_engine_rest_unset_required_fields(): - transport = transports.EngineServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.EngineServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.pause_engine._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) def test_pause_engine_rest_interceptors(null_interceptor): transport = transports.EngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EngineServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.EngineServiceRestInterceptor(), + ) client = EngineServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.EngineServiceRestInterceptor, "post_pause_engine") as post, \ - mock.patch.object(transports.EngineServiceRestInterceptor, "pre_pause_engine") as pre: + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EngineServiceRestInterceptor, "post_pause_engine" + ) as post, mock.patch.object( + transports.EngineServiceRestInterceptor, "pre_pause_engine" + ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = engine_service.PauseEngineRequest.pb(engine_service.PauseEngineRequest()) + pb_message = engine_service.PauseEngineRequest.pb( + engine_service.PauseEngineRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -4220,31 +4687,43 @@ def test_pause_engine_rest_interceptors(null_interceptor): req.return_value._content = engine.Engine.to_json(engine.Engine()) request = engine_service.PauseEngineRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = engine.Engine() - client.pause_engine(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.pause_engine( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() -def test_pause_engine_rest_bad_request(transport: str = 'rest', request_type=engine_service.PauseEngineRequest): +def test_pause_engine_rest_bad_request( + transport: str = "rest", request_type=engine_service.PauseEngineRequest +): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/engines/sample4'} + request_init = { + "name": "projects/sample1/locations/sample2/collections/sample3/engines/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): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 400 @@ -4260,16 +4739,18 @@ def test_pause_engine_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: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = engine.Engine() # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/collections/sample3/engines/sample4'} + sample_request = { + "name": "projects/sample1/locations/sample2/collections/sample3/engines/sample4" + } # get truthy value for each flattened field mock_args = dict( - name='name_value', + name="name_value", ) mock_args.update(sample_request) @@ -4279,7 +4760,7 @@ def test_pause_engine_rest_flattened(): # Convert return value to protobuf type return_value = engine.Engine.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value client.pause_engine(**mock_args) @@ -4288,10 +4769,14 @@ def test_pause_engine_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}:pause" % client.transport._host, args[1]) + assert path_template.validate( + "%s/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}:pause" + % client.transport._host, + args[1], + ) -def test_pause_engine_rest_flattened_error(transport: str = 'rest'): +def test_pause_engine_rest_flattened_error(transport: str = "rest"): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4302,21 +4787,23 @@ def test_pause_engine_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.pause_engine( engine_service.PauseEngineRequest(), - name='name_value', + name="name_value", ) def test_pause_engine_rest_error(): client = EngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) -@pytest.mark.parametrize("request_type", [ - engine_service.ResumeEngineRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + engine_service.ResumeEngineRequest, + dict, + ], +) def test_resume_engine_rest(request_type): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4324,18 +4811,20 @@ def test_resume_engine_rest(request_type): ) # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/engines/sample4'} + request_init = { + "name": "projects/sample1/locations/sample2/collections/sample3/engines/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: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = engine.Engine( - name='name_value', - display_name='display_name_value', - data_store_ids=['data_store_ids_value'], - solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, - industry_vertical=common.IndustryVertical.GENERIC, + name="name_value", + display_name="display_name_value", + data_store_ids=["data_store_ids_value"], + solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION, + industry_vertical=common.IndustryVertical.GENERIC, ) # Wrap the value into a proper Response obj @@ -4345,71 +4834,79 @@ def test_resume_engine_rest(request_type): return_value = engine.Engine.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.resume_engine(request) # Establish that the response is the type that we expect. assert isinstance(response, engine.Engine) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.data_store_ids == ['data_store_ids_value'] + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.data_store_ids == ["data_store_ids_value"] assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION assert response.industry_vertical == common.IndustryVertical.GENERIC -def test_resume_engine_rest_required_fields(request_type=engine_service.ResumeEngineRequest): +def test_resume_engine_rest_required_fields( + request_type=engine_service.ResumeEngineRequest, +): transport_class = transports.EngineServiceRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).resume_engine._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).resume_engine._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = 'name_value' + jsonified_request["name"] = "name_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).resume_engine._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).resume_engine._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' + assert jsonified_request["name"] == "name_value" client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. return_value = engine.Engine() # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force 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, + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, } - transcode_result['body'] = pb_request + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -4419,39 +4916,48 @@ def test_resume_engine_rest_required_fields(request_type=engine_service.ResumeEn return_value = engine.Engine.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.resume_engine(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_resume_engine_rest_unset_required_fields(): - transport = transports.EngineServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.EngineServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.resume_engine._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) def test_resume_engine_rest_interceptors(null_interceptor): transport = transports.EngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EngineServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.EngineServiceRestInterceptor(), + ) client = EngineServiceClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.EngineServiceRestInterceptor, "post_resume_engine") as post, \ - mock.patch.object(transports.EngineServiceRestInterceptor, "pre_resume_engine") as pre: + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EngineServiceRestInterceptor, "post_resume_engine" + ) as post, mock.patch.object( + transports.EngineServiceRestInterceptor, "pre_resume_engine" + ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = engine_service.ResumeEngineRequest.pb(engine_service.ResumeEngineRequest()) + pb_message = engine_service.ResumeEngineRequest.pb( + engine_service.ResumeEngineRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -4465,31 +4971,43 @@ def test_resume_engine_rest_interceptors(null_interceptor): req.return_value._content = engine.Engine.to_json(engine.Engine()) request = engine_service.ResumeEngineRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = engine.Engine() - client.resume_engine(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.resume_engine( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() -def test_resume_engine_rest_bad_request(transport: str = 'rest', request_type=engine_service.ResumeEngineRequest): +def test_resume_engine_rest_bad_request( + transport: str = "rest", request_type=engine_service.ResumeEngineRequest +): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/engines/sample4'} + request_init = { + "name": "projects/sample1/locations/sample2/collections/sample3/engines/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): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 400 @@ -4505,16 +5023,18 @@ def test_resume_engine_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: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = engine.Engine() # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/collections/sample3/engines/sample4'} + sample_request = { + "name": "projects/sample1/locations/sample2/collections/sample3/engines/sample4" + } # get truthy value for each flattened field mock_args = dict( - name='name_value', + name="name_value", ) mock_args.update(sample_request) @@ -4524,7 +5044,7 @@ def test_resume_engine_rest_flattened(): # Convert return value to protobuf type return_value = engine.Engine.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value client.resume_engine(**mock_args) @@ -4533,10 +5053,14 @@ def test_resume_engine_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}:resume" % client.transport._host, args[1]) + assert path_template.validate( + "%s/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}:resume" + % client.transport._host, + args[1], + ) -def test_resume_engine_rest_flattened_error(transport: str = 'rest'): +def test_resume_engine_rest_flattened_error(transport: str = "rest"): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4547,21 +5071,23 @@ def test_resume_engine_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.resume_engine( engine_service.ResumeEngineRequest(), - name='name_value', + name="name_value", ) def test_resume_engine_rest_error(): client = EngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) -@pytest.mark.parametrize("request_type", [ - engine_service.TuneEngineRequest, - dict, -]) +@pytest.mark.parametrize( + "request_type", + [ + engine_service.TuneEngineRequest, + dict, + ], +) def test_tune_engine_rest(request_type): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4569,20 +5095,22 @@ def test_tune_engine_rest(request_type): ) # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/engines/sample4'} + request_init = { + "name": "projects/sample1/locations/sample2/collections/sample3/engines/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: + with mock.patch.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 = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.tune_engine(request) @@ -4590,98 +5118,116 @@ def test_tune_engine_rest(request_type): assert response.operation.name == "operations/spam" -def test_tune_engine_rest_required_fields(request_type=engine_service.TuneEngineRequest): +def test_tune_engine_rest_required_fields( + request_type=engine_service.TuneEngineRequest, +): transport_class = transports.EngineServiceRestTransport request_init = {} request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) # verify fields with default values are dropped - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).tune_engine._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).tune_engine._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = 'name_value' + jsonified_request["name"] = "name_value" - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).tune_engine._get_unset_required_fields(jsonified_request) + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).tune_engine._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' + assert jsonified_request["name"] == "name_value" client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') + 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: + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: + with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force 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, + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, } - transcode_result['body'] = 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') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.tune_engine(request) - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_tune_engine_rest_unset_required_fields(): - transport = transports.EngineServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + transport = transports.EngineServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) unset_fields = transport.tune_engine._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) def test_tune_engine_rest_interceptors(null_interceptor): transport = transports.EngineServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EngineServiceRestInterceptor(), - ) + interceptor=None + if null_interceptor + else transports.EngineServiceRestInterceptor(), + ) client = EngineServiceClient(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.EngineServiceRestInterceptor, "post_tune_engine") as post, \ - mock.patch.object(transports.EngineServiceRestInterceptor, "pre_tune_engine") as pre: + 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.EngineServiceRestInterceptor, "post_tune_engine" + ) as post, mock.patch.object( + transports.EngineServiceRestInterceptor, "pre_tune_engine" + ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = engine_service.TuneEngineRequest.pb(engine_service.TuneEngineRequest()) + pb_message = engine_service.TuneEngineRequest.pb( + engine_service.TuneEngineRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -4692,34 +5238,48 @@ def test_tune_engine_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) request = engine_service.TuneEngineRequest() - metadata =[ + metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.tune_engine(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + client.tune_engine( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) pre.assert_called_once() post.assert_called_once() -def test_tune_engine_rest_bad_request(transport: str = 'rest', request_type=engine_service.TuneEngineRequest): +def test_tune_engine_rest_bad_request( + transport: str = "rest", request_type=engine_service.TuneEngineRequest +): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/engines/sample4'} + request_init = { + "name": "projects/sample1/locations/sample2/collections/sample3/engines/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): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 400 @@ -4735,16 +5295,18 @@ def test_tune_engine_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: + with mock.patch.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 = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/collections/sample3/engines/sample4'} + sample_request = { + "name": "projects/sample1/locations/sample2/collections/sample3/engines/sample4" + } # get truthy value for each flattened field mock_args = dict( - name='name_value', + name="name_value", ) mock_args.update(sample_request) @@ -4752,7 +5314,7 @@ def test_tune_engine_rest_flattened(): response_value = Response() response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value client.tune_engine(**mock_args) @@ -4761,10 +5323,14 @@ def test_tune_engine_rest_flattened(): # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}:tune" % client.transport._host, args[1]) + assert path_template.validate( + "%s/v1alpha/{name=projects/*/locations/*/collections/*/engines/*}:tune" + % client.transport._host, + args[1], + ) -def test_tune_engine_rest_flattened_error(transport: str = 'rest'): +def test_tune_engine_rest_flattened_error(transport: str = "rest"): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4775,14 +5341,13 @@ def test_tune_engine_rest_flattened_error(transport: str = 'rest'): with pytest.raises(ValueError): client.tune_engine( engine_service.TuneEngineRequest(), - name='name_value', + name="name_value", ) def test_tune_engine_rest_error(): client = EngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -4824,8 +5389,7 @@ def test_credentials_transport_error(): options.api_key = "api_key" with pytest.raises(ValueError): client = EngineServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() + client_options=options, credentials=ga_credentials.AnonymousCredentials() ) # It is an error to provide scopes and a transport instance. @@ -4847,6 +5411,7 @@ def test_transport_instance(): client = EngineServiceClient(transport=transport) assert client.transport is transport + def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.EngineServiceGrpcTransport( @@ -4861,28 +5426,37 @@ def test_transport_get_channel(): channel = transport.grpc_channel assert channel -@pytest.mark.parametrize("transport_class", [ - transports.EngineServiceGrpcTransport, - transports.EngineServiceGrpcAsyncIOTransport, - transports.EngineServiceRestTransport, -]) + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EngineServiceGrpcTransport, + transports.EngineServiceGrpcAsyncIOTransport, + transports.EngineServiceRestTransport, + ], +) def test_transport_adc(transport_class): # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "rest", + ], +) def test_transport_kind(transport_name): transport = EngineServiceClient.get_transport_class(transport_name)( credentials=ga_credentials.AnonymousCredentials(), ) assert transport.kind == transport_name + def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = EngineServiceClient( @@ -4893,18 +5467,21 @@ def test_transport_grpc_default(): transports.EngineServiceGrpcTransport, ) + def test_engine_service_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.EngineServiceTransport( credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" + credentials_file="credentials.json", ) def test_engine_service_base_transport(): # Instantiate the base transport. - with mock.patch('google.cloud.discoveryengine_v1alpha.services.engine_service.transports.EngineServiceTransport.__init__') as Transport: + with mock.patch( + "google.cloud.discoveryengine_v1alpha.services.engine_service.transports.EngineServiceTransport.__init__" + ) as Transport: Transport.return_value = None transport = transports.EngineServiceTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -4913,16 +5490,16 @@ def test_engine_service_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( - 'create_engine', - 'delete_engine', - 'update_engine', - 'get_engine', - 'list_engines', - 'pause_engine', - 'resume_engine', - 'tune_engine', - 'get_operation', - 'list_operations', + "create_engine", + "delete_engine", + "update_engine", + "get_engine", + "list_engines", + "pause_engine", + "resume_engine", + "tune_engine", + "get_operation", + "list_operations", ) for method in methods: with pytest.raises(NotImplementedError): @@ -4938,7 +5515,7 @@ def test_engine_service_base_transport(): # Catch all for all remaining methods and properties remainder = [ - 'kind', + "kind", ] for r in remainder: with pytest.raises(NotImplementedError): @@ -4947,25 +5524,30 @@ def test_engine_service_base_transport(): def test_engine_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.discoveryengine_v1alpha.services.engine_service.transports.EngineServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.discoveryengine_v1alpha.services.engine_service.transports.EngineServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.EngineServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", ) - load_creds.assert_called_once_with("credentials.json", + load_creds.assert_called_once_with( + "credentials.json", scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id="octopus", ) def test_engine_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.discoveryengine_v1alpha.services.engine_service.transports.EngineServiceTransport._prep_wrapped_messages') as Transport: + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.discoveryengine_v1alpha.services.engine_service.transports.EngineServiceTransport._prep_wrapped_messages" + ) as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.EngineServiceTransport() @@ -4974,14 +5556,12 @@ def test_engine_service_base_transport_with_adc(): def test_engine_service_auth_adc(): # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: + with mock.patch.object(google.auth, "default", autospec=True) as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) EngineServiceClient() adc.assert_called_once_with( scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id=None, ) @@ -4996,12 +5576,12 @@ def test_engine_service_auth_adc(): def test_engine_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: + 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',), + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id="octopus", ) @@ -5015,48 +5595,45 @@ def test_engine_service_transport_auth_adc(transport_class): ], ) def test_engine_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'] + 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: + 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) + 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 - ) + gdch_mock.with_gdch_audience.assert_called_once_with(e) @pytest.mark.parametrize( "transport_class,grpc_helpers", [ (transports.EngineServiceGrpcTransport, grpc_helpers), - (transports.EngineServiceGrpcAsyncIOTransport, grpc_helpers_async) + (transports.EngineServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) def test_engine_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( + 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"] - ) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) create_channel.assert_called_with( "discoveryengine.googleapis.com:443", credentials=creds, credentials_file=None, quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), scopes=["1", "2"], default_host="discoveryengine.googleapis.com", ssl_credentials=None, @@ -5067,10 +5644,14 @@ def test_engine_service_transport_create_channel(transport_class, grpc_helpers): ) -@pytest.mark.parametrize("transport_class", [transports.EngineServiceGrpcTransport, transports.EngineServiceGrpcAsyncIOTransport]) -def test_engine_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): +@pytest.mark.parametrize( + "transport_class", + [ + transports.EngineServiceGrpcTransport, + transports.EngineServiceGrpcAsyncIOTransport, + ], +) +def test_engine_service_grpc_transport_client_cert_source_for_mtls(transport_class): cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. @@ -5079,7 +5660,7 @@ def test_engine_service_grpc_transport_client_cert_source_for_mtls( transport_class( host="squid.clam.whelk", credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds + ssl_channel_credentials=mock_ssl_channel_creds, ) mock_create_channel.assert_called_once_with( "squid.clam.whelk:443", @@ -5100,20 +5681,21 @@ def test_engine_service_grpc_transport_client_cert_source_for_mtls( with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: transport_class( credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback + 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 + certificate_chain=expected_cert, private_key=expected_key ) + def test_engine_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.EngineServiceRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.EngineServiceRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback ) mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) @@ -5121,7 +5703,7 @@ def test_engine_service_http_transport_client_cert_source_for_mtls(): def test_engine_service_rest_lro_client(): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='rest', + transport="rest", ) transport = client.transport @@ -5135,43 +5717,58 @@ def test_engine_service_rest_lro_client(): assert transport.operations_client is transport.operations_client -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) def test_engine_service_host_no_port(transport_name): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com'), - transport=transport_name, + client_options=client_options.ClientOptions( + api_endpoint="discoveryengine.googleapis.com" + ), + transport=transport_name, ) assert client.transport._host == ( - 'discoveryengine.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com' + "discoveryengine.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://discoveryengine.googleapis.com" ) -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) def test_engine_service_host_with_port(transport_name): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='discoveryengine.googleapis.com:8000'), + client_options=client_options.ClientOptions( + api_endpoint="discoveryengine.googleapis.com:8000" + ), transport=transport_name, ) assert client.transport._host == ( - 'discoveryengine.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://discoveryengine.googleapis.com:8000' + "discoveryengine.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://discoveryengine.googleapis.com:8000" ) -@pytest.mark.parametrize("transport_name", [ - "rest", -]) + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) def test_engine_service_client_transport_session_collision(transport_name): creds1 = ga_credentials.AnonymousCredentials() creds2 = ga_credentials.AnonymousCredentials() @@ -5207,8 +5804,10 @@ def test_engine_service_client_transport_session_collision(transport_name): session1 = client1.transport.tune_engine._session session2 = client2.transport.tune_engine._session assert session1 != session2 + + def test_engine_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.EngineServiceGrpcTransport( @@ -5221,7 +5820,7 @@ def test_engine_service_grpc_transport_channel(): def test_engine_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) # Check that channel is used if provided. transport = transports.EngineServiceGrpcAsyncIOTransport( @@ -5235,12 +5834,20 @@ def test_engine_service_grpc_asyncio_transport_channel(): # 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.EngineServiceGrpcTransport, transports.EngineServiceGrpcAsyncIOTransport]) -def test_engine_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: +@pytest.mark.parametrize( + "transport_class", + [ + transports.EngineServiceGrpcTransport, + transports.EngineServiceGrpcAsyncIOTransport, + ], +) +def test_engine_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 @@ -5249,7 +5856,7 @@ def test_engine_service_transport_channel_mtls_with_client_cert_source( cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -5279,17 +5886,23 @@ def test_engine_service_transport_channel_mtls_with_client_cert_source( # 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.EngineServiceGrpcTransport, transports.EngineServiceGrpcAsyncIOTransport]) -def test_engine_service_transport_channel_mtls_with_adc( - transport_class -): +@pytest.mark.parametrize( + "transport_class", + [ + transports.EngineServiceGrpcTransport, + transports.EngineServiceGrpcAsyncIOTransport, + ], +) +def test_engine_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: + 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() @@ -5320,7 +5933,7 @@ def test_engine_service_transport_channel_mtls_with_adc( def test_engine_service_grpc_lro_client(): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', + transport="grpc", ) transport = client.transport @@ -5337,7 +5950,7 @@ def test_engine_service_grpc_lro_client(): def test_engine_service_grpc_lro_async_client(): client = EngineServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), - transport='grpc_asyncio', + transport="grpc_asyncio", ) transport = client.transport @@ -5355,7 +5968,13 @@ def test_collection_path(): project = "squid" location = "clam" collection = "whelk" - expected = "projects/{project}/locations/{location}/collections/{collection}".format(project=project, location=location, collection=collection, ) + expected = ( + "projects/{project}/locations/{location}/collections/{collection}".format( + project=project, + location=location, + collection=collection, + ) + ) actual = EngineServiceClient.collection_path(project, location, collection) assert expected == actual @@ -5372,12 +5991,18 @@ def test_parse_collection_path(): actual = EngineServiceClient.parse_collection_path(path) assert expected == actual + def test_engine_path(): project = "cuttlefish" location = "mussel" collection = "winkle" engine = "nautilus" - expected = "projects/{project}/locations/{location}/collections/{collection}/engines/{engine}".format(project=project, location=location, collection=collection, engine=engine, ) + expected = "projects/{project}/locations/{location}/collections/{collection}/engines/{engine}".format( + project=project, + location=location, + collection=collection, + engine=engine, + ) actual = EngineServiceClient.engine_path(project, location, collection, engine) assert expected == actual @@ -5395,9 +6020,12 @@ def test_parse_engine_path(): actual = EngineServiceClient.parse_engine_path(path) assert expected == actual + def test_common_billing_account_path(): billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) actual = EngineServiceClient.common_billing_account_path(billing_account) assert expected == actual @@ -5412,9 +6040,12 @@ def test_parse_common_billing_account_path(): actual = EngineServiceClient.parse_common_billing_account_path(path) assert expected == actual + def test_common_folder_path(): folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) + expected = "folders/{folder}".format( + folder=folder, + ) actual = EngineServiceClient.common_folder_path(folder) assert expected == actual @@ -5429,9 +6060,12 @@ def test_parse_common_folder_path(): actual = EngineServiceClient.parse_common_folder_path(path) assert expected == actual + def test_common_organization_path(): organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) + expected = "organizations/{organization}".format( + organization=organization, + ) actual = EngineServiceClient.common_organization_path(organization) assert expected == actual @@ -5446,9 +6080,12 @@ def test_parse_common_organization_path(): actual = EngineServiceClient.parse_common_organization_path(path) assert expected == actual + def test_common_project_path(): project = "winkle" - expected = "projects/{project}".format(project=project, ) + expected = "projects/{project}".format( + project=project, + ) actual = EngineServiceClient.common_project_path(project) assert expected == actual @@ -5463,10 +6100,14 @@ def test_parse_common_project_path(): actual = EngineServiceClient.parse_common_project_path(path) assert expected == actual + def test_common_location_path(): project = "scallop" location = "abalone" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) actual = EngineServiceClient.common_location_path(project, location) assert expected == actual @@ -5486,14 +6127,18 @@ def test_parse_common_location_path(): def test_client_with_default_client_info(): client_info = gapic_v1.client_info.ClientInfo() - with mock.patch.object(transports.EngineServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.EngineServiceTransport, "_prep_wrapped_messages" + ) as prep: client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) - with mock.patch.object(transports.EngineServiceTransport, '_prep_wrapped_messages') as prep: + with mock.patch.object( + transports.EngineServiceTransport, "_prep_wrapped_messages" + ) as prep: transport_class = EngineServiceClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), @@ -5501,29 +6146,41 @@ def test_client_with_default_client_info(): ) prep.assert_called_once_with(client_info) + @pytest.mark.asyncio async def test_transport_close_async(): client = EngineServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) - with mock.patch.object(type(getattr(client.transport, "grpc_channel")), "close") as close: + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: async with client: close.assert_not_called() close.assert_called_once() -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): +def test_get_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.GetOperationRequest +): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'}, request) + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6" + }, + 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): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 400 @@ -5531,19 +6188,25 @@ def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=op req.return_value = response_value client.get_operation(request) -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) def test_get_operation_rest(request_type): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6'} + request_init = { + "name": "projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5/operations/sample6" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = operations_pb2.Operation() @@ -5552,7 +6215,7 @@ def test_get_operation_rest(request_type): response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.get_operation(request) @@ -5560,17 +6223,27 @@ def test_get_operation_rest(request_type): # Establish that the response is the type that we expect. assert isinstance(response, operations_pb2.Operation) -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + +def test_list_operations_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.ListOperationsRequest +): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'}, request) + request = json_format.ParseDict( + { + "name": "projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5" + }, + 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): + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 400 @@ -5578,19 +6251,25 @@ def test_list_operations_rest_bad_request(transport: str = 'rest', request_type= req.return_value = response_value client.list_operations(request) -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) def test_list_operations_rest(request_type): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {'name': 'projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5'} + request_init = { + "name": "projects/sample1/locations/sample2/collections/sample3/dataStores/sample4/branches/sample5" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: + with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = operations_pb2.ListOperationsResponse() @@ -5599,7 +6278,7 @@ def test_list_operations_rest(request_type): response_value.status_code = 200 json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.list_operations(request) @@ -5610,7 +6289,8 @@ def test_list_operations_rest(request_type): def test_get_operation(transport: str = "grpc"): client = EngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5629,10 +6309,13 @@ def test_get_operation(transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, operations_pb2.Operation) + + @pytest.mark.asyncio async def test_get_operation_async(transport: str = "grpc"): client = EngineServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5654,6 +6337,7 @@ async def test_get_operation_async(transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, operations_pb2.Operation) + def test_get_operation_field_headers(): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5676,7 +6360,12 @@ def test_get_operation_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + @pytest.mark.asyncio async def test_get_operation_field_headers_async(): client = EngineServiceAsyncClient( @@ -5701,7 +6390,11 @@ async def test_get_operation_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + def test_get_operation_from_dict(): client = EngineServiceClient( @@ -5718,6 +6411,8 @@ def test_get_operation_from_dict(): } ) call.assert_called() + + @pytest.mark.asyncio async def test_get_operation_from_dict_async(): client = EngineServiceAsyncClient( @@ -5739,7 +6434,8 @@ async def test_get_operation_from_dict_async(): def test_list_operations(transport: str = "grpc"): client = EngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5758,10 +6454,13 @@ def test_list_operations(transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, operations_pb2.ListOperationsResponse) + + @pytest.mark.asyncio async def test_list_operations_async(transport: str = "grpc"): client = EngineServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5783,6 +6482,7 @@ async def test_list_operations_async(transport: str = "grpc"): # Establish that the response is the type that we expect. assert isinstance(response, operations_pb2.ListOperationsResponse) + def test_list_operations_field_headers(): client = EngineServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5805,7 +6505,12 @@ def test_list_operations_field_headers(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + @pytest.mark.asyncio async def test_list_operations_field_headers_async(): client = EngineServiceAsyncClient( @@ -5830,7 +6535,11 @@ async def test_list_operations_field_headers_async(): # Establish that the field header was sent. _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + def test_list_operations_from_dict(): client = EngineServiceClient( @@ -5847,6 +6556,8 @@ def test_list_operations_from_dict(): } ) call.assert_called() + + @pytest.mark.asyncio async def test_list_operations_from_dict_async(): client = EngineServiceAsyncClient( @@ -5874,23 +6585,24 @@ def test_transport_close(): for transport, close_name in transports.items(): client = EngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport + credentials=ga_credentials.AnonymousCredentials(), transport=transport ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with mock.patch.object( + type(getattr(client.transport, close_name)), "close" + ) as close: with client: close.assert_not_called() close.assert_called_once() + def test_client_ctx(): transports = [ - 'rest', - 'grpc', + "rest", + "grpc", ] for transport in transports: client = EngineServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport + credentials=ga_credentials.AnonymousCredentials(), transport=transport ) # Test client calls underlying transport. with mock.patch.object(type(client.transport), "close") as close: @@ -5899,10 +6611,14 @@ def test_client_ctx(): pass close.assert_called() -@pytest.mark.parametrize("client_class,transport_class", [ - (EngineServiceClient, transports.EngineServiceGrpcTransport), - (EngineServiceAsyncClient, transports.EngineServiceGrpcAsyncIOTransport), -]) + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (EngineServiceClient, transports.EngineServiceGrpcTransport), + (EngineServiceAsyncClient, transports.EngineServiceGrpcAsyncIOTransport), + ], +) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True